Skip to content

fix: skip invalid prompts in Pi supervision handlers - #7236

Open
Lykhoyda wants to merge 6 commits into
kunchenguid:mainfrom
Lykhoyda:fm/firstmate-branch-prompt-trim
Open

Lykhoyda wants to merge 6 commits into
kunchenguid:mainfrom
Lykhoyda:fm/firstmate-branch-prompt-trim

Conversation

@Lykhoyda

@Lykhoyda Lykhoyda commented Oct 13, 2026 •

Copy link
Copy Markdown

What Changed

  • Guard both Pi supervision before_agent_start handlers against missing or non-string user prompts.
  • Add regression cases for promptless and non-string events, including an assertion that they never enter captain mirror context.
  • Clarify that captain prompts are trimmed before staging and invalid prompts are skipped.

Risk Assessment

✅ Low: The bounded prompt guards prevent invalid prompt consumption while preserving custom-turn bookkeeping, ownership checks, and valid captain-message mirroring.

Testing

Live SDK scenarios and both focused regressions passed; logs and the driver were retained. No visual evidence was needed for this event-handling change. Full-suite, lint, CI and real-provider/TUI checks were not run; provider responses were deterministic local fixtures.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
An extension starts a promptless custom turn; Pi completes it without extension errors. ✅ pass live pi-live.log: PROMPTLESS_CUSTOM_TURN
Malformed user events reach Pi's real extension runner; undefined, null, numeric and object prompts cause no crash or captain mirror entry. ✅ pass live pi-live.log: MALFORMED_USER_EVENTS; pi-base.log: BASE_REGRESSION
A captain submits text with surrounding whitespace; the turn completes and the branch persists the trimmed captain text exactly once. ✅ pass live pi-live.log: CAPTAIN_USER_TURN and BRANCH_MIRROR
Evidence: Live Pi turns and persisted branch mirror

Source: Live Pi turns and persisted branch mirror

EXTENSIONS [
  '~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/fm-branch-supervision.ts',
  '~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/fm-primary-pi-watch.ts',
  '<inline:lab-bus-probe>'
] LOAD_ERRORS []
PROMPTLESS_CUSTOM_TURN completed; provider requests=1; extension errors=0
MALFORMED_USER_EVENTS undefined/null/number/object accepted by real runner without extension errors
CAPTAIN_USER_TURN completed; provider requests=2; extension errors=0
BRANCH_MIRROR ["[main] LAB_TURN_COMPLETED","[captain] Captain normal live prompt","[main] LAB_TURN_COMPLETED"]
CAPTAIN_MIRROR trimmed once; custom/malformed inputs absent
Evidence: Base-commit trim crash reproduction

Source: Base-commit trim crash reproduction

EXTENSIONS [
  '~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/local-base-branch.ts',
  '~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/local-base-watch.ts',
  '<inline:lab-bus-probe>'
] LOAD_ERRORS []
PROMPTLESS_CUSTOM_TURN completed; provider requests=1; extension errors=0
EXTENSION_ERROR {
  extensionPath: '~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/local-base-branch.ts',
  event: 'before_agent_start',
  error: "Cannot read properties of undefined (reading 'trim')",
  stack: "TypeError: Cannot read properties of undefined (reading 'trim')\n" +
    '    at ~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/local-base-branch.ts:1690:34\n' +
    '    at process.processTicksAndRejections (node:internal/process/task_queues:104:5)\n' +
    '    at async ExtensionRunner.emitBeforeAgentStart (file://~/.nvm/versions/node/v24.14.0/lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-TJXZSVTD.js:523:27033)\n' +
    '    at async file://~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.test-live-pi/driver.mjs:39:46\n' +
    '    at async file://~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.test-live-pi/driver.mjs:35:1'
}
EXTENSION_ERROR {
  extensionPath: '~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/local-base-branch.ts',
  event: 'before_agent_start',
  error: "Cannot read properties of null (reading 'trim')",
  stack: "TypeError: Cannot read properties of null (reading 'trim')\n" +
    '    at ~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/local-base-branch.ts:1690:34\n' +
    '    at process.processTicksAndRejections (node:internal/process/task_queues:104:5)\n' +
    '    at async ExtensionRunner.emitBeforeAgentStart (file://~/.nvm/versions/node/v24.14.0/lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-TJXZSVTD.js:523:27033)\n' +
    '    at async file://~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.test-live-pi/driver.mjs:39:46\n' +
    '    at async file://~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.test-live-pi/driver.mjs:35:1'
}
EXTENSION_ERROR {
  extensionPath: '~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/local-base-branch.ts',
  event: 'before_agent_start',
  error: 'event.prompt.trim is not a function',
  stack: 'TypeError: event.prompt.trim is not a function\n' +
    '    at ~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/local-base-branch.ts:1690:34\n' +
    '    at process.processTicksAndRejections (node:internal/process/task_queues:104:5)\n' +
    '    at async ExtensionRunner.emitBeforeAgentStart (file://~/.nvm/versions/node/v24.14.0/lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-TJXZSVTD.js:523:27033)\n' +
    '    at async file://~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.test-live-pi/driver.mjs:39:46\n' +
    '    at async file://~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.test-live-pi/driver.mjs:35:1'
}
EXTENSION_ERROR {
  extensionPath: '~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/local-base-branch.ts',
  event: 'before_agent_start',
  error: 'event.prompt.trim is not a function',
  stack: 'TypeError: event.prompt.trim is not a function\n' +
    '    at ~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.pi/extensions/local-base-branch.ts:1690:34\n' +
    '    at process.processTicksAndRejections (node:internal/process/task_queues:104:5)\n' +
    '    at async ExtensionRunner.emitBeforeAgentStart (file://~/.nvm/versions/node/v24.14.0/lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-TJXZSVTD.js:523:27033)\n' +
    '    at async file://~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.test-live-pi/driver.mjs:39:46\n' +
    '    at async file://~/.no-mistakes/worktrees/85e4fc3a5051/01M4VEF2V9HW3RQZZK5TD3QPZD/.test-live-pi/driver.mjs:35:1'
}
BASE_REGRESSION reproduced trim failure via real extension runner
Evidence: Disposable real-SDK validation driver

Source: Disposable real-SDK validation driver

import {createServer} from 'node:http';
import {mkdirSync,writeFileSync,readFileSync,readdirSync} from 'node:fs';
import {resolve} from 'node:path';
import assert from 'node:assert/strict';
const root=process.cwd(), home=resolve('.test-live-pi/home'), agentDir=resolve('.test-live-pi/agent');
process.env.FM_HOME=home; process.env.PI_CODING_AGENT_DIR=agentDir; process.env.PI_OFFLINE='1';
for(const k of ['FM_ROOT_OVERRIDE','FM_STATE_OVERRIDE','FM_CONFIG_OVERRIDE','FM_DATA_OVERRIDE','FM_PROJECTS_OVERRIDE','FM_GATE_REFUSE_BYPASS']) delete process.env[k];
mkdirSync(agentDir,{recursive:true});
writeFileSync(home+'/state/.lock',process.pid+'\n');
writeFileSync(home+'/state/.wake-queue','');
const requests=[];
const server=createServer(async(req,res)=>{
 let body='';for await(const c of req)body+=c;
 const request=JSON.parse(body);requests.push(request);
 res.writeHead(200,{'Content-Type':'text/event-stream'});
 const chunk=(delta,finish_reason=null)=>res.write('data: '+JSON.stringify({id:'lab',object:'chat.completion.chunk',created:1,model:'lab',choices:[{index:0,delta,finish_reason}]})+'\n\n');
 if(request.tools?.some(t=>t.function?.name==='fm_branch_report') && !request.messages.some(m=>m.role==='tool')) {
 chunk({role:'assistant',tool_calls:[{index:0,id:'lab-report',type:'function',function:{name:'fm_branch_report',arguments:JSON.stringify({task:'lab',verdict:'routine',summary:'Disposable lab observation recorded',wake:'signal: lab.status'})}}]});chunk({},'tool_calls');
 } else {chunk({role:'assistant',content:'LAB_TURN_COMPLETED'});chunk({},'stop');}res.end('data: [DONE]\n\n');
});
await new Promise(r=>server.listen(0,'127.0.0.1',r));
writeFileSync(agentDir+'/models.json',JSON.stringify({providers:{lab:{baseUrl:`http://127.0.0.1:${server.address().port}/v1`,api:'openai-completions',apiKey:'disposable-local',models:[{id:'lab',contextWindow:128000,maxTokens:2000}]}}}));
writeFileSync(home+'/config/supervision-branch-model','lab/lab\n');
const sdk=await import('~/.nvm/versions/node/v24.14.0/lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/index.js');
const runtime=await sdk.ModelRuntime.create({authPath:agentDir+'/auth.json',modelsPath:agentDir+'/models.json',modelsStorePath:agentDir+'/catalog',allowModelNetwork:false});
let bus;
const settings=sdk.SettingsManager.create(root,agentDir);
const loader=new sdk.DefaultResourceLoader({cwd:root,agentDir,settingsManager:settings,noExtensions:true,noSkills:true,noPromptTemplates:true,noThemes:true,noContextFiles:true,extensionFactories:[{name:"lab-bus-probe",factory:pi=>{bus=pi.events}}],additionalExtensionPaths:[root+'/.pi/extensions/'+(process.env.LAB_BASE?'local-base-branch.ts':'fm-branch-supervision.ts'),root+'/.pi/extensions/'+(process.env.LAB_BASE?'local-base-watch.ts':'fm-primary-pi-watch.ts')]});
await loader.reload();
const {session,extensionsResult}=await sdk.createAgentSession({cwd:root,agentDir,modelRuntime:runtime,model:runtime.getModel('lab','lab'),resourceLoader:loader,settingsManager:settings,sessionManager:sdk.SessionManager.create(root,agentDir+'/sessions'),tools:[]});
const errors=[];
console.log('EXTENSIONS',extensionsResult.extensions.map(e=>e.path), 'LOAD_ERRORS',extensionsResult.errors);
assert.equal(extensionsResult.errors.length,0);
await session.bindExtensions({onError:e=>{errors.push(e);console.log('EXTENSION_ERROR',e)}});
await (async()=>{try {
 await session.sendCustomMessage({customType:'lab-injected',content:'Injected continuation without captain prompt',display:false},{triggerTurn:true});
 assert.equal(errors.length,0);assert.equal(requests.length,1);
 console.log('PROMPTLESS_CUSTOM_TURN completed; provider requests=1; extension errors=0');
 for(const prompt of [undefined,null,42,{}]) await session.extensionRunner.emitBeforeAgentStart({messageType:'user',prompt},{basePrompt:'lab'});
 if(process.env.LAB_BASE){assert(errors.some(e=>String(e.error||e.message||JSON.stringify(e)).includes('trim')));console.log('BASE_REGRESSION reproduced trim failure via real extension runner');} else assert.equal(errors.length,0); if(!process.env.LAB_BASE)console.log('MALFORMED_USER_EVENTS undefined/null/number/object accepted by real runner without extension errors');
 if(process.env.LAB_BASE){return;}
 await session.prompt('  Captain normal live prompt  ');
 assert.equal(errors.length,0);assert.equal(requests.length,2);
 console.log('CAPTAIN_USER_TURN completed; provider requests=2; extension errors=0');
 // Inject a harmless signal into the disposable queue so the real branch constructs and flushes its mirror.
 writeFileSync(home+'/state/.wake-queue','1\t1\tsignal\tlab.status\tsignal: lab.status\n');
 writeFileSync(home+'/state/lab.meta','project='+home+'/projects/approved\nwindow=fm-lab\n');
 const offer={message:'signal: lab.status',projects:[],heartbeat:false,eligible:true,awayOnly:false,accepted:false,accept(p){this.accepted=true;this.settlement=p}};
 bus.emit('fm-branch-supervision:dispatch',offer);
 assert.equal(offer.accepted,true);await offer.settlement;
 const pointer=readFileSync(home+'/state/.branch-session','utf8').trim();
 const entries=readFileSync(pointer,'utf8').trim().split('\n').map(s=>JSON.parse(s));
 const mirror=entries.filter(e=>e.type==='custom_message'&&e.customType==='fm-main-mirror').map(e=>e.content);
 console.log('BRANCH_MIRROR',JSON.stringify(mirror));
 assert.equal(mirror.filter(s=>s==='[captain] Captain normal live prompt').length,1);
 assert.equal(mirror.filter(s=>s.startsWith('[captain] ')).length,1);
 assert.equal(errors.length,0);
 console.log('CAPTAIN_MIRROR trimmed once; custom/malformed inputs absent');
} finally {await session.extensionRunner.emit({type:'session_shutdown'});session.dispose();server.close();}})();

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
An extension triggers a promptless Pi turn without crashing before_agent_start ✅ pass live pi-live.txt; pi-base-reproduction.txt
Missing, null, numeric, object, empty, and whitespace prompts cause no errors or captain mirror entries ✅ pass live pi-live.txt: MALFORMED_RESULT and PERSISTED_MIRROR
A normal captain prompt is trimmed and mirrored exactly once after a promptless turn ✅ pass live pi-live.txt: PERSISTED_MIRROR
An operational watcher prompt remains excluded from captain dialog ✅ pass live pi-live.txt: MIRROR_RESULT
  • pi --help to verify the installed harness interface
  • bin/fm-lab-home.sh create &#34;$PWD/.phase-live/home&#34; and real Pi SDK 1.2.0 scenarios on Node 24.14.0 with isolated configuration and a local HTTP/SSE provider
  • AgentSession.sendCustomMessage(..., {triggerTurn: true}), AgentSession.prompt(...), and malformed events through the real ExtensionRunner.emit(...)
  • Real supervision branch heartbeat, report-tool execution, and persisted session JSONL mirror assertions
  • Same live driver against the base extension from git show 7df545bf:.pi/extensions/fm-branch-supervision.ts, reproducing the exact trim error
  • Focused test_requested_healthy_outcome_and_unsolicited_routine_outcome_delivery: initial Node 26 timeout; unchanged Node 24 rerun passed
  • Removed disposable lab files and confirmed clean worktree with git status --short

✅ No issues found.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
An extension starts a promptless custom turn; Pi completes it without extension errors. ✅ pass live pi-live.log: PROMPTLESS_CUSTOM_TURN
Malformed user events reach Pi's real extension runner; undefined, null, numeric and object prompts cause no crash or captain mirror entry. ✅ pass live pi-live.log: MALFORMED_USER_EVENTS; pi-base.log: BASE_REGRESSION
A captain submits text with surrounding whitespace; the turn completes and the branch persists the trimmed captain text exactly once. ✅ pass live pi-live.log: CAPTAIN_USER_TURN and BRANCH_MIRROR
  • test_requested_healthy_outcome_and_unsolicited_routine_outcome_delivery via a temporary focused runner
  • test_pi_streaming_time_delivery_keeps_the_successor_chain via a temporary focused runner
  • Real installed Pi 1.2.0 SDK with both tracked extensions, Node 24.14.0, an isolated lab home and a disposable local provider endpoint
  • LAB_BASE=1 node .test-live-pi/driver.mjs: reproduced base-commit trim errors
  • node .test-live-pi/driver.mjs: verified promptless completion, malformed-event guards and persisted captain mirror
  • Confirmed target HEAD and clean working tree after cleanup
✅ **Document** - passed

✅ No issues found.

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

✅ No issues found.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: first look at #7236, head a0927d6d, vs main 7df545bf (still red on Pi 1.2 BeforeAgentStartEvent.prompt / fm-pi-primary-types). Thanks @Lykhoyda.

What I reviewed: tip is a two-line runtime guard in .pi/extensions/fm-branch-supervision.ts — typeof event.prompt === \"string\" ? event.prompt : \"\" before .trim(), so promptless / non-string before_agent_start turns no longer crash the supervision branch; docs + a focused test for missing/null/number/object prompts. No workflows, secrets, or network. Fork CI approved: CI 38462883791, Require no-mistakes 38462884236.

Attestation: MATCH. Live: 4/4 against real Pi SDK 1.2.0 (promptless turn, malformed prompts, captain mirror once, operational excluded), including base reproduction of the trim crash on 7df545bf.

Contract-class: restore. The existing default before_agent_start captain-mirror path was specified and broken on promptless turns; this restores that path without adding a new always-on surface.

VISION (per rule):

  • One captain, one interface — aligns (avoids a silent/crash failure under load).
  • Authority is explicit — aligns (no new consent surface).
  • Scripts own the mechanics — aligns (tiny typed guard; judgment unchanged).
  • A restart is a non-event — aligns.
  • Delegation with a spine — aligns.
  • The fleet outlives any vendor — aligns (defends the Pi adapter against vendor prompt-shape drift; related to the main-red Pi 1.2 type family, but this is a runtime coerce, not the types-only fix).
  • Scope — aligns.

Next: waiting on CI. Main is red, so no merge this wake even if this tip goes green — stamp auto-merge-next-if-green once CI is green on a current base. Overlap: #6760 also touches fm-branch-supervision.ts; land only one edit set at a time if both are ready.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: re-check of #7236 on newer head 40474e80 (was a0927d6d) vs main 7df545bf (still red). Thanks @Lykhoyda.

What changed since last stamp: the same runtime coerce now also guards fm-primary-pi-watch.ts (\"prompt\" in event && typeof === \"string\" before consumeWake), matching the branch-supervision fix, plus tests on both sides. That is exactly the narrowing main needs for fm-pi-primary-types (TS2339 on BeforeAgentStartCustomEvent). No workflows/secrets/network. Fork CI approved: CI 38484216928, Require no-mistakes 38484216806.

Attestation: MATCH. Live: 4/4 against real Pi SDK (unchanged go).

Contract-class: restore (reconfirmed). Existing default before_agent_start captain-mirror / wake-consume path was specified and broken on promptless turns; this restores it without a new always-on surface.

VISION: One captain / Authority / Scripts / Restart / Spine / Vendor / Scope — all align.

Main-red note: this tip should clear parallel 1 (fm-pi-primary-types). Serial 4 (fm-remote-reply NUL-bearing line) is unrelated, so this tip alone is not yet the full green path for main — no merge this wake. Stamp auto-merge-next-if-green once tip CI is green and main allows (restore + safe).

Overlap: #7176 carries a weaker early-return on the same two files; prefer this restore for that edit set.

…consumers and added a watcher regression. Watcher suite, lint, and whitespace checks passed. Serial shard 4 failed in unchanged remote-reply code; its NUL-byte case passed locally. Limitations: tsc unavailable; Node 24 branch suite timed out; remaining remote tests stopped. CI rerun remains unverified
@Lykhoyda
Lykhoyda force-pushed the fm/firstmate-branch-prompt-trim branch from 40474e8 to d1d4cf4 Compare October 14, 2026 07:51
@Lykhoyda Lykhoyda changed the title fix: prevent Pi branch supervision crashes on promptless turns fix: skip invalid prompts in Pi supervision handlers Oct 14, 2026
@Lykhoyda

Copy link
Copy Markdown
Author

Could a maintainer rerun the cancelled Behavior portable serial 2 job? It was cancelled mid-run; the other required checks passed, and I do not have permission to rerun it.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @Lykhoyda, and sorry about the cancelled job. I re-ran it for you. Re-check on head d1d4cf45 against main 0397cb2b, which is green again.

What I reviewed: the diff is still just the two typeof event.prompt !== "string" guards in fm-branch-supervision.ts and fm-primary-pi-watch.ts, plus the doc line and the regression cases. No workflows, secrets or network changes. The three commits that landed on main since your base (8c9c67de, including #7233 and #6341) touch none of these files.

Contract-class: restore (reconfirmed). The existing default before_agent_start mirror and wake-consume path was specified and crashed on promptless or non-string turns. Your base reproduction shows it. This restores that path without adding a new surface.

VISION: One captain / Authority / Scripts / Restart / Spine / Vendor / Scope all align.

CI: every required job is green except Behavior portable serial 2. On both attempts it printed ALL TESTS PASSED and was then cancelled at the job's 30-minute timeout, so it's a runner-time limit, not a test failure. I've re-run it once more. Nothing is waiting on you. If that job comes back green and the PR is still mergeable, this can auto-merge on the next pass. If it keeps timing out, a rebase onto current main would get a fresh full run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants