@agimon-ai/doompi-autocompact 0.0.1-alpha.24 → 0.0.1-alpha.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -48,7 +48,7 @@ import { installAutocompactRuntime, thresholdTokens } from '@agimon-ai/doompi-au
48
48
  import type { AutocompactPass } from '@agimon-ai/doompi-autocompact';
49
49
  ```
50
50
 
51
- `installAutocompactRuntime` installs package resources into a supplied package-local Cordis root. Normal Pi activation should use the discovered `extensions/pi` entry. `thresholdTokens` exposes the threshold policy for hosts that need to preview or test checkpoint boundaries.
51
+ `installAutocompactRuntime` installs package resources into the package plugin fiber supplied by the shared runner-scoped Cordis host. Normal Pi activation should use the discovered `extensions/pi` entry, which connects to that host and disposes its plugin fiber before releasing the host lease. `thresholdTokens` exposes the threshold policy for hosts that need to preview or test checkpoint boundaries.
52
52
 
53
53
  ## Development
54
54
 
@@ -1,4 +1,4 @@
1
- const e=require(`../../types/constants.cjs`),t=require(`../compaction/policy.cjs`),n=require(`../../services/summarizationModel.cjs`),r=require(`../telemetry/logSinkTelemetry.cjs`);let i=require(`node:fs`),a=require(`node:path`),o=require(`node:url`),s=require(`node:worker_threads`),c=require(`@agimon-ai/doompi-config`),l=require(`@agimon-ai/doompi-task/store/paths`),u=require(`@agimon-ai/doompi-task/store/taskStore`),d=require(`@agimon-ai/doompi-team/api/team-snapshot`),f=require(`@agimon-ai/doompi-ui/footer`),p=require(`@deepseek-ai/cordis`),m=require(`@earendil-works/pi-coding-agent`);const h=`@root`,g=`doom-autocompact`,_={waiting:`waiting`,checkpointPending:`checkpoint_pending`,checkpointReady:`checkpoint_ready`,compacting:`compacting`};function v(e,t={}){return{"pi.session.id":e.sessionManager.getSessionId(),...t}}function y(e){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r?.type!==`custom`||r.customType!==`doom-autocompact-state`)continue;let i=t.parseState(r.data);if(i)return i}}function b(e){for(let t of e.sessionManager.getBranch().toReversed())if(!(t.type===`custom`&&t.customType===`doom-autocompact-state`)&&t.type!==`label`)return t.id;return h}function x(e){return e instanceof Error?e.message:String(e)}function S(e){for(let t of e.toReversed()){if(t.type!==`custom`||t.customType!==`agent-harness-plan-document`)continue;if(!t.data||typeof t.data!=`object`)return;let e=t.data;return typeof e.content!=`string`||typeof e.path!=`string`?void 0:{content:e.content,path:e.path}}}function C(e){let t=[];try{let n=new u.TaskStore({cwd:e.cwd,report:{error:(e,n)=>t.push(`${e}: ${x(n)}`),warn:(e,n)=>t.push(`${e}: ${x(n)}`),event:()=>void 0}});return n.configureSession((0,l.resolveSessionKey)(e.sessionManager.getSessionId())),{tasks:n.read().tasks,...t.length>0?{error:t.join(`; `)}:{}}}catch(e){return{tasks:[],error:x(e)}}}function w(){try{let e=(0,d.readActiveTeamSnapshot)();return e?{members:e.members}:{}}catch(e){return{error:x(e)}}}function T(e){return e.tasks.filter(e=>e.status===`pending`||e.status===`in_progress`||e.status===`failed`).map(e=>({id:e.id,status:e.status,subject:e.subject,...e.activeForm?{activeForm:e.activeForm}:{},...e.owner?{owner:e.owner}:{},...e.blockedBy?.length?{blockedBy:e.blockedBy}:{},...e.delegation?{delegation:{agent:e.delegation.agent,state:e.delegation.state,...e.delegation.result?.error?{error:e.delegation.result.error}:{}}}:{}}))}function E(e,t){let n=e.map(e=>{let t=[e.activeForm?`active: ${e.activeForm}`:void 0,e.owner?`owner: ${e.owner}`:void 0,e.blockedBy?.length?`blocked by: ${e.blockedBy.join(`, `)}`:void 0,e.delegation?`delegation: ${e.delegation.agent} (${e.delegation.state})`:void 0,e.delegation?.error?`error: ${e.delegation.error}`:void 0].filter(e=>!!e);return`- #${e.id} [${e.status}] ${e.subject}${t.length>0?` | ${t.join(` | `)}`:``}`});return t&&n.push(`- Task snapshot error: ${t}`),n.length>0?n.join(`
1
+ const e=require(`../../types/constants.cjs`),t=require(`../compaction/policy.cjs`),n=require(`../../services/summarizationModel.cjs`),r=require(`../telemetry/logSinkTelemetry.cjs`);let i=require(`node:fs`),a=require(`node:path`),o=require(`node:url`),s=require(`node:worker_threads`),c=require(`@agimon-ai/doompi-config`),l=require(`@agimon-ai/doompi-extension-contracts/cordis-host`),u=require(`@agimon-ai/doompi-task/store/paths`),d=require(`@agimon-ai/doompi-task/store/taskStore`),f=require(`@agimon-ai/doompi-team/api/team-snapshot`),p=require(`@agimon-ai/doompi-extension-contracts/ui-hub`),m=require(`@earendil-works/pi-coding-agent`);const h=`@root`,g=`doom-autocompact`,_={waiting:`waiting`,checkpointPending:`checkpoint_pending`,checkpointReady:`checkpoint_ready`,compacting:`compacting`};function v(e,t={}){return{"pi.session.id":e.sessionManager.getSessionId(),...t}}function y(e){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r?.type!==`custom`||r.customType!==`doom-autocompact-state`)continue;let i=t.parseState(r.data);if(i)return i}}function b(e){for(let t of e.sessionManager.getBranch().toReversed())if(!(t.type===`custom`&&t.customType===`doom-autocompact-state`)&&t.type!==`label`)return t.id;return h}function x(e){return e instanceof Error?e.message:String(e)}function S(e){for(let t of e.toReversed()){if(t.type!==`custom`||t.customType!==`agent-harness-plan-document`)continue;if(!t.data||typeof t.data!=`object`)return;let e=t.data;return typeof e.content!=`string`||typeof e.path!=`string`?void 0:{content:e.content,path:e.path}}}function C(e){let t=[];try{let n=new d.TaskStore({cwd:e.cwd,report:{error:(e,n)=>t.push(`${e}: ${x(n)}`),warn:(e,n)=>t.push(`${e}: ${x(n)}`),event:()=>void 0}});return n.configureSession((0,u.resolveSessionKey)(e.sessionManager.getSessionId())),{tasks:n.read().tasks,...t.length>0?{error:t.join(`; `)}:{}}}catch(e){return{tasks:[],error:x(e)}}}function w(){try{let e=(0,f.readActiveTeamSnapshot)();return e?{members:e.members}:{}}catch(e){return{error:x(e)}}}function T(e){return e.tasks.filter(e=>e.status===`pending`||e.status===`in_progress`||e.status===`failed`).map(e=>({id:e.id,status:e.status,subject:e.subject,...e.activeForm?{activeForm:e.activeForm}:{},...e.owner?{owner:e.owner}:{},...e.blockedBy?.length?{blockedBy:e.blockedBy}:{},...e.delegation?{delegation:{agent:e.delegation.agent,state:e.delegation.state,...e.delegation.result?.error?{error:e.delegation.result.error}:{}}}:{}}))}function E(e,t){let n=e.map(e=>{let t=[e.activeForm?`active: ${e.activeForm}`:void 0,e.owner?`owner: ${e.owner}`:void 0,e.blockedBy?.length?`blocked by: ${e.blockedBy.join(`, `)}`:void 0,e.delegation?`delegation: ${e.delegation.agent} (${e.delegation.state})`:void 0,e.delegation?.error?`error: ${e.delegation.error}`:void 0].filter(e=>!!e);return`- #${e.id} [${e.status}] ${e.subject}${t.length>0?` | ${t.join(` | `)}`:``}`});return t&&n.push(`- Task snapshot error: ${t}`),n.length>0?n.join(`
2
2
  `):`(no active tasks)`}function D(e){let t=(e.members??[]).map(e=>{let t=[`role: ${e.role}`,e.agent?`agent: ${e.agent}`:void 0,e.runId?`run: ${e.runId}`:void 0,e.task?`task ${e.task.id}: ${e.task.subject}`:void 0].filter(e=>!!e);return`- ${e.name} | ${t.join(` | `)}`});return e.error&&t.push(`- Team snapshot error: ${e.error}`),t.length>0?t.join(`
3
3
  `):e.members?`(no active team members)`:`(team runtime unavailable)`}function ee(e,t,n){let r=S(e);return{...r?{planPath:r.path}:{},tasks:T(t),...t.error?{taskError:t.error}:{},teamAvailable:!!n.members,teamMembers:n.members??[],...n.error?{teamError:n.error}:{}}}function O(e){let t=e.planPath?`Source: ${e.planPath}\nExact plan content is restored separately by Doom Plan.`:`(no active plan document)`,n={...e.teamAvailable?{members:e.teamMembers}:{},...e.teamError?{error:e.teamError}:{}};return`<compaction-runtime-state>
4
4
  Authoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.
@@ -46,5 +46,5 @@ ${n}Return only the decision tag when required, followed by a concise structured
46
46
  ### Blocked
47
47
  ## Key Decisions
48
48
  ## Next Steps
49
- ## Critical Context`}function M(e,n,r){let i=t.projectContextMessages((0,m.buildSessionContext)(n).messages,n).messages;if(e===1||!r)return i;let a=n.findIndex(e=>e.id===r);return a===-1?i:n.slice(a+1).filter(e=>e.type!==`custom_message`||e.customType!==`doom-autocompact-checkpoint`).flatMap(e=>(0,m.sessionEntryToContextMessages)(e))}function N(e){let t=(0,o.fileURLToPath)(e),n=(0,a.dirname)(t);for(;;){let e=(0,a.join)(n,`checkpointWorker.mjs`);if((0,i.existsSync)(e))return(0,o.pathToFileURL)(e);let t=(0,a.dirname)(n);if(t===n)break;n=t}throw Error(`Cannot find checkpointWorker.mjs by walking from ${t}.`)}function P(e,t){return new Promise((n,r)=>{let i=new s.Worker(N(require(`url`).pathToFileURL(__filename).href),{workerData:e}),a=!1,o=e=>{a||(a=!0,t.removeEventListener(`abort`,c),e())},c=()=>{o(()=>{i.terminate(),r(t.reason instanceof Error?t.reason:Error(`Autocompact summarization aborted.`))})};i.once(`message`,e=>{o(()=>{typeof e.checkpoint==`string`?n(e.checkpoint):r(Error(e.error??`Autocompact summarization worker returned no checkpoint.`))})}),i.once(`error`,e=>o(()=>r(e))),i.once(`exit`,e=>{e!==0&&o(()=>r(Error(`Autocompact summarization worker exited with code ${e}.`)))}),t.addEventListener(`abort`,c,{once:!0}),i.unref(),t.aborted&&c()})}function F(e){try{return(0,c.loadDoomConfig)((0,c.getHarnessState)().root??e).modes?.planning?.subagents}catch{process.emitWarning(`Doom autocompact planning configuration could not be loaded; using the active session model instead.`);return}}function I(e){let t=F(e.cwd),r=t?.model?n.parseModelReference(t.model):void 0,i=r?e.modelRegistry.find(r.provider,r.modelId):void 0,a=i??e.model;if(!a)return;let o=t?.thinking??(i?r?.thinking:void 0)??e.thinkingLevel;return{model:a,...o?{thinkingLevel:o}:{}}}async function L(e,t){let n=t(e.context);if(!n)throw Error(`No active model is available for autocompact summarization.`);let r=await e.context.modelRegistry.getApiKeyAndHeaders(n.model);if(!r.ok)throw Error(r.error);return P({messages:e.messages,model:n.model,reserveTokens:m.DEFAULT_COMPACTION_SETTINGS.reserveTokens,apiKey:r.apiKey,headers:r.headers,instructions:e.instructions,previousCheckpoint:e.previousCheckpoint,thinkingLevel:n.thinkingLevel,env:r.env},e.signal)}function R(e,t,n=`info`){e?.hasUI&&e.ui.notify(t,n)}function z(n,i,a={}){let o=a.resolveModel??I,s=a.generateCheckpoint??(e=>L(e,o)),c=a.readTaskSnapshot??C,l=a.readTeamSnapshot??w,u=a.telemetry??r.createAutocompactTelemetry(),d=a.doomIntegrations??!0,p=new Set,x=new Set,T=new Set,E=!0,D=0,A=t.createInitialState(),N,P,F;n.effect(()=>async()=>{E=!1,D+=1,P?.abort(Error(`Autocompact runtime is shutting down.`)),P=void 0,await Promise.allSettled(T),F?.dispose(),F=void 0,N=void 0,p.clear(),x.clear(),A=t.createInitialState(),await u.shutdown()},`${g}/runtime`),F=d?(0,f.registerDoomFooterContribution)(i,{source:g,id:`autocompact`,order:20}):{update:()=>void 0,dispose:()=>void 0};let z=e=>{if(!E)return;let t=A.phase===_.checkpointPending?`summarizing`:A.phase===_.checkpointReady?`applying`:void 0;F?.update(t?{fullText:`Compacting p${A.pass}`,compactText:`C${A.pass}`}:void 0);let n=e??N;n?.hasUI&&n.ui.setStatus(`doom-autocompact`,t?`Compacting pass ${A.pass} (${t})…`:void 0)},B=()=>{E&&(i.appendEntry(e.STATE_CUSTOM_TYPE,{...A}),z())},V=()=>{delete A.requestId,delete A.snapshotLeafId,delete A.snapshotTokens,delete A.pendingCheckpoint,delete A.compactionPass},H=e=>{A.checkpointQueue=A.checkpointQueue.filter(t=>t!==e)},te=e=>{E&&(A=y(e.sessionManager.getBranch())??t.createInitialState(),!(A.phase===_.checkpointReady&&A.requestId&&A.snapshotLeafId&&A.pendingCheckpoint||A.phase===_.waiting)&&(P?.abort(),P=void 0,A.phase=_.waiting,V(),B()))},U=t=>{E&&i.sendMessage({customType:e.RESUME_MESSAGE_TYPE,content:`${t} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,display:!1,details:{version:2,cycle:A.cycle,pass:A.pass}},{triggerTurn:!0,deliverAs:`steer`})},W=(e,t)=>{if(!E||e!==A.requestId||A.phase!==_.checkpointPending)return;let n=A.snapshotLeafId;A.phase=_.waiting,n&&(A.lastAttemptLeafId=n),V(),B(),R(N,`Doom autocompact summarization pass ${A.pass} failed: ${t instanceof Error?t.message:String(t)}`,`error`)},G=(e,t,n,i)=>{E&&(t.error&&(R(e,`Doom autocompact task steering degraded: ${t.error}`,`warning`),u.recordWarning(r.AUTOCOMPACT_EVENT.taskSnapshotDegraded,Error(t.error),i)),n.error&&(R(e,`Doom autocompact team steering degraded: ${n.error}`,`warning`),u.recordWarning(r.AUTOCOMPACT_EVENT.teamSnapshotDegraded,Error(n.error),i)))},K=(t,n,r)=>{if(!E)return{tasks:[],teamAvailable:!1,teamMembers:[]};let a=c(t),o=l();G(t,a,o,r);let s=ee(n,a,o);return i.sendMessage({customType:e.RUNTIME_STATE_MESSAGE_TYPE,content:O(s),display:!1,details:{version:1,...s}}),s},q=(n,a)=>{if(!E||!A.requestId||!A.snapshotLeafId||!A.pendingCheckpoint)return!1;let o=a.sessionManager.getBranch(),s=t.projectContextMessages((0,m.buildSessionContext)(o).messages,o).messages,c=t.mergeFileDetails(A,t.fileOperationsFromMessages(s)),l=A.requestId,d=A.cycle,f=t.withCanonicalFileSections(A.pendingCheckpoint,c),p={...c,doomAutocompact:{version:2,cycle:d,pass:n,requestId:l,snapshotLeafId:A.snapshotLeafId,tokensBefore:A.snapshotTokens??a.getContextUsage()?.tokens??0},retainedMessages:t.retainedMessagesAfterSnapshot(o,A.snapshotLeafId)};R(a,`Doom autocompact pass ${n} context commit started.`);let h=a.isIdle();i.sendMessage({customType:e.CONTEXT_MESSAGE_TYPE,content:f,display:!1,details:p});let g=b(a),y=K(a,o,v(a,{"autocompact.request.id":l,"autocompact.cycle":d,"autocompact.pass":n}));return h&&i.setLabel(g,`autocompact:c${d}:p${n}`),A.readFiles=c.readFiles,A.modifiedFiles=c.modifiedFiles,delete A.latestCheckpointSnapshotLeafId,A.phase=_.waiting,A.checkpointQueue=[],A.exhaustedPasses=[],A.invalidAttempts=0,A.baselinePending=!0,delete A.lastAttemptLeafId,V(),A.cycle+=1,A.pass=1,B(),u.recordEvent(r.AUTOCOMPACT_EVENT.contextCommitted,v(a,{"autocompact.request.id":l,"autocompact.cycle":d,"autocompact.pass":n,"autocompact.snapshot_leaf_id":p.doomAutocompact.snapshotLeafId,"autocompact.tokens_before":p.doomAutocompact.tokensBefore,"autocompact.message_count.before":s.length,"autocompact.message_count.retained":p.retainedMessages.length,"autocompact.apply_mode":h?`idle`:`turn_end`,...k(y)})),R(a,`Doom autocompact context committed. Baseline will be captured from the next settled context.`),h&&U(`Asynchronous compaction completed.`),!0},J=(e,n,i)=>{if(!E)return;let a=D,o=n.sessionManager.getBranch(),d=b(n),f=t.createRequestId(n.sessionManager.getSessionId(),A.cycle,e,d),p=e>1?t.checkpointSummaryFromEntry(t.latestCheckpointArtifactEntry(o)):void 0,m=M(e,o,A.latestCheckpointSnapshotLeafId),h=c(n),g=l(),y=v(n,{"autocompact.request.id":f,"autocompact.cycle":A.cycle,"autocompact.pass":e,"autocompact.snapshot_leaf_id":d,"autocompact.tokens_before":i,"autocompact.message_count.before":m.length});G(n,h,g,y),A.phase=_.checkpointPending,A.pass=e,A.requestId=f,A.snapshotLeafId=d,A.snapshotTokens=i,delete A.pendingCheckpoint,delete A.compactionPass,delete A.lastAttemptLeafId,B(),P?.abort(),P=new AbortController;let x=P.signal;R(n,`Doom autocompact summarization pass ${e} started.`);let C=u.runInSpan(`doom_autocompact.checkpoint`,y,async()=>{await u.recordEvent(r.AUTOCOMPACT_EVENT.checkpointStarted,y);try{let t=await s({messages:m,instructions:j(e,{plan:S(o),taskSnapshot:h,teamSnapshot:g,readFiles:A.readFiles,modifiedFiles:A.modifiedFiles}),...p?{previousCheckpoint:p}:{},context:n,signal:x});if(!E||a!==D)throw x.reason??Error(`Autocompact checkpoint became stale.`);if(!t.trim())throw Error(`Summarization returned an empty checkpoint.`);return await u.recordEvent(r.AUTOCOMPACT_EVENT.checkpointCompleted,{...y,"autocompact.checkpoint.characters":t.length}),t}catch(e){throw E&&a===D&&await u.recordError(r.AUTOCOMPACT_EVENT.checkpointFailed,e,y),e}}).then(t=>{!E||a!==D||f!==A.requestId||A.phase!==_.checkpointPending||(A.phase=_.checkpointReady,A.pendingCheckpoint=t.trim(),B(),R(N,`Doom autocompact summarization pass ${e} completed.`),N&&Q(N))}).catch(e=>{E&&a===D&&W(f,e)});T.add(C),C.finally(()=>T.delete(C))},Y=e=>{if(!E||A.phase!==_.waiting||e.hasPendingMessages())return!1;let n=e.getContextUsage();if(!n||n.tokens===null)return!1;if(A.baselinePending)return t.baselineUsageIsSettled(e.sessionManager.getBranch())?(A.baselineTokens=n.tokens,A.baselinePending=!1,B(),R(e,`Doom autocompact baseline captured at ${A.baselineTokens} tokens.`),!1):!1;let r=b(e);if(A.lastAttemptLeafId===r)return!1;for(let e of[1,2,3])e<A.pass||A.checkpointQueue.includes(e)||A.exhaustedPasses.includes(e)||n.tokens>=t.thresholdTokens(e,n.contextWindow,A.baselineTokens)&&A.checkpointQueue.push(e);let i=A.checkpointQueue[0];return i?(J(i,e,n.tokens),!0):!1},X=(n,r)=>{if(!E)return;let a=A.snapshotLeafId;i.appendEntry(e.CHECKPOINT_MESSAGE_TYPE,{...t.checkpointRequestDetails(A.cycle,n,A.requestId??`completed`),summary:r}),a&&(A.latestCheckpointSnapshotLeafId=a)},Z=e=>{if(!E||A.phase!==_.checkpointReady||!A.requestId||!A.pendingCheckpoint)return`none`;let n=A.pass,i=t.parseCheckpointDecision(A.pendingCheckpoint);if(!t.isStructuredCheckpoint(i.summary)){let t=A.snapshotLeafId,i=A.requestId,a=A.invalidAttempts+1,o=a>=3;A.phase=_.waiting,t&&(A.lastAttemptLeafId=t),o?(H(n),A.exhaustedPasses=[...A.exhaustedPasses,n],A.invalidAttempts=0):A.invalidAttempts=a,V(),B();let s=Error(`Summarization pass ${n} returned an incomplete checkpoint.`);return R(e,o?`Doom autocompact summarization pass ${n} returned an incomplete checkpoint ${a} times and was abandoned.`:`Doom autocompact summarization pass ${n} returned an incomplete checkpoint.`,`error`),u.recordError(r.AUTOCOMPACT_EVENT.checkpointInvalid,s,v(e,{"autocompact.cycle":A.cycle,"autocompact.pass":n,"autocompact.checkpoint.attempts":a,"autocompact.checkpoint.exhausted":o,...i?{"autocompact.request.id":i}:{}})),`invalid`}return A.invalidAttempts=0,n===1?(X(1,i.summary),H(1),A.phase=_.waiting,A.pass=2,V(),B(),`pass1`):n===2&&i.shouldCompact!==!0?(X(2,i.summary),H(2),A.phase=_.waiting,A.pass=3,V(),B(),`deferred`):(A.pendingCheckpoint=i.summary,q(n,e)?`committed`:`invalid`)};function Q(e){E&&(N=e,e.isIdle()&&Z(e)!==`committed`&&Y(e))}i.on(`context`,(e,n)=>{if(!E)return;let i=t.projectContextMessages(e.messages,n.sessionManager.getBranch());if(i.invalidMarker){let e=n.sessionManager.getLeafId()??h;x.has(e)||(x.add(e),u.recordError(r.AUTOCOMPACT_EVENT.contextMarkerInvalid,Error(`Doom autocompact context marker is malformed.`),v(n,{"autocompact.leaf_id":e})));return}if(i.marker)return p.has(i.marker.requestId)||(p.add(i.marker.requestId),u.recordEvent(r.AUTOCOMPACT_EVENT.contextApplied,v(n,{"autocompact.request.id":i.marker.requestId,"autocompact.cycle":i.marker.cycle,"autocompact.pass":i.marker.pass,"autocompact.snapshot_leaf_id":i.marker.snapshotLeafId,"autocompact.tokens_before":i.marker.tokensBefore,"autocompact.message_count.before":e.messages.length,"autocompact.message_count.after":i.messages.length,"autocompact.message_count.retained":i.retainedMessageCount}))),{messages:i.messages}});let $=e=>{E&&(D+=1,P?.abort(Error(`Autocompact session generation was replaced.`)),P=void 0,p.clear(),x.clear(),N=e,te(e),Q(e))};i.on(`session_start`,(e,t)=>$(t)),i.on(`session_tree`,(e,t)=>$(t)),i.on(`turn_end`,(e,t)=>{if(E){if(N=t,t.isIdle()){Q(t);return}A.phase===_.checkpointReady&&(e.toolResults?.length??0)>0&&!t.hasPendingMessages()&&Z(t)!==`none`||Y(t)}}),i.on(`agent_settled`,(e,t)=>{E&&Q(t)}),i.on(`session_before_compact`,e=>{if(!(!E||e.reason!==`threshold`))return A.phase===_.checkpointPending||A.phase===_.checkpointReady||A.baselinePending?{cancel:!0}:void 0}),i.on(`session_compact`,(e,n)=>{if(!E)return;D+=1,P?.abort(),P=void 0;let a=t.fileDetailsFromUnknown(e.compactionEntry.details),o=t.mergeFileDetails(A,void 0,a);A.readFiles=o.readFiles,A.modifiedFiles=o.modifiedFiles,delete A.latestCheckpointSnapshotLeafId,A.baselinePending=!0,A.phase=_.waiting,V(),A.checkpointQueue=[],A.exhaustedPasses=[],A.invalidAttempts=0,delete A.lastAttemptLeafId,i.setLabel(e.compactionEntry.id,`autocompact:c${A.cycle}:external`);let s=A.cycle,c=v(n,{"autocompact.cycle":s,"autocompact.native.reason":e.reason}),l=K(n,n.sessionManager.getBranch(),c);A.cycle+=1,A.pass=1,B(),u.recordEvent(r.AUTOCOMPACT_EVENT.nativeCompactionCompleted,v(n,{"autocompact.cycle":s,"autocompact.native.reason":e.reason,"autocompact.native.from_extension":e.fromExtension,"autocompact.tokens_before":e.compactionEntry.tokensBefore,...k(l)})),R(n,`Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${A.pass}.`)})}async function B(e){let t=new p.Context,n,r=()=>(n??=t.fiber.dispose(),n);try{z(t,e)}catch(e){throw await r(),e}e.on(`session_shutdown`,r)}exports.default=B,exports.installAutocompactRuntime=z;
49
+ ## Critical Context`}function M(e,n,r){let i=t.projectContextMessages((0,m.buildSessionContext)(n).messages,n).messages;if(e===1||!r)return i;let a=n.findIndex(e=>e.id===r);return a===-1?i:n.slice(a+1).filter(e=>e.type!==`custom_message`||e.customType!==`doom-autocompact-checkpoint`).flatMap(e=>(0,m.sessionEntryToContextMessages)(e))}function N(e){let t=(0,o.fileURLToPath)(e),n=(0,a.dirname)(t);for(;;){let e=(0,a.join)(n,`checkpointWorker.mjs`);if((0,i.existsSync)(e))return(0,o.pathToFileURL)(e);let t=(0,a.dirname)(n);if(t===n)break;n=t}throw Error(`Cannot find checkpointWorker.mjs by walking from ${t}.`)}function P(e,t){return new Promise((n,r)=>{let i=new s.Worker(N(require(`url`).pathToFileURL(__filename).href),{workerData:e}),a=!1,o=e=>{a||(a=!0,t.removeEventListener(`abort`,c),e())},c=()=>{o(()=>{i.terminate(),r(t.reason instanceof Error?t.reason:Error(`Autocompact summarization aborted.`))})};i.once(`message`,e=>{o(()=>{typeof e.checkpoint==`string`?n(e.checkpoint):r(Error(e.error??`Autocompact summarization worker returned no checkpoint.`))})}),i.once(`error`,e=>o(()=>r(e))),i.once(`exit`,e=>{e!==0&&o(()=>r(Error(`Autocompact summarization worker exited with code ${e}.`)))}),t.addEventListener(`abort`,c,{once:!0}),i.unref(),t.aborted&&c()})}function F(e){try{return(0,c.loadDoomConfig)((0,c.getHarnessState)().root??e).modes?.planning?.subagents}catch{process.emitWarning(`Doom autocompact planning configuration could not be loaded; using the active session model instead.`);return}}function I(e){let t=F(e.cwd),r=t?.model?n.parseModelReference(t.model):void 0,i=r?e.modelRegistry.find(r.provider,r.modelId):void 0,a=i??e.model;if(!a)return;let o=t?.thinking??(i?r?.thinking:void 0)??e.thinkingLevel;return{model:a,...o?{thinkingLevel:o}:{}}}async function L(e,t){let n=t(e.context);if(!n)throw Error(`No active model is available for autocompact summarization.`);let r=await e.context.modelRegistry.getApiKeyAndHeaders(n.model);if(!r.ok)throw Error(r.error);return P({messages:e.messages,model:n.model,reserveTokens:m.DEFAULT_COMPACTION_SETTINGS.reserveTokens,apiKey:r.apiKey,headers:r.headers,instructions:e.instructions,previousCheckpoint:e.previousCheckpoint,thinkingLevel:n.thinkingLevel,env:r.env},e.signal)}function R(e,t,n=`info`){e?.hasUI&&e.ui.notify(t,n)}function z(n,i,a={}){let o=a.resolveModel??I,s=a.generateCheckpoint??(e=>L(e,o)),c=a.readTaskSnapshot??C,l=a.readTeamSnapshot??w,u=a.telemetry??r.createAutocompactTelemetry(),d=a.doomIntegrations??!0,f=new Set,x=new Set,T=new Set,E=!0,D=0,A=t.createInitialState(),N,P,F;n.effect(()=>async()=>{E=!1,D+=1,P?.abort(Error(`Autocompact runtime is shutting down.`)),P=void 0,await Promise.allSettled(T),F=void 0,N=void 0,f.clear(),x.clear(),A=t.createInitialState(),await u.shutdown()},`${g}/runtime`),d&&n.inject([p.DOOM_UI_HUB_SERVICE],e=>{let t=(0,p.requireDoomUiHub)(e).registerFooter({source:g,id:`autocompact`,order:20});return F=t,()=>{t.dispose(),F===t&&(F=void 0)}});let z=e=>{if(!E)return;let t=A.phase===_.checkpointPending?`summarizing`:A.phase===_.checkpointReady?`applying`:void 0;F?.update(t?{fullText:`Compacting p${A.pass}`,compactText:`C${A.pass}`}:void 0);let n=e??N;n?.hasUI&&n.ui.setStatus(`doom-autocompact`,t?`Compacting pass ${A.pass} (${t})…`:void 0)},B=()=>{E&&(i.appendEntry(e.STATE_CUSTOM_TYPE,{...A}),z())},V=()=>{delete A.requestId,delete A.snapshotLeafId,delete A.snapshotTokens,delete A.pendingCheckpoint,delete A.compactionPass},H=e=>{A.checkpointQueue=A.checkpointQueue.filter(t=>t!==e)},te=e=>{E&&(A=y(e.sessionManager.getBranch())??t.createInitialState(),!(A.phase===_.checkpointReady&&A.requestId&&A.snapshotLeafId&&A.pendingCheckpoint||A.phase===_.waiting)&&(P?.abort(),P=void 0,A.phase=_.waiting,V(),B()))},U=t=>{E&&i.sendMessage({customType:e.RESUME_MESSAGE_TYPE,content:`${t} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,display:!1,details:{version:2,cycle:A.cycle,pass:A.pass}},{triggerTurn:!0,deliverAs:`steer`})},W=(e,t)=>{if(!E||e!==A.requestId||A.phase!==_.checkpointPending)return;let n=A.snapshotLeafId;A.phase=_.waiting,n&&(A.lastAttemptLeafId=n),V(),B(),R(N,`Doom autocompact summarization pass ${A.pass} failed: ${t instanceof Error?t.message:String(t)}`,`error`)},G=(e,t,n,i)=>{E&&(t.error&&(R(e,`Doom autocompact task steering degraded: ${t.error}`,`warning`),u.recordWarning(r.AUTOCOMPACT_EVENT.taskSnapshotDegraded,Error(t.error),i)),n.error&&(R(e,`Doom autocompact team steering degraded: ${n.error}`,`warning`),u.recordWarning(r.AUTOCOMPACT_EVENT.teamSnapshotDegraded,Error(n.error),i)))},K=(t,n,r)=>{if(!E)return{tasks:[],teamAvailable:!1,teamMembers:[]};let a=c(t),o=l();G(t,a,o,r);let s=ee(n,a,o);return i.sendMessage({customType:e.RUNTIME_STATE_MESSAGE_TYPE,content:O(s),display:!1,details:{version:1,...s}}),s},q=(n,a)=>{if(!E||!A.requestId||!A.snapshotLeafId||!A.pendingCheckpoint)return!1;let o=a.sessionManager.getBranch(),s=t.projectContextMessages((0,m.buildSessionContext)(o).messages,o).messages,c=t.mergeFileDetails(A,t.fileOperationsFromMessages(s)),l=A.requestId,d=A.cycle,f=t.withCanonicalFileSections(A.pendingCheckpoint,c),p={...c,doomAutocompact:{version:2,cycle:d,pass:n,requestId:l,snapshotLeafId:A.snapshotLeafId,tokensBefore:A.snapshotTokens??a.getContextUsage()?.tokens??0},retainedMessages:t.retainedMessagesAfterSnapshot(o,A.snapshotLeafId)};R(a,`Doom autocompact pass ${n} context commit started.`);let h=a.isIdle();i.sendMessage({customType:e.CONTEXT_MESSAGE_TYPE,content:f,display:!1,details:p});let g=b(a),y=K(a,o,v(a,{"autocompact.request.id":l,"autocompact.cycle":d,"autocompact.pass":n}));return h&&i.setLabel(g,`autocompact:c${d}:p${n}`),A.readFiles=c.readFiles,A.modifiedFiles=c.modifiedFiles,delete A.latestCheckpointSnapshotLeafId,A.phase=_.waiting,A.checkpointQueue=[],A.exhaustedPasses=[],A.invalidAttempts=0,A.baselinePending=!0,delete A.lastAttemptLeafId,V(),A.cycle+=1,A.pass=1,B(),u.recordEvent(r.AUTOCOMPACT_EVENT.contextCommitted,v(a,{"autocompact.request.id":l,"autocompact.cycle":d,"autocompact.pass":n,"autocompact.snapshot_leaf_id":p.doomAutocompact.snapshotLeafId,"autocompact.tokens_before":p.doomAutocompact.tokensBefore,"autocompact.message_count.before":s.length,"autocompact.message_count.retained":p.retainedMessages.length,"autocompact.apply_mode":h?`idle`:`turn_end`,...k(y)})),R(a,`Doom autocompact context committed. Baseline will be captured from the next settled context.`),h&&U(`Asynchronous compaction completed.`),!0},J=(e,n,i)=>{if(!E)return;let a=D,o=n.sessionManager.getBranch(),d=b(n),f=t.createRequestId(n.sessionManager.getSessionId(),A.cycle,e,d),p=e>1?t.checkpointSummaryFromEntry(t.latestCheckpointArtifactEntry(o)):void 0,m=M(e,o,A.latestCheckpointSnapshotLeafId),h=c(n),g=l(),y=v(n,{"autocompact.request.id":f,"autocompact.cycle":A.cycle,"autocompact.pass":e,"autocompact.snapshot_leaf_id":d,"autocompact.tokens_before":i,"autocompact.message_count.before":m.length});G(n,h,g,y),A.phase=_.checkpointPending,A.pass=e,A.requestId=f,A.snapshotLeafId=d,A.snapshotTokens=i,delete A.pendingCheckpoint,delete A.compactionPass,delete A.lastAttemptLeafId,B(),P?.abort(),P=new AbortController;let x=P.signal;R(n,`Doom autocompact summarization pass ${e} started.`);let C=u.runInSpan(`doom_autocompact.checkpoint`,y,async()=>{await u.recordEvent(r.AUTOCOMPACT_EVENT.checkpointStarted,y);try{let t=await s({messages:m,instructions:j(e,{plan:S(o),taskSnapshot:h,teamSnapshot:g,readFiles:A.readFiles,modifiedFiles:A.modifiedFiles}),...p?{previousCheckpoint:p}:{},context:n,signal:x});if(!E||a!==D)throw x.reason??Error(`Autocompact checkpoint became stale.`);if(!t.trim())throw Error(`Summarization returned an empty checkpoint.`);return await u.recordEvent(r.AUTOCOMPACT_EVENT.checkpointCompleted,{...y,"autocompact.checkpoint.characters":t.length}),t}catch(e){throw E&&a===D&&await u.recordError(r.AUTOCOMPACT_EVENT.checkpointFailed,e,y),e}}).then(t=>{!E||a!==D||f!==A.requestId||A.phase!==_.checkpointPending||(A.phase=_.checkpointReady,A.pendingCheckpoint=t.trim(),B(),R(N,`Doom autocompact summarization pass ${e} completed.`),N&&Q(N))}).catch(e=>{E&&a===D&&W(f,e)});T.add(C),C.finally(()=>T.delete(C))},Y=e=>{if(!E||A.phase!==_.waiting||e.hasPendingMessages())return!1;let n=e.getContextUsage();if(!n||n.tokens===null)return!1;if(A.baselinePending)return t.baselineUsageIsSettled(e.sessionManager.getBranch())?(A.baselineTokens=n.tokens,A.baselinePending=!1,B(),R(e,`Doom autocompact baseline captured at ${A.baselineTokens} tokens.`),!1):!1;let r=b(e);if(A.lastAttemptLeafId===r)return!1;for(let e of[1,2,3])e<A.pass||A.checkpointQueue.includes(e)||A.exhaustedPasses.includes(e)||n.tokens>=t.thresholdTokens(e,n.contextWindow,A.baselineTokens)&&A.checkpointQueue.push(e);let i=A.checkpointQueue[0];return i?(J(i,e,n.tokens),!0):!1},X=(n,r)=>{if(!E)return;let a=A.snapshotLeafId;i.appendEntry(e.CHECKPOINT_MESSAGE_TYPE,{...t.checkpointRequestDetails(A.cycle,n,A.requestId??`completed`),summary:r}),a&&(A.latestCheckpointSnapshotLeafId=a)},Z=e=>{if(!E||A.phase!==_.checkpointReady||!A.requestId||!A.pendingCheckpoint)return`none`;let n=A.pass,i=t.parseCheckpointDecision(A.pendingCheckpoint);if(!t.isStructuredCheckpoint(i.summary)){let t=A.snapshotLeafId,i=A.requestId,a=A.invalidAttempts+1,o=a>=3;A.phase=_.waiting,t&&(A.lastAttemptLeafId=t),o?(H(n),A.exhaustedPasses=[...A.exhaustedPasses,n],A.invalidAttempts=0):A.invalidAttempts=a,V(),B();let s=Error(`Summarization pass ${n} returned an incomplete checkpoint.`);return R(e,o?`Doom autocompact summarization pass ${n} returned an incomplete checkpoint ${a} times and was abandoned.`:`Doom autocompact summarization pass ${n} returned an incomplete checkpoint.`,`error`),u.recordError(r.AUTOCOMPACT_EVENT.checkpointInvalid,s,v(e,{"autocompact.cycle":A.cycle,"autocompact.pass":n,"autocompact.checkpoint.attempts":a,"autocompact.checkpoint.exhausted":o,...i?{"autocompact.request.id":i}:{}})),`invalid`}return A.invalidAttempts=0,n===1?(X(1,i.summary),H(1),A.phase=_.waiting,A.pass=2,V(),B(),`pass1`):n===2&&i.shouldCompact!==!0?(X(2,i.summary),H(2),A.phase=_.waiting,A.pass=3,V(),B(),`deferred`):(A.pendingCheckpoint=i.summary,q(n,e)?`committed`:`invalid`)};function Q(e){E&&(N=e,e.isIdle()&&Z(e)!==`committed`&&Y(e))}i.on(`context`,(e,n)=>{if(!E)return;let i=t.projectContextMessages(e.messages,n.sessionManager.getBranch());if(i.invalidMarker){let e=n.sessionManager.getLeafId()??h;x.has(e)||(x.add(e),u.recordError(r.AUTOCOMPACT_EVENT.contextMarkerInvalid,Error(`Doom autocompact context marker is malformed.`),v(n,{"autocompact.leaf_id":e})));return}if(i.marker)return f.has(i.marker.requestId)||(f.add(i.marker.requestId),u.recordEvent(r.AUTOCOMPACT_EVENT.contextApplied,v(n,{"autocompact.request.id":i.marker.requestId,"autocompact.cycle":i.marker.cycle,"autocompact.pass":i.marker.pass,"autocompact.snapshot_leaf_id":i.marker.snapshotLeafId,"autocompact.tokens_before":i.marker.tokensBefore,"autocompact.message_count.before":e.messages.length,"autocompact.message_count.after":i.messages.length,"autocompact.message_count.retained":i.retainedMessageCount}))),{messages:i.messages}});let $=e=>{E&&(D+=1,P?.abort(Error(`Autocompact session generation was replaced.`)),P=void 0,f.clear(),x.clear(),N=e,te(e),Q(e))};i.on(`session_start`,(e,t)=>$(t)),i.on(`session_tree`,(e,t)=>$(t)),i.on(`turn_end`,(e,t)=>{if(E){if(N=t,t.isIdle()){Q(t);return}A.phase===_.checkpointReady&&(e.toolResults?.length??0)>0&&!t.hasPendingMessages()&&Z(t)!==`none`||Y(t)}}),i.on(`agent_settled`,(e,t)=>{E&&Q(t)}),i.on(`session_before_compact`,e=>{if(!(!E||e.reason!==`threshold`))return A.phase===_.checkpointPending||A.phase===_.checkpointReady||A.baselinePending?{cancel:!0}:void 0}),i.on(`session_compact`,(e,n)=>{if(!E)return;D+=1,P?.abort(),P=void 0;let a=t.fileDetailsFromUnknown(e.compactionEntry.details),o=t.mergeFileDetails(A,void 0,a);A.readFiles=o.readFiles,A.modifiedFiles=o.modifiedFiles,delete A.latestCheckpointSnapshotLeafId,A.baselinePending=!0,A.phase=_.waiting,V(),A.checkpointQueue=[],A.exhaustedPasses=[],A.invalidAttempts=0,delete A.lastAttemptLeafId,i.setLabel(e.compactionEntry.id,`autocompact:c${A.cycle}:external`);let s=A.cycle,c=v(n,{"autocompact.cycle":s,"autocompact.native.reason":e.reason}),l=K(n,n.sessionManager.getBranch(),c);A.cycle+=1,A.pass=1,B(),u.recordEvent(r.AUTOCOMPACT_EVENT.nativeCompactionCompleted,v(n,{"autocompact.cycle":s,"autocompact.native.reason":e.reason,"autocompact.native.from_extension":e.fromExtension,"autocompact.tokens_before":e.compactionEntry.tokensBefore,...k(l)})),R(n,`Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${A.pass}.`)})}async function B(e){let t=await(0,l.connectDoomCordisHost)(e,`@agimon-ai/doompi-autocompact`),n=t.root.plugin(V,{pi:e});try{await n}catch(e){try{await n.dispose()}finally{await t.dispose()}throw e}let r;e.on(`session_shutdown`,()=>r??=(async()=>{try{await n.dispose()}finally{await t.dispose()}})())}function V(e,t){z(e,t.pi)}exports.default=B,exports.installAutocompactRuntime=z;
50
50
  //# sourceMappingURL=extension.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"extension.cjs","names":["parseState","TaskStore","projectContextMessages","Worker","parseModelReference","DEFAULT_COMPACTION_SETTINGS","createAutocompactTelemetry","createInitialState","STATE_CUSTOM_TYPE","RESUME_MESSAGE_TYPE","AUTOCOMPACT_EVENT","RUNTIME_STATE_MESSAGE_TYPE","mergeFileDetails","fileOperationsFromMessages","withCanonicalFileSections","retainedMessagesAfterSnapshot","CONTEXT_MESSAGE_TYPE","createRequestId","checkpointSummaryFromEntry","latestCheckpointArtifactEntry","baselineUsageIsSettled","thresholdTokens","CHECKPOINT_MESSAGE_TYPE","checkpointRequestDetails","parseCheckpointDecision","isStructuredCheckpoint","fileDetailsFromUnknown","Context"],"sources":["../../../../src/adapters/pi/extension.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { Worker } from 'node:worker_threads';\n\nimport { getHarnessState, loadDoomConfig, type PlanningAgentConfig } from '@agimon-ai/doompi-config';\nimport { resolveSessionKey } from '@agimon-ai/doompi-task/store/paths';\nimport { TaskStore } from '@agimon-ai/doompi-task/store/taskStore';\nimport type { Task } from '@agimon-ai/doompi-task/store/types';\nimport { readActiveTeamSnapshot, type TeamMemberSnapshot } from '@agimon-ai/doompi-team/api/team-snapshot';\nimport { registerDoomFooterContribution } from '@agimon-ai/doompi-ui/footer';\nimport { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent';\nimport {\n buildSessionContext,\n DEFAULT_COMPACTION_SETTINGS,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n createInitialState,\n createRequestId,\n fileDetailsFromUnknown,\n fileOperationsFromMessages,\n isStructuredCheckpoint,\n latestCheckpointArtifactEntry,\n mergeFileDetails,\n parseCheckpointDecision,\n parseState,\n projectContextMessages,\n retainedMessagesAfterSnapshot,\n thresholdTokens,\n withCanonicalFileSections,\n} from '../../adapters/compaction/policy';\nimport { parseModelReference, type SummarizationModel } from '../../services/summarizationModel.ts';\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type { AutocompactEventAttributes, AutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\n\nexport type { ModelReference, SummarizationModel } from '../../services/summarizationModel.ts';\nexport { parseModelReference, resolveSummarizationModel } from '../../services/summarizationModel.ts';\n\nimport type { AutocompactContextDetails, AutocompactPass, AutocompactState } from '../../types/index.ts';\n\nconst ROOT_WORKING_LEAF = '@root';\nconst PLAN_DOCUMENT_ENTRY = 'agent-harness-plan-document';\nconst FOOTER_SOURCE = 'doom-autocompact';\nconst FOOTER_ORDER = 20;\nconst STATUS_KEY = 'doom-autocompact';\nconst STATE_PHASE = {\n waiting: 'waiting',\n checkpointPending: 'checkpoint_pending',\n checkpointReady: 'checkpoint_ready',\n compacting: 'compacting',\n} as const;\ntype CheckpointCapture = 'none' | 'pass1' | 'committed' | 'deferred' | 'invalid';\ntype CheckpointMessages = ReturnType<typeof buildSessionContext>['messages'];\n\ninterface PlanSnapshot {\n content: string;\n path: string;\n}\n\ninterface TaskSnapshot {\n tasks: Task[];\n error?: string;\n}\n\ninterface TeamSnapshot {\n members?: TeamMemberSnapshot[];\n error?: string;\n}\n\ninterface SteeringSnapshot {\n plan?: PlanSnapshot;\n taskSnapshot: TaskSnapshot;\n teamSnapshot: TeamSnapshot;\n readFiles: string[];\n modifiedFiles: string[];\n}\n\ninterface RuntimeTaskSnapshot {\n id: number;\n status: Task['status'];\n subject: string;\n activeForm?: string;\n owner?: string;\n blockedBy?: number[];\n delegation?: {\n agent: string;\n state: NonNullable<Task['delegation']>['state'];\n error?: string;\n };\n}\n\ninterface RuntimeStateSnapshot {\n planPath?: string;\n tasks: RuntimeTaskSnapshot[];\n taskError?: string;\n teamAvailable: boolean;\n teamMembers: TeamMemberSnapshot[];\n teamError?: string;\n}\n\ninterface CheckpointGenerationInput {\n messages: CheckpointMessages;\n instructions: string;\n previousCheckpoint?: string;\n context: ExtensionContext;\n signal: AbortSignal;\n}\n\ninterface CheckpointWorkerResult {\n checkpoint?: string;\n error?: string;\n}\n\nexport interface AutocompactDependencies {\n generateCheckpoint?: (input: CheckpointGenerationInput) => Promise<string>;\n readTaskSnapshot?: (context: ExtensionContext) => TaskSnapshot;\n readTeamSnapshot?: () => TeamSnapshot;\n resolveModel?: (context: ExtensionContext) => SummarizationModel | undefined;\n telemetry?: AutocompactTelemetry;\n doomIntegrations?: boolean;\n}\n\nfunction telemetryAttributes(\n context: ExtensionContext,\n attributes: AutocompactEventAttributes = {},\n): AutocompactEventAttributes {\n return {\n 'pi.session.id': context.sessionManager.getSessionId(),\n ...attributes,\n };\n}\n\nfunction latestPersistedState(branch: SessionEntry[]): AutocompactState | undefined {\n for (let index = branch.length - 1; index >= 0; index -= 1) {\n const entry = branch[index];\n if (entry?.type !== 'custom' || entry.customType !== STATE_CUSTOM_TYPE) continue;\n const parsed = parseState(entry.data);\n if (parsed) return parsed;\n }\n return undefined;\n}\n\nfunction workingLeafId(ctx: ExtensionContext): string {\n for (const entry of ctx.sessionManager.getBranch().toReversed()) {\n if (entry.type === 'custom' && entry.customType === STATE_CUSTOM_TYPE) continue;\n if (entry.type === 'label') continue;\n return entry.id;\n }\n return ROOT_WORKING_LEAF;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction latestPlanSnapshot(branch: SessionEntry[]): PlanSnapshot | undefined {\n for (const entry of branch.toReversed()) {\n if (entry.type !== 'custom' || entry.customType !== PLAN_DOCUMENT_ENTRY) continue;\n if (!entry.data || typeof entry.data !== 'object') return undefined;\n const data = entry.data as Record<string, unknown>;\n if (typeof data.content !== 'string' || typeof data.path !== 'string') return undefined;\n return { content: data.content, path: data.path };\n }\n return undefined;\n}\n\nfunction readTaskSnapshotWithDoomTask(context: ExtensionContext): TaskSnapshot {\n const failures: string[] = [];\n try {\n const store = new TaskStore({\n cwd: context.cwd,\n report: {\n error: (event, error) => failures.push(`${event}: ${errorMessage(error)}`),\n warn: (event, error) => failures.push(`${event}: ${errorMessage(error)}`),\n event: () => undefined,\n },\n });\n store.configureSession(resolveSessionKey(context.sessionManager.getSessionId()));\n const tasks = store.read().tasks;\n return { tasks, ...(failures.length > 0 ? { error: failures.join('; ') } : {}) };\n } catch (error) {\n return { tasks: [], error: errorMessage(error) };\n }\n}\n\nfunction readTeamSnapshotWithDoomTeam(): TeamSnapshot {\n try {\n const snapshot = readActiveTeamSnapshot();\n return snapshot ? { members: snapshot.members } : {};\n } catch (error) {\n return { error: errorMessage(error) };\n }\n}\n\nfunction activeTaskSnapshots(snapshot: TaskSnapshot): RuntimeTaskSnapshot[] {\n return snapshot.tasks\n .filter((task) => task.status === 'pending' || task.status === 'in_progress' || task.status === 'failed')\n .map((task) => ({\n id: task.id,\n status: task.status,\n subject: task.subject,\n ...(task.activeForm ? { activeForm: task.activeForm } : {}),\n ...(task.owner ? { owner: task.owner } : {}),\n ...(task.blockedBy?.length ? { blockedBy: task.blockedBy } : {}),\n ...(task.delegation\n ? {\n delegation: {\n agent: task.delegation.agent,\n state: task.delegation.state,\n ...(task.delegation.result?.error ? { error: task.delegation.result.error } : {}),\n },\n }\n : {}),\n }));\n}\n\nfunction formatRuntimeTasks(tasks: RuntimeTaskSnapshot[], error?: string): string {\n const lines = tasks.map((task) => {\n const details = [\n task.activeForm ? `active: ${task.activeForm}` : undefined,\n task.owner ? `owner: ${task.owner}` : undefined,\n task.blockedBy?.length ? `blocked by: ${task.blockedBy.join(', ')}` : undefined,\n task.delegation ? `delegation: ${task.delegation.agent} (${task.delegation.state})` : undefined,\n task.delegation?.error ? `error: ${task.delegation.error}` : undefined,\n ].filter((value): value is string => Boolean(value));\n return `- #${task.id} [${task.status}] ${task.subject}${details.length > 0 ? ` | ${details.join(' | ')}` : ''}`;\n });\n if (error) lines.push(`- Task snapshot error: ${error}`);\n return lines.length > 0 ? lines.join('\\n') : '(no active tasks)';\n}\n\nfunction formatTeamSnapshot(snapshot: TeamSnapshot): string {\n const lines = (snapshot.members ?? []).map((member) => {\n const details = [\n `role: ${member.role}`,\n member.agent ? `agent: ${member.agent}` : undefined,\n member.runId ? `run: ${member.runId}` : undefined,\n member.task ? `task ${member.task.id}: ${member.task.subject}` : undefined,\n ].filter((value): value is string => Boolean(value));\n return `- ${member.name} | ${details.join(' | ')}`;\n });\n if (snapshot.error) lines.push(`- Team snapshot error: ${snapshot.error}`);\n if (lines.length > 0) return lines.join('\\n');\n return snapshot.members ? '(no active team members)' : '(team runtime unavailable)';\n}\n\nfunction runtimeStateSnapshot(\n branch: SessionEntry[],\n taskSnapshot: TaskSnapshot,\n teamSnapshot: TeamSnapshot,\n): RuntimeStateSnapshot {\n const plan = latestPlanSnapshot(branch);\n return {\n ...(plan ? { planPath: plan.path } : {}),\n tasks: activeTaskSnapshots(taskSnapshot),\n ...(taskSnapshot.error ? { taskError: taskSnapshot.error } : {}),\n teamAvailable: Boolean(teamSnapshot.members),\n teamMembers: teamSnapshot.members ?? [],\n ...(teamSnapshot.error ? { teamError: teamSnapshot.error } : {}),\n };\n}\n\nfunction formatRuntimeState(snapshot: RuntimeStateSnapshot): string {\n const plan = snapshot.planPath\n ? `Source: ${snapshot.planPath}\\nExact plan content is restored separately by Doom Plan.`\n : '(no active plan document)';\n const teamSnapshot: TeamSnapshot = {\n ...(snapshot.teamAvailable ? { members: snapshot.teamMembers } : {}),\n ...(snapshot.teamError ? { error: snapshot.teamError } : {}),\n };\n return `<compaction-runtime-state>\nAuthoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.\n<active-plan>\n${plan}\n</active-plan>\n<active-tasks>\n${formatRuntimeTasks(snapshot.tasks, snapshot.taskError)}\n</active-tasks>\n<active-team>\n${formatTeamSnapshot(teamSnapshot)}\n</active-team>\n</compaction-runtime-state>`;\n}\n\nfunction runtimeTelemetryAttributes(snapshot: RuntimeStateSnapshot): AutocompactEventAttributes {\n return {\n 'autocompact.runtime.plan_present': Boolean(snapshot.planPath),\n 'autocompact.runtime.task_count': snapshot.tasks.length,\n 'autocompact.runtime.team_available': snapshot.teamAvailable,\n 'autocompact.runtime.team_member_count': snapshot.teamMembers.length,\n };\n}\n\nfunction steeringEnvelope(snapshot: SteeringSnapshot): string {\n const plan = snapshot.plan\n ? `Source: ${snapshot.plan.path}\\n\\n${snapshot.plan.content}`\n : '(no active plan document)';\n const importantContext = [\n snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(', ')}` : undefined,\n snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(', ')}` : undefined,\n ].filter((value): value is string => Boolean(value));\n\n return `<compaction-steering priority=\"user,plan,tasks,team,important-context,recent-messages\">\n<user-prompt source=\"conversation\">\nTreat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.\n</user-prompt>\n<active-plan>\n${plan}\n</active-plan>\n<active-tasks>\n${formatRuntimeTasks(activeTaskSnapshots(snapshot.taskSnapshot), snapshot.taskSnapshot.error)}\n</active-tasks>\n<active-team>\n${formatTeamSnapshot(snapshot.teamSnapshot)}\n</active-team>\n<important-context>\n${importantContext.length > 0 ? importantContext.join('\\n') : '(none recorded outside the conversation)'}\n</important-context>\n</compaction-steering>`;\n}\n\nfunction checkpointInstructions(pass: AutocompactPass, steering: SteeringSnapshot): string {\n const decision =\n pass === 2\n ? 'Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\\n\\n'\n : '';\n\n // Summarization is a tool-less single LLM call, so instructions describe only what to\n // produce. Directives aimed at an implementing agent leak into the checkpoint body.\n return `Create Doom autocompact checkpoint pass ${pass}.\n\n${steeringEnvelope(steering)}\n\nApply the steering evidence in priority order. Do not invent plan, task, or team state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.\n\n${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.\n\n## Goal\n## Constraints & Preferences\n## Progress\n### Done\n### In Progress\n### Blocked\n## Key Decisions\n## Next Steps\n## Critical Context`;\n}\n\nfunction messagesForCheckpoint(\n pass: AutocompactPass,\n branch: SessionEntry[],\n previousSnapshotLeafId: string | undefined,\n): CheckpointMessages {\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n if (pass === 1 || !previousSnapshotLeafId) return projected;\n const snapshotIndex = branch.findIndex((entry) => entry.id === previousSnapshotLeafId);\n if (snapshotIndex === -1) return projected;\n return branch\n .slice(snapshotIndex + 1)\n .filter((entry) => entry.type !== 'custom_message' || entry.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap((entry) => sessionEntryToContextMessages(entry));\n}\n\nexport function findCheckpointWorkerUrl(importFileUrl: string | URL): URL {\n const importFilePath = fileURLToPath(importFileUrl);\n let directory = dirname(importFilePath);\n\n while (true) {\n const workerPath = join(directory, 'checkpointWorker.mjs');\n if (existsSync(workerPath)) return pathToFileURL(workerPath);\n\n const parent = dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n\n throw new Error(`Cannot find checkpointWorker.mjs by walking from ${importFilePath}.`);\n}\n\nfunction runCheckpointWorker(workerInput: Record<string, unknown>, signal: AbortSignal): Promise<string> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(findCheckpointWorkerUrl(import.meta.url), { workerData: workerInput });\n let settled = false;\n\n const settle = (complete: () => void): void => {\n if (settled) return;\n settled = true;\n signal.removeEventListener('abort', abort);\n complete();\n };\n const abort = (): void => {\n settle(() => {\n void worker.terminate();\n reject(signal.reason instanceof Error ? signal.reason : new Error('Autocompact summarization aborted.'));\n });\n };\n\n worker.once('message', (result: CheckpointWorkerResult) => {\n settle(() => {\n if (typeof result.checkpoint === 'string') resolve(result.checkpoint);\n else reject(new Error(result.error ?? 'Autocompact summarization worker returned no checkpoint.'));\n });\n });\n worker.once('error', (error) => settle(() => reject(error)));\n worker.once('exit', (code) => {\n if (code !== 0) settle(() => reject(new Error(`Autocompact summarization worker exited with code ${code}.`)));\n });\n signal.addEventListener('abort', abort, { once: true });\n worker.unref();\n if (signal.aborted) abort();\n });\n}\n\nfunction subagentModelConfig(cwd: string): PlanningAgentConfig | undefined {\n try {\n return loadDoomConfig(getHarnessState().root ?? cwd).modes?.planning?.subagents;\n } catch {\n process.emitWarning(\n 'Doom autocompact planning configuration could not be loaded; using the active session model instead.',\n );\n return undefined;\n }\n}\n\n/** Explicit Doom model selection honors the configured planning subagent model. */\nexport function resolveDoomSummarizationModel(ctx: ExtensionContext): SummarizationModel | undefined {\n const configured = subagentModelConfig(ctx.cwd);\n const reference = configured?.model ? parseModelReference(configured.model) : undefined;\n const configuredModel = reference ? ctx.modelRegistry.find(reference.provider, reference.modelId) : undefined;\n const model = configuredModel ?? ctx.model;\n if (!model) return undefined;\n const thinkingLevel =\n configured?.thinking ?? (configuredModel ? reference?.thinking : undefined) ?? ctx.thinkingLevel;\n return { model, ...(thinkingLevel ? { thinkingLevel } : {}) };\n}\n\nasync function generateCheckpointWithPi(\n input: CheckpointGenerationInput,\n resolveModel: (context: ExtensionContext) => SummarizationModel | undefined,\n): Promise<string> {\n const selection = resolveModel(input.context);\n if (!selection) throw new Error('No active model is available for autocompact summarization.');\n const auth = await input.context.modelRegistry.getApiKeyAndHeaders(selection.model);\n if (!auth.ok) throw new Error(auth.error);\n return runCheckpointWorker(\n {\n messages: input.messages,\n model: selection.model,\n reserveTokens: DEFAULT_COMPACTION_SETTINGS.reserveTokens,\n apiKey: auth.apiKey,\n headers: auth.headers,\n instructions: input.instructions,\n previousCheckpoint: input.previousCheckpoint,\n thinkingLevel: selection.thinkingLevel,\n env: auth.env,\n },\n input.signal,\n );\n}\n\nfunction notify(ctx: ExtensionContext | undefined, message: string, level: 'info' | 'warning' | 'error' = 'info') {\n if (ctx?.hasUI) ctx.ui.notify(message, level);\n}\n\nexport function installAutocompactRuntime(\n cordis: Context,\n pi: ExtensionAPI,\n dependencies: AutocompactDependencies = {},\n): void {\n const resolveModel = dependencies.resolveModel ?? resolveDoomSummarizationModel;\n const generateCheckpoint =\n dependencies.generateCheckpoint ??\n ((input: CheckpointGenerationInput) => generateCheckpointWithPi(input, resolveModel));\n const readTaskSnapshot = dependencies.readTaskSnapshot ?? readTaskSnapshotWithDoomTask;\n const readTeamSnapshot = dependencies.readTeamSnapshot ?? readTeamSnapshotWithDoomTeam;\n const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();\n const doomIntegrations = dependencies.doomIntegrations ?? true;\n const appliedContextRequests = new Set<string>();\n const invalidContextLeaves = new Set<string>();\n const checkpointWork = new Set<Promise<void>>();\n let active = true;\n let sessionGeneration = 0;\n let state = createInitialState();\n let currentContext: ExtensionContext | undefined;\n let checkpointController: AbortController | undefined;\n let footerContribution: ReturnType<typeof registerDoomFooterContribution> | undefined;\n\n cordis.effect(\n () => async () => {\n active = false;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact runtime is shutting down.'));\n checkpointController = undefined;\n await Promise.allSettled(checkpointWork);\n footerContribution?.dispose();\n footerContribution = undefined;\n currentContext = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n state = createInitialState();\n await telemetry.shutdown();\n },\n `${FOOTER_SOURCE}/runtime`,\n );\n\n footerContribution = doomIntegrations\n ? registerDoomFooterContribution(pi, {\n source: FOOTER_SOURCE,\n id: 'autocompact',\n order: FOOTER_ORDER,\n })\n : { update: () => undefined, dispose: () => undefined };\n\n /** Compaction runs off the main thread, so the phase is the only signal the user gets. */\n const refreshStatus = (ctx?: ExtensionContext): void => {\n if (!active) return;\n const phase =\n state.phase === STATE_PHASE.checkpointPending\n ? 'summarizing'\n : state.phase === STATE_PHASE.checkpointReady\n ? 'applying'\n : undefined;\n footerContribution?.update(\n phase ? { fullText: `Compacting p${state.pass}`, compactText: `C${state.pass}` } : undefined,\n );\n const target = ctx ?? currentContext;\n if (target?.hasUI) target.ui.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : undefined);\n };\n\n // Every phase transition persists, so this is the one place that keeps the status honest.\n const persist = (): void => {\n if (!active) return;\n pi.appendEntry(STATE_CUSTOM_TYPE, { ...state });\n refreshStatus();\n };\n\n const clearPendingCheckpoint = (): void => {\n delete state.requestId;\n delete state.snapshotLeafId;\n delete state.snapshotTokens;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n };\n\n const completeQueuedPass = (pass: AutocompactPass): void => {\n state.checkpointQueue = state.checkpointQueue.filter((queuedPass) => queuedPass !== pass);\n };\n\n const restore = (ctx: ExtensionContext): void => {\n if (!active) return;\n state = latestPersistedState(ctx.sessionManager.getBranch()) ?? createInitialState();\n const resumablePending =\n state.phase === STATE_PHASE.checkpointReady && state.requestId && state.snapshotLeafId && state.pendingCheckpoint;\n if (resumablePending || state.phase === STATE_PHASE.waiting) return;\n\n checkpointController?.abort();\n checkpointController = undefined;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n persist();\n };\n\n const resumeAgent = (message: string): void => {\n if (!active) return;\n pi.sendMessage(\n {\n customType: RESUME_MESSAGE_TYPE,\n content: `${message} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,\n display: false,\n details: { version: STATE_VERSION, cycle: state.cycle, pass: state.pass },\n },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n };\n\n const failCheckpoint = (requestId: string, error: unknown): void => {\n if (!active || requestId !== state.requestId || state.phase !== STATE_PHASE.checkpointPending) return;\n const failedLeafId = state.snapshotLeafId;\n state.phase = STATE_PHASE.waiting;\n if (failedLeafId) state.lastAttemptLeafId = failedLeafId;\n clearPendingCheckpoint();\n persist();\n notify(\n currentContext,\n `Doom autocompact summarization pass ${state.pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n 'error',\n );\n };\n\n const reportSnapshotFailures = (\n ctx: ExtensionContext,\n taskSnapshot: TaskSnapshot,\n teamSnapshot: TeamSnapshot,\n attributes: AutocompactEventAttributes,\n ): void => {\n if (!active) return;\n if (taskSnapshot.error) {\n notify(ctx, `Doom autocompact task steering degraded: ${taskSnapshot.error}`, 'warning');\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.taskSnapshotDegraded, new Error(taskSnapshot.error), attributes);\n }\n if (teamSnapshot.error) {\n notify(ctx, `Doom autocompact team steering degraded: ${teamSnapshot.error}`, 'warning');\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.teamSnapshotDegraded, new Error(teamSnapshot.error), attributes);\n }\n };\n\n const preserveRuntimeState = (\n ctx: ExtensionContext,\n branch: SessionEntry[],\n attributes: AutocompactEventAttributes,\n ): RuntimeStateSnapshot => {\n if (!active) {\n return { tasks: [], teamAvailable: false, teamMembers: [] };\n }\n const taskSnapshot = readTaskSnapshot(ctx);\n const teamSnapshot = readTeamSnapshot();\n reportSnapshotFailures(ctx, taskSnapshot, teamSnapshot, attributes);\n const snapshot = runtimeStateSnapshot(branch, taskSnapshot, teamSnapshot);\n pi.sendMessage({\n customType: RUNTIME_STATE_MESSAGE_TYPE,\n content: formatRuntimeState(snapshot),\n display: false,\n details: { version: 1, ...snapshot },\n });\n return snapshot;\n };\n\n const commitCheckpoint = (pass: 2 | 3, ctx: ExtensionContext): boolean => {\n if (!active || !state.requestId || !state.snapshotLeafId || !state.pendingCheckpoint) return false;\n const branch = ctx.sessionManager.getBranch();\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n const fileDetails = mergeFileDetails(state, fileOperationsFromMessages(projected));\n const requestId = state.requestId;\n const cycle = state.cycle;\n const summary = withCanonicalFileSections(state.pendingCheckpoint, fileDetails);\n const details: AutocompactContextDetails = {\n ...fileDetails,\n doomAutocompact: {\n version: STATE_VERSION,\n cycle,\n pass,\n requestId,\n snapshotLeafId: state.snapshotLeafId,\n tokensBefore: state.snapshotTokens ?? ctx.getContextUsage()?.tokens ?? 0,\n },\n retainedMessages: retainedMessagesAfterSnapshot(branch, state.snapshotLeafId),\n };\n\n notify(ctx, `Doom autocompact pass ${pass} context commit started.`);\n const committedWhileIdle = ctx.isIdle();\n pi.sendMessage({ customType: CONTEXT_MESSAGE_TYPE, content: summary, display: false, details });\n const contextMessageLeafId = workingLeafId(ctx);\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, branch, runtimeAttributes);\n // Mid-run the marker is queued as a steering message, so its entry id is not resolvable yet.\n if (committedWhileIdle) pi.setLabel(contextMessageLeafId, `autocompact:c${cycle}:p${pass}`);\n\n state.readFiles = fileDetails.readFiles;\n state.modifiedFiles = fileDetails.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n state.phase = STATE_PHASE.waiting;\n state.checkpointQueue = [];\n // A compacted context is a fresh ladder: passes abandoned in the previous cycle are eligible again.\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n state.baselinePending = true;\n delete state.lastAttemptLeafId;\n clearPendingCheckpoint();\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextCommitted,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': details.doomAutocompact.snapshotLeafId,\n 'autocompact.tokens_before': details.doomAutocompact.tokensBefore,\n 'autocompact.message_count.before': projected.length,\n 'autocompact.message_count.retained': details.retainedMessages.length,\n 'autocompact.apply_mode': committedWhileIdle ? 'idle' : 'turn_end',\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n notify(ctx, `Doom autocompact context committed. Baseline will be captured from the next settled context.`);\n // A mid-run commit needs no resume steer: the agent is already continuing.\n if (committedWhileIdle) resumeAgent('Asynchronous compaction completed.');\n return true;\n };\n\n const requestCheckpoint = (pass: AutocompactPass, ctx: ExtensionContext, tokensBefore: number): void => {\n if (!active) return;\n const generation = sessionGeneration;\n const branch = ctx.sessionManager.getBranch();\n const snapshotLeafId = workingLeafId(ctx);\n const requestId = createRequestId(ctx.sessionManager.getSessionId(), state.cycle, pass, snapshotLeafId);\n const previousCheckpoint = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(branch)) : undefined;\n const messages = messagesForCheckpoint(pass, branch, state.latestCheckpointSnapshotLeafId);\n const taskSnapshot = readTaskSnapshot(ctx);\n const teamSnapshot = readTeamSnapshot();\n const attributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': snapshotLeafId,\n 'autocompact.tokens_before': tokensBefore,\n 'autocompact.message_count.before': messages.length,\n });\n reportSnapshotFailures(ctx, taskSnapshot, teamSnapshot, attributes);\n\n state.phase = STATE_PHASE.checkpointPending;\n state.pass = pass;\n state.requestId = requestId;\n state.snapshotLeafId = snapshotLeafId;\n state.snapshotTokens = tokensBefore;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n delete state.lastAttemptLeafId;\n persist();\n\n checkpointController?.abort();\n checkpointController = new AbortController();\n const checkpointSignal = checkpointController.signal;\n notify(ctx, `Doom autocompact summarization pass ${pass} started.`);\n const operation = telemetry\n .runInSpan('doom_autocompact.checkpoint', attributes, async () => {\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, attributes);\n try {\n const checkpoint = await generateCheckpoint({\n messages,\n instructions: checkpointInstructions(pass, {\n plan: latestPlanSnapshot(branch),\n taskSnapshot,\n teamSnapshot,\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n }),\n ...(previousCheckpoint ? { previousCheckpoint } : {}),\n context: ctx,\n signal: checkpointSignal,\n });\n if (!active || generation !== sessionGeneration) {\n throw checkpointSignal.reason ?? new Error('Autocompact checkpoint became stale.');\n }\n if (!checkpoint.trim()) throw new Error('Summarization returned an empty checkpoint.');\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {\n ...attributes,\n 'autocompact.checkpoint.characters': checkpoint.length,\n });\n return checkpoint;\n } catch (error) {\n if (active && generation === sessionGeneration) {\n await telemetry.recordError(AUTOCOMPACT_EVENT.checkpointFailed, error, attributes);\n }\n throw error;\n }\n })\n .then((checkpoint) => {\n if (\n !active ||\n generation !== sessionGeneration ||\n requestId !== state.requestId ||\n state.phase !== STATE_PHASE.checkpointPending\n ) {\n return;\n }\n state.phase = STATE_PHASE.checkpointReady;\n state.pendingCheckpoint = checkpoint.trim();\n persist();\n notify(currentContext, `Doom autocompact summarization pass ${pass} completed.`);\n if (currentContext) processProgress(currentContext);\n })\n .catch((error: unknown) => {\n if (active && generation === sessionGeneration) failCheckpoint(requestId, error);\n });\n checkpointWork.add(operation);\n void operation.finally(() => checkpointWork.delete(operation));\n };\n\n const evaluateUsage = (ctx: ExtensionContext): boolean => {\n if (!active || state.phase !== STATE_PHASE.waiting || ctx.hasPendingMessages()) return false;\n const usage = ctx.getContextUsage();\n if (!usage || usage.tokens === null) return false;\n if (state.baselinePending) {\n // Reported usage still describes the pre-compaction context until an assistant\n // responds against the projected one, and capturing it early poisons every threshold.\n if (!baselineUsageIsSettled(ctx.sessionManager.getBranch())) return false;\n state.baselineTokens = usage.tokens;\n state.baselinePending = false;\n persist();\n notify(ctx, `Doom autocompact baseline captured at ${state.baselineTokens} tokens.`);\n return false;\n }\n const leafId = workingLeafId(ctx);\n if (state.lastAttemptLeafId === leafId) return false;\n\n for (const pass of [1, 2, 3] as const) {\n if (pass < state.pass || state.checkpointQueue.includes(pass) || state.exhaustedPasses.includes(pass)) continue;\n if (usage.tokens >= thresholdTokens(pass, usage.contextWindow, state.baselineTokens)) {\n state.checkpointQueue.push(pass);\n }\n }\n const nextPass = state.checkpointQueue[0];\n if (!nextPass) return false;\n requestCheckpoint(nextPass, ctx, usage.tokens);\n return true;\n };\n\n // Staged checkpoints seed the next summarization pass only. They are appended as plain\n // session entries so they never enter the agent's LLM context: delivering them as messages\n // reads like a user instruction and derails the run (\"Checkpoint acknowledged...\").\n const stageCheckpoint = (pass: 1 | 2, summary: string): void => {\n if (!active) return;\n const checkpointSnapshotLeafId = state.snapshotLeafId;\n pi.appendEntry(CHECKPOINT_MESSAGE_TYPE, {\n ...checkpointRequestDetails(state.cycle, pass, state.requestId ?? 'completed'),\n summary,\n });\n if (checkpointSnapshotLeafId) state.latestCheckpointSnapshotLeafId = checkpointSnapshotLeafId;\n };\n\n const captureReadyCheckpoint = (ctx: ExtensionContext): CheckpointCapture => {\n if (!active || state.phase !== STATE_PHASE.checkpointReady || !state.requestId || !state.pendingCheckpoint) {\n return 'none';\n }\n const pass = state.pass;\n const decision = parseCheckpointDecision(state.pendingCheckpoint);\n if (!isStructuredCheckpoint(decision.summary)) {\n const failedLeafId = state.snapshotLeafId;\n const invalidRequestId = state.requestId;\n // A queued pass is retried once per new leaf, so an output the summarizer never formats\n // correctly would otherwise burn a full summarization call every turn for the session.\n const attempts = state.invalidAttempts + 1;\n const exhausted = attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS;\n state.phase = STATE_PHASE.waiting;\n if (failedLeafId) state.lastAttemptLeafId = failedLeafId;\n if (exhausted) {\n completeQueuedPass(pass);\n state.exhaustedPasses = [...state.exhaustedPasses, pass];\n state.invalidAttempts = 0;\n } else {\n state.invalidAttempts = attempts;\n }\n clearPendingCheckpoint();\n persist();\n const error = new Error(`Summarization pass ${pass} returned an incomplete checkpoint.`);\n notify(\n ctx,\n exhausted\n ? `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint ${attempts} times and was abandoned.`\n : `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint.`,\n 'error',\n );\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.checkpointInvalid,\n error,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': exhausted,\n ...(invalidRequestId ? { 'autocompact.request.id': invalidRequestId } : {}),\n }),\n );\n return 'invalid';\n }\n\n state.invalidAttempts = 0;\n\n if (pass === 1) {\n stageCheckpoint(1, decision.summary);\n completeQueuedPass(1);\n state.phase = STATE_PHASE.waiting;\n state.pass = 2;\n clearPendingCheckpoint();\n persist();\n return 'pass1';\n }\n\n if (pass === 2 && decision.shouldCompact !== true) {\n stageCheckpoint(2, decision.summary);\n completeQueuedPass(2);\n state.phase = STATE_PHASE.waiting;\n state.pass = 3;\n clearPendingCheckpoint();\n persist();\n return 'deferred';\n }\n\n state.pendingCheckpoint = decision.summary;\n return commitCheckpoint(pass, ctx) ? 'committed' : 'invalid';\n };\n\n function processProgress(ctx: ExtensionContext): void {\n if (!active) return;\n currentContext = ctx;\n if (!ctx.isIdle()) return;\n if (captureReadyCheckpoint(ctx) !== 'committed') evaluateUsage(ctx);\n }\n\n pi.on('context', (event, ctx) => {\n if (!active) return undefined;\n const projection = projectContextMessages(event.messages, ctx.sessionManager.getBranch());\n if (projection.invalidMarker) {\n const leafId = ctx.sessionManager.getLeafId() ?? ROOT_WORKING_LEAF;\n if (!invalidContextLeaves.has(leafId)) {\n invalidContextLeaves.add(leafId);\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.contextMarkerInvalid,\n new Error('Doom autocompact context marker is malformed.'),\n telemetryAttributes(ctx, { 'autocompact.leaf_id': leafId }),\n );\n }\n return undefined;\n }\n if (!projection.marker) return undefined;\n if (!appliedContextRequests.has(projection.marker.requestId)) {\n appliedContextRequests.add(projection.marker.requestId);\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextApplied,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': projection.marker.requestId,\n 'autocompact.cycle': projection.marker.cycle,\n 'autocompact.pass': projection.marker.pass,\n 'autocompact.snapshot_leaf_id': projection.marker.snapshotLeafId,\n 'autocompact.tokens_before': projection.marker.tokensBefore,\n 'autocompact.message_count.before': event.messages.length,\n 'autocompact.message_count.after': projection.messages.length,\n 'autocompact.message_count.retained': projection.retainedMessageCount,\n }),\n );\n }\n return { messages: projection.messages };\n });\n\n const beginSessionGeneration = (ctx: ExtensionContext): void => {\n if (!active) return;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact session generation was replaced.'));\n checkpointController = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n currentContext = ctx;\n restore(ctx);\n processProgress(ctx);\n };\n\n pi.on('session_start', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('session_tree', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('turn_end', (event, ctx) => {\n if (!active) return;\n currentContext = ctx;\n if (ctx.isIdle()) {\n processProgress(ctx);\n return;\n }\n // A ready checkpoint must be applied without waiting for the run to finish, otherwise\n // context keeps growing past the window for the rest of a long autonomous run. Tool\n // results confirm the run continues, so the queued marker lands before the next request.\n const canApplyDuringRun =\n state.phase === STATE_PHASE.checkpointReady && (event.toolResults?.length ?? 0) > 0 && !ctx.hasPendingMessages();\n if (canApplyDuringRun && captureReadyCheckpoint(ctx) !== 'none') return;\n evaluateUsage(ctx);\n });\n\n pi.on('agent_settled', (_event, ctx) => {\n if (!active) return;\n processProgress(ctx);\n });\n\n pi.on('session_before_compact', (event) => {\n if (!active || event.reason !== 'threshold') return undefined;\n // Native compaction stays cancelled while our own machinery is working, and stays\n // available as the emergency backstop once that machinery has stalled or declined.\n const machineryActive =\n state.phase === STATE_PHASE.checkpointPending ||\n state.phase === STATE_PHASE.checkpointReady ||\n state.baselinePending;\n return machineryActive ? { cancel: true } : undefined;\n });\n\n pi.on('session_compact', (event, ctx) => {\n if (!active) return;\n sessionGeneration += 1;\n // Native compaction supersedes any summarization still in flight.\n checkpointController?.abort();\n checkpointController = undefined;\n const eventDetails = fileDetailsFromUnknown(event.compactionEntry.details);\n const cumulative = mergeFileDetails(state, undefined, eventDetails);\n state.readFiles = cumulative.readFiles;\n state.modifiedFiles = cumulative.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n // Reported usage still describes the pre-compaction context here too, so the baseline\n // waits for the first assistant response measured against the compacted one.\n state.baselinePending = true;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n state.checkpointQueue = [];\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n delete state.lastAttemptLeafId;\n\n pi.setLabel(event.compactionEntry.id, `autocompact:c${state.cycle}:external`);\n const completedCycle = state.cycle;\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, ctx.sessionManager.getBranch(), runtimeAttributes);\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.nativeCompactionCompleted,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n 'autocompact.native.from_extension': event.fromExtension,\n 'autocompact.tokens_before': event.compactionEntry.tokensBefore,\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n notify(\n ctx,\n `Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${state.pass}.`,\n );\n });\n}\n\n/** The package's single standard Pi factory. */\nexport async function autocompactExtension(pi: ExtensionAPI): Promise<void> {\n const cordis = new Context();\n let disposal: Promise<void> | undefined;\n const dispose = (): Promise<void> => {\n disposal ??= cordis.fiber.dispose();\n return disposal;\n };\n\n try {\n installAutocompactRuntime(cordis, pi);\n } catch (error) {\n await dispose();\n throw error;\n }\n\n pi.on('session_shutdown', dispose);\n}\n\nexport default autocompactExtension;\n"],"mappings":"mlBAsDA,MAAM,EAAoB,QAEpB,EAAgB,mBAGhB,EAAc,CAClB,QAAS,UACT,kBAAmB,qBACnB,gBAAiB,mBACjB,WAAY,aACb,CAwED,SAAS,EACP,EACA,EAAyC,EAAE,CACf,CAC5B,MAAO,CACL,gBAAiB,EAAQ,eAAe,cAAc,CACtD,GAAG,EACJ,CAGH,SAAS,EAAqB,EAAsD,CACl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B,oBAAqB,EACrB,4BAA6B,EAAM,OACnC,oCAAqC,EAAM,cAC3C,4BAA6B,EAAM,gBAAgB,aACnD,GAAG,EAA2B,EAAgB,CAC/C,CAAC,CACH,CACD,EACE,EACA,mGAAmG,EAAM,KAAK,GAC/G,EACD,CAIJ,eAAsB,EAAqB,EAAiC,CAC1E,IAAM,EAAS,IAAIiB,EAAAA,QACf,EACE,OACJ,IAAa,EAAO,MAAM,SAAS,CAC5B,GAGT,GAAI,CACF,EAA0B,EAAQ,EAAG,OAC9B,EAAO,CAEd,MADA,MAAM,GAAS,CACT,EAGR,EAAG,GAAG,mBAAoB,EAAQ"}
1
+ {"version":3,"file":"extension.cjs","names":["parseState","TaskStore","projectContextMessages","Worker","parseModelReference","DEFAULT_COMPACTION_SETTINGS","createAutocompactTelemetry","createInitialState","DOOM_UI_HUB_SERVICE","STATE_CUSTOM_TYPE","RESUME_MESSAGE_TYPE","AUTOCOMPACT_EVENT","RUNTIME_STATE_MESSAGE_TYPE","mergeFileDetails","fileOperationsFromMessages","withCanonicalFileSections","retainedMessagesAfterSnapshot","CONTEXT_MESSAGE_TYPE","createRequestId","checkpointSummaryFromEntry","latestCheckpointArtifactEntry","baselineUsageIsSettled","thresholdTokens","CHECKPOINT_MESSAGE_TYPE","checkpointRequestDetails","parseCheckpointDecision","isStructuredCheckpoint","fileDetailsFromUnknown"],"sources":["../../../../src/adapters/pi/extension.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { Worker } from 'node:worker_threads';\n\nimport { getHarnessState, loadDoomConfig, type PlanningAgentConfig } from '@agimon-ai/doompi-config';\nimport { connectDoomCordisHost } from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport { resolveSessionKey } from '@agimon-ai/doompi-task/store/paths';\nimport { TaskStore } from '@agimon-ai/doompi-task/store/taskStore';\nimport type { Task } from '@agimon-ai/doompi-task/store/types';\nimport { readActiveTeamSnapshot, type TeamMemberSnapshot } from '@agimon-ai/doompi-team/api/team-snapshot';\nimport type { DoomFooterContributionHandle } from '@agimon-ai/doompi-extension-contracts/footer';\nimport { DOOM_UI_HUB_SERVICE, requireDoomUiHub } from '@agimon-ai/doompi-extension-contracts/ui-hub';\nimport type { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent';\nimport {\n buildSessionContext,\n DEFAULT_COMPACTION_SETTINGS,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n createInitialState,\n createRequestId,\n fileDetailsFromUnknown,\n fileOperationsFromMessages,\n isStructuredCheckpoint,\n latestCheckpointArtifactEntry,\n mergeFileDetails,\n parseCheckpointDecision,\n parseState,\n projectContextMessages,\n retainedMessagesAfterSnapshot,\n thresholdTokens,\n withCanonicalFileSections,\n} from '../../adapters/compaction/policy';\nimport { parseModelReference, type SummarizationModel } from '../../services/summarizationModel.ts';\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type { AutocompactEventAttributes, AutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\n\nexport type { ModelReference, SummarizationModel } from '../../services/summarizationModel.ts';\nexport { parseModelReference, resolveSummarizationModel } from '../../services/summarizationModel.ts';\n\nimport type { AutocompactContextDetails, AutocompactPass, AutocompactState } from '../../types/index.ts';\n\nconst ROOT_WORKING_LEAF = '@root';\nconst PACKAGE_SOURCE = '@agimon-ai/doompi-autocompact';\nconst PLAN_DOCUMENT_ENTRY = 'agent-harness-plan-document';\nconst FOOTER_SOURCE = 'doom-autocompact';\nconst FOOTER_ORDER = 20;\nconst STATUS_KEY = 'doom-autocompact';\nconst STATE_PHASE = {\n waiting: 'waiting',\n checkpointPending: 'checkpoint_pending',\n checkpointReady: 'checkpoint_ready',\n compacting: 'compacting',\n} as const;\ntype CheckpointCapture = 'none' | 'pass1' | 'committed' | 'deferred' | 'invalid';\ntype CheckpointMessages = ReturnType<typeof buildSessionContext>['messages'];\n\ninterface PlanSnapshot {\n content: string;\n path: string;\n}\n\ninterface TaskSnapshot {\n tasks: Task[];\n error?: string;\n}\n\ninterface TeamSnapshot {\n members?: TeamMemberSnapshot[];\n error?: string;\n}\n\ninterface SteeringSnapshot {\n plan?: PlanSnapshot;\n taskSnapshot: TaskSnapshot;\n teamSnapshot: TeamSnapshot;\n readFiles: string[];\n modifiedFiles: string[];\n}\n\ninterface RuntimeTaskSnapshot {\n id: number;\n status: Task['status'];\n subject: string;\n activeForm?: string;\n owner?: string;\n blockedBy?: number[];\n delegation?: {\n agent: string;\n state: NonNullable<Task['delegation']>['state'];\n error?: string;\n };\n}\n\ninterface RuntimeStateSnapshot {\n planPath?: string;\n tasks: RuntimeTaskSnapshot[];\n taskError?: string;\n teamAvailable: boolean;\n teamMembers: TeamMemberSnapshot[];\n teamError?: string;\n}\n\ninterface CheckpointGenerationInput {\n messages: CheckpointMessages;\n instructions: string;\n previousCheckpoint?: string;\n context: ExtensionContext;\n signal: AbortSignal;\n}\n\ninterface CheckpointWorkerResult {\n checkpoint?: string;\n error?: string;\n}\n\nexport interface AutocompactDependencies {\n generateCheckpoint?: (input: CheckpointGenerationInput) => Promise<string>;\n readTaskSnapshot?: (context: ExtensionContext) => TaskSnapshot;\n readTeamSnapshot?: () => TeamSnapshot;\n resolveModel?: (context: ExtensionContext) => SummarizationModel | undefined;\n telemetry?: AutocompactTelemetry;\n doomIntegrations?: boolean;\n}\n\nfunction telemetryAttributes(\n context: ExtensionContext,\n attributes: AutocompactEventAttributes = {},\n): AutocompactEventAttributes {\n return {\n 'pi.session.id': context.sessionManager.getSessionId(),\n ...attributes,\n };\n}\n\nfunction latestPersistedState(branch: SessionEntry[]): AutocompactState | undefined {\n for (let index = branch.length - 1; index >= 0; index -= 1) {\n const entry = branch[index];\n if (entry?.type !== 'custom' || entry.customType !== STATE_CUSTOM_TYPE) continue;\n const parsed = parseState(entry.data);\n if (parsed) return parsed;\n }\n return undefined;\n}\n\nfunction workingLeafId(ctx: ExtensionContext): string {\n for (const entry of ctx.sessionManager.getBranch().toReversed()) {\n if (entry.type === 'custom' && entry.customType === STATE_CUSTOM_TYPE) continue;\n if (entry.type === 'label') continue;\n return entry.id;\n }\n return ROOT_WORKING_LEAF;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction latestPlanSnapshot(branch: SessionEntry[]): PlanSnapshot | undefined {\n for (const entry of branch.toReversed()) {\n if (entry.type !== 'custom' || entry.customType !== PLAN_DOCUMENT_ENTRY) continue;\n if (!entry.data || typeof entry.data !== 'object') return undefined;\n const data = entry.data as Record<string, unknown>;\n if (typeof data.content !== 'string' || typeof data.path !== 'string') return undefined;\n return { content: data.content, path: data.path };\n }\n return undefined;\n}\n\nfunction readTaskSnapshotWithDoomTask(context: ExtensionContext): TaskSnapshot {\n const failures: string[] = [];\n try {\n const store = new TaskStore({\n cwd: context.cwd,\n report: {\n error: (event, error) => failures.push(`${event}: ${errorMessage(error)}`),\n warn: (event, error) => failures.push(`${event}: ${errorMessage(error)}`),\n event: () => undefined,\n },\n });\n store.configureSession(resolveSessionKey(context.sessionManager.getSessionId()));\n const tasks = store.read().tasks;\n return { tasks, ...(failures.length > 0 ? { error: failures.join('; ') } : {}) };\n } catch (error) {\n return { tasks: [], error: errorMessage(error) };\n }\n}\n\nfunction readTeamSnapshotWithDoomTeam(): TeamSnapshot {\n try {\n const snapshot = readActiveTeamSnapshot();\n return snapshot ? { members: snapshot.members } : {};\n } catch (error) {\n return { error: errorMessage(error) };\n }\n}\n\nfunction activeTaskSnapshots(snapshot: TaskSnapshot): RuntimeTaskSnapshot[] {\n return snapshot.tasks\n .filter((task) => task.status === 'pending' || task.status === 'in_progress' || task.status === 'failed')\n .map((task) => ({\n id: task.id,\n status: task.status,\n subject: task.subject,\n ...(task.activeForm ? { activeForm: task.activeForm } : {}),\n ...(task.owner ? { owner: task.owner } : {}),\n ...(task.blockedBy?.length ? { blockedBy: task.blockedBy } : {}),\n ...(task.delegation\n ? {\n delegation: {\n agent: task.delegation.agent,\n state: task.delegation.state,\n ...(task.delegation.result?.error ? { error: task.delegation.result.error } : {}),\n },\n }\n : {}),\n }));\n}\n\nfunction formatRuntimeTasks(tasks: RuntimeTaskSnapshot[], error?: string): string {\n const lines = tasks.map((task) => {\n const details = [\n task.activeForm ? `active: ${task.activeForm}` : undefined,\n task.owner ? `owner: ${task.owner}` : undefined,\n task.blockedBy?.length ? `blocked by: ${task.blockedBy.join(', ')}` : undefined,\n task.delegation ? `delegation: ${task.delegation.agent} (${task.delegation.state})` : undefined,\n task.delegation?.error ? `error: ${task.delegation.error}` : undefined,\n ].filter((value): value is string => Boolean(value));\n return `- #${task.id} [${task.status}] ${task.subject}${details.length > 0 ? ` | ${details.join(' | ')}` : ''}`;\n });\n if (error) lines.push(`- Task snapshot error: ${error}`);\n return lines.length > 0 ? lines.join('\\n') : '(no active tasks)';\n}\n\nfunction formatTeamSnapshot(snapshot: TeamSnapshot): string {\n const lines = (snapshot.members ?? []).map((member) => {\n const details = [\n `role: ${member.role}`,\n member.agent ? `agent: ${member.agent}` : undefined,\n member.runId ? `run: ${member.runId}` : undefined,\n member.task ? `task ${member.task.id}: ${member.task.subject}` : undefined,\n ].filter((value): value is string => Boolean(value));\n return `- ${member.name} | ${details.join(' | ')}`;\n });\n if (snapshot.error) lines.push(`- Team snapshot error: ${snapshot.error}`);\n if (lines.length > 0) return lines.join('\\n');\n return snapshot.members ? '(no active team members)' : '(team runtime unavailable)';\n}\n\nfunction runtimeStateSnapshot(\n branch: SessionEntry[],\n taskSnapshot: TaskSnapshot,\n teamSnapshot: TeamSnapshot,\n): RuntimeStateSnapshot {\n const plan = latestPlanSnapshot(branch);\n return {\n ...(plan ? { planPath: plan.path } : {}),\n tasks: activeTaskSnapshots(taskSnapshot),\n ...(taskSnapshot.error ? { taskError: taskSnapshot.error } : {}),\n teamAvailable: Boolean(teamSnapshot.members),\n teamMembers: teamSnapshot.members ?? [],\n ...(teamSnapshot.error ? { teamError: teamSnapshot.error } : {}),\n };\n}\n\nfunction formatRuntimeState(snapshot: RuntimeStateSnapshot): string {\n const plan = snapshot.planPath\n ? `Source: ${snapshot.planPath}\\nExact plan content is restored separately by Doom Plan.`\n : '(no active plan document)';\n const teamSnapshot: TeamSnapshot = {\n ...(snapshot.teamAvailable ? { members: snapshot.teamMembers } : {}),\n ...(snapshot.teamError ? { error: snapshot.teamError } : {}),\n };\n return `<compaction-runtime-state>\nAuthoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.\n<active-plan>\n${plan}\n</active-plan>\n<active-tasks>\n${formatRuntimeTasks(snapshot.tasks, snapshot.taskError)}\n</active-tasks>\n<active-team>\n${formatTeamSnapshot(teamSnapshot)}\n</active-team>\n</compaction-runtime-state>`;\n}\n\nfunction runtimeTelemetryAttributes(snapshot: RuntimeStateSnapshot): AutocompactEventAttributes {\n return {\n 'autocompact.runtime.plan_present': Boolean(snapshot.planPath),\n 'autocompact.runtime.task_count': snapshot.tasks.length,\n 'autocompact.runtime.team_available': snapshot.teamAvailable,\n 'autocompact.runtime.team_member_count': snapshot.teamMembers.length,\n };\n}\n\nfunction steeringEnvelope(snapshot: SteeringSnapshot): string {\n const plan = snapshot.plan\n ? `Source: ${snapshot.plan.path}\\n\\n${snapshot.plan.content}`\n : '(no active plan document)';\n const importantContext = [\n snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(', ')}` : undefined,\n snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(', ')}` : undefined,\n ].filter((value): value is string => Boolean(value));\n\n return `<compaction-steering priority=\"user,plan,tasks,team,important-context,recent-messages\">\n<user-prompt source=\"conversation\">\nTreat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.\n</user-prompt>\n<active-plan>\n${plan}\n</active-plan>\n<active-tasks>\n${formatRuntimeTasks(activeTaskSnapshots(snapshot.taskSnapshot), snapshot.taskSnapshot.error)}\n</active-tasks>\n<active-team>\n${formatTeamSnapshot(snapshot.teamSnapshot)}\n</active-team>\n<important-context>\n${importantContext.length > 0 ? importantContext.join('\\n') : '(none recorded outside the conversation)'}\n</important-context>\n</compaction-steering>`;\n}\n\nfunction checkpointInstructions(pass: AutocompactPass, steering: SteeringSnapshot): string {\n const decision =\n pass === 2\n ? 'Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\\n\\n'\n : '';\n\n // Summarization is a tool-less single LLM call, so instructions describe only what to\n // produce. Directives aimed at an implementing agent leak into the checkpoint body.\n return `Create Doom autocompact checkpoint pass ${pass}.\n\n${steeringEnvelope(steering)}\n\nApply the steering evidence in priority order. Do not invent plan, task, or team state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.\n\n${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.\n\n## Goal\n## Constraints & Preferences\n## Progress\n### Done\n### In Progress\n### Blocked\n## Key Decisions\n## Next Steps\n## Critical Context`;\n}\n\nfunction messagesForCheckpoint(\n pass: AutocompactPass,\n branch: SessionEntry[],\n previousSnapshotLeafId: string | undefined,\n): CheckpointMessages {\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n if (pass === 1 || !previousSnapshotLeafId) return projected;\n const snapshotIndex = branch.findIndex((entry) => entry.id === previousSnapshotLeafId);\n if (snapshotIndex === -1) return projected;\n return branch\n .slice(snapshotIndex + 1)\n .filter((entry) => entry.type !== 'custom_message' || entry.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap((entry) => sessionEntryToContextMessages(entry));\n}\n\nexport function findCheckpointWorkerUrl(importFileUrl: string | URL): URL {\n const importFilePath = fileURLToPath(importFileUrl);\n let directory = dirname(importFilePath);\n\n while (true) {\n const workerPath = join(directory, 'checkpointWorker.mjs');\n if (existsSync(workerPath)) return pathToFileURL(workerPath);\n\n const parent = dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n\n throw new Error(`Cannot find checkpointWorker.mjs by walking from ${importFilePath}.`);\n}\n\nfunction runCheckpointWorker(workerInput: Record<string, unknown>, signal: AbortSignal): Promise<string> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(findCheckpointWorkerUrl(import.meta.url), { workerData: workerInput });\n let settled = false;\n\n const settle = (complete: () => void): void => {\n if (settled) return;\n settled = true;\n signal.removeEventListener('abort', abort);\n complete();\n };\n const abort = (): void => {\n settle(() => {\n void worker.terminate();\n reject(signal.reason instanceof Error ? signal.reason : new Error('Autocompact summarization aborted.'));\n });\n };\n\n worker.once('message', (result: CheckpointWorkerResult) => {\n settle(() => {\n if (typeof result.checkpoint === 'string') resolve(result.checkpoint);\n else reject(new Error(result.error ?? 'Autocompact summarization worker returned no checkpoint.'));\n });\n });\n worker.once('error', (error) => settle(() => reject(error)));\n worker.once('exit', (code) => {\n if (code !== 0) settle(() => reject(new Error(`Autocompact summarization worker exited with code ${code}.`)));\n });\n signal.addEventListener('abort', abort, { once: true });\n worker.unref();\n if (signal.aborted) abort();\n });\n}\n\nfunction subagentModelConfig(cwd: string): PlanningAgentConfig | undefined {\n try {\n return loadDoomConfig(getHarnessState().root ?? cwd).modes?.planning?.subagents;\n } catch {\n process.emitWarning(\n 'Doom autocompact planning configuration could not be loaded; using the active session model instead.',\n );\n return undefined;\n }\n}\n\n/** Explicit Doom model selection honors the configured planning subagent model. */\nexport function resolveDoomSummarizationModel(ctx: ExtensionContext): SummarizationModel | undefined {\n const configured = subagentModelConfig(ctx.cwd);\n const reference = configured?.model ? parseModelReference(configured.model) : undefined;\n const configuredModel = reference ? ctx.modelRegistry.find(reference.provider, reference.modelId) : undefined;\n const model = configuredModel ?? ctx.model;\n if (!model) return undefined;\n const thinkingLevel =\n configured?.thinking ?? (configuredModel ? reference?.thinking : undefined) ?? ctx.thinkingLevel;\n return { model, ...(thinkingLevel ? { thinkingLevel } : {}) };\n}\n\nasync function generateCheckpointWithPi(\n input: CheckpointGenerationInput,\n resolveModel: (context: ExtensionContext) => SummarizationModel | undefined,\n): Promise<string> {\n const selection = resolveModel(input.context);\n if (!selection) throw new Error('No active model is available for autocompact summarization.');\n const auth = await input.context.modelRegistry.getApiKeyAndHeaders(selection.model);\n if (!auth.ok) throw new Error(auth.error);\n return runCheckpointWorker(\n {\n messages: input.messages,\n model: selection.model,\n reserveTokens: DEFAULT_COMPACTION_SETTINGS.reserveTokens,\n apiKey: auth.apiKey,\n headers: auth.headers,\n instructions: input.instructions,\n previousCheckpoint: input.previousCheckpoint,\n thinkingLevel: selection.thinkingLevel,\n env: auth.env,\n },\n input.signal,\n );\n}\n\nfunction notify(ctx: ExtensionContext | undefined, message: string, level: 'info' | 'warning' | 'error' = 'info') {\n if (ctx?.hasUI) ctx.ui.notify(message, level);\n}\n\nexport function installAutocompactRuntime(\n cordis: Context,\n pi: ExtensionAPI,\n dependencies: AutocompactDependencies = {},\n): void {\n const resolveModel = dependencies.resolveModel ?? resolveDoomSummarizationModel;\n const generateCheckpoint =\n dependencies.generateCheckpoint ??\n ((input: CheckpointGenerationInput) => generateCheckpointWithPi(input, resolveModel));\n const readTaskSnapshot = dependencies.readTaskSnapshot ?? readTaskSnapshotWithDoomTask;\n const readTeamSnapshot = dependencies.readTeamSnapshot ?? readTeamSnapshotWithDoomTeam;\n const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();\n const doomIntegrations = dependencies.doomIntegrations ?? true;\n const appliedContextRequests = new Set<string>();\n const invalidContextLeaves = new Set<string>();\n const checkpointWork = new Set<Promise<void>>();\n let active = true;\n let sessionGeneration = 0;\n let state = createInitialState();\n let currentContext: ExtensionContext | undefined;\n let checkpointController: AbortController | undefined;\n let footerContribution: DoomFooterContributionHandle | undefined;\n\n cordis.effect(\n () => async () => {\n active = false;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact runtime is shutting down.'));\n checkpointController = undefined;\n await Promise.allSettled(checkpointWork);\n footerContribution = undefined;\n currentContext = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n state = createInitialState();\n await telemetry.shutdown();\n },\n `${FOOTER_SOURCE}/runtime`,\n );\n\n if (doomIntegrations) {\n cordis.inject([DOOM_UI_HUB_SERVICE], (uiContext) => {\n const contribution = requireDoomUiHub(uiContext).registerFooter({\n source: FOOTER_SOURCE,\n id: 'autocompact',\n order: FOOTER_ORDER,\n });\n footerContribution = contribution;\n return () => {\n contribution.dispose();\n if (footerContribution === contribution) footerContribution = undefined;\n };\n });\n }\n\n /** Compaction runs off the main thread, so the phase is the only signal the user gets. */\n const refreshStatus = (ctx?: ExtensionContext): void => {\n if (!active) return;\n const phase =\n state.phase === STATE_PHASE.checkpointPending\n ? 'summarizing'\n : state.phase === STATE_PHASE.checkpointReady\n ? 'applying'\n : undefined;\n footerContribution?.update(\n phase ? { fullText: `Compacting p${state.pass}`, compactText: `C${state.pass}` } : undefined,\n );\n const target = ctx ?? currentContext;\n if (target?.hasUI) target.ui.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : undefined);\n };\n\n // Every phase transition persists, so this is the one place that keeps the status honest.\n const persist = (): void => {\n if (!active) return;\n pi.appendEntry(STATE_CUSTOM_TYPE, { ...state });\n refreshStatus();\n };\n\n const clearPendingCheckpoint = (): void => {\n delete state.requestId;\n delete state.snapshotLeafId;\n delete state.snapshotTokens;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n };\n\n const completeQueuedPass = (pass: AutocompactPass): void => {\n state.checkpointQueue = state.checkpointQueue.filter((queuedPass) => queuedPass !== pass);\n };\n\n const restore = (ctx: ExtensionContext): void => {\n if (!active) return;\n state = latestPersistedState(ctx.sessionManager.getBranch()) ?? createInitialState();\n const resumablePending =\n state.phase === STATE_PHASE.checkpointReady && state.requestId && state.snapshotLeafId && state.pendingCheckpoint;\n if (resumablePending || state.phase === STATE_PHASE.waiting) return;\n\n checkpointController?.abort();\n checkpointController = undefined;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n persist();\n };\n\n const resumeAgent = (message: string): void => {\n if (!active) return;\n pi.sendMessage(\n {\n customType: RESUME_MESSAGE_TYPE,\n content: `${message} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,\n display: false,\n details: { version: STATE_VERSION, cycle: state.cycle, pass: state.pass },\n },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n };\n\n const failCheckpoint = (requestId: string, error: unknown): void => {\n if (!active || requestId !== state.requestId || state.phase !== STATE_PHASE.checkpointPending) return;\n const failedLeafId = state.snapshotLeafId;\n state.phase = STATE_PHASE.waiting;\n if (failedLeafId) state.lastAttemptLeafId = failedLeafId;\n clearPendingCheckpoint();\n persist();\n notify(\n currentContext,\n `Doom autocompact summarization pass ${state.pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n 'error',\n );\n };\n\n const reportSnapshotFailures = (\n ctx: ExtensionContext,\n taskSnapshot: TaskSnapshot,\n teamSnapshot: TeamSnapshot,\n attributes: AutocompactEventAttributes,\n ): void => {\n if (!active) return;\n if (taskSnapshot.error) {\n notify(ctx, `Doom autocompact task steering degraded: ${taskSnapshot.error}`, 'warning');\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.taskSnapshotDegraded, new Error(taskSnapshot.error), attributes);\n }\n if (teamSnapshot.error) {\n notify(ctx, `Doom autocompact team steering degraded: ${teamSnapshot.error}`, 'warning');\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.teamSnapshotDegraded, new Error(teamSnapshot.error), attributes);\n }\n };\n\n const preserveRuntimeState = (\n ctx: ExtensionContext,\n branch: SessionEntry[],\n attributes: AutocompactEventAttributes,\n ): RuntimeStateSnapshot => {\n if (!active) {\n return { tasks: [], teamAvailable: false, teamMembers: [] };\n }\n const taskSnapshot = readTaskSnapshot(ctx);\n const teamSnapshot = readTeamSnapshot();\n reportSnapshotFailures(ctx, taskSnapshot, teamSnapshot, attributes);\n const snapshot = runtimeStateSnapshot(branch, taskSnapshot, teamSnapshot);\n pi.sendMessage({\n customType: RUNTIME_STATE_MESSAGE_TYPE,\n content: formatRuntimeState(snapshot),\n display: false,\n details: { version: 1, ...snapshot },\n });\n return snapshot;\n };\n\n const commitCheckpoint = (pass: 2 | 3, ctx: ExtensionContext): boolean => {\n if (!active || !state.requestId || !state.snapshotLeafId || !state.pendingCheckpoint) return false;\n const branch = ctx.sessionManager.getBranch();\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n const fileDetails = mergeFileDetails(state, fileOperationsFromMessages(projected));\n const requestId = state.requestId;\n const cycle = state.cycle;\n const summary = withCanonicalFileSections(state.pendingCheckpoint, fileDetails);\n const details: AutocompactContextDetails = {\n ...fileDetails,\n doomAutocompact: {\n version: STATE_VERSION,\n cycle,\n pass,\n requestId,\n snapshotLeafId: state.snapshotLeafId,\n tokensBefore: state.snapshotTokens ?? ctx.getContextUsage()?.tokens ?? 0,\n },\n retainedMessages: retainedMessagesAfterSnapshot(branch, state.snapshotLeafId),\n };\n\n notify(ctx, `Doom autocompact pass ${pass} context commit started.`);\n const committedWhileIdle = ctx.isIdle();\n pi.sendMessage({ customType: CONTEXT_MESSAGE_TYPE, content: summary, display: false, details });\n const contextMessageLeafId = workingLeafId(ctx);\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, branch, runtimeAttributes);\n // Mid-run the marker is queued as a steering message, so its entry id is not resolvable yet.\n if (committedWhileIdle) pi.setLabel(contextMessageLeafId, `autocompact:c${cycle}:p${pass}`);\n\n state.readFiles = fileDetails.readFiles;\n state.modifiedFiles = fileDetails.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n state.phase = STATE_PHASE.waiting;\n state.checkpointQueue = [];\n // A compacted context is a fresh ladder: passes abandoned in the previous cycle are eligible again.\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n state.baselinePending = true;\n delete state.lastAttemptLeafId;\n clearPendingCheckpoint();\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextCommitted,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': details.doomAutocompact.snapshotLeafId,\n 'autocompact.tokens_before': details.doomAutocompact.tokensBefore,\n 'autocompact.message_count.before': projected.length,\n 'autocompact.message_count.retained': details.retainedMessages.length,\n 'autocompact.apply_mode': committedWhileIdle ? 'idle' : 'turn_end',\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n notify(ctx, `Doom autocompact context committed. Baseline will be captured from the next settled context.`);\n // A mid-run commit needs no resume steer: the agent is already continuing.\n if (committedWhileIdle) resumeAgent('Asynchronous compaction completed.');\n return true;\n };\n\n const requestCheckpoint = (pass: AutocompactPass, ctx: ExtensionContext, tokensBefore: number): void => {\n if (!active) return;\n const generation = sessionGeneration;\n const branch = ctx.sessionManager.getBranch();\n const snapshotLeafId = workingLeafId(ctx);\n const requestId = createRequestId(ctx.sessionManager.getSessionId(), state.cycle, pass, snapshotLeafId);\n const previousCheckpoint = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(branch)) : undefined;\n const messages = messagesForCheckpoint(pass, branch, state.latestCheckpointSnapshotLeafId);\n const taskSnapshot = readTaskSnapshot(ctx);\n const teamSnapshot = readTeamSnapshot();\n const attributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': snapshotLeafId,\n 'autocompact.tokens_before': tokensBefore,\n 'autocompact.message_count.before': messages.length,\n });\n reportSnapshotFailures(ctx, taskSnapshot, teamSnapshot, attributes);\n\n state.phase = STATE_PHASE.checkpointPending;\n state.pass = pass;\n state.requestId = requestId;\n state.snapshotLeafId = snapshotLeafId;\n state.snapshotTokens = tokensBefore;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n delete state.lastAttemptLeafId;\n persist();\n\n checkpointController?.abort();\n checkpointController = new AbortController();\n const checkpointSignal = checkpointController.signal;\n notify(ctx, `Doom autocompact summarization pass ${pass} started.`);\n const operation = telemetry\n .runInSpan('doom_autocompact.checkpoint', attributes, async () => {\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, attributes);\n try {\n const checkpoint = await generateCheckpoint({\n messages,\n instructions: checkpointInstructions(pass, {\n plan: latestPlanSnapshot(branch),\n taskSnapshot,\n teamSnapshot,\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n }),\n ...(previousCheckpoint ? { previousCheckpoint } : {}),\n context: ctx,\n signal: checkpointSignal,\n });\n if (!active || generation !== sessionGeneration) {\n throw checkpointSignal.reason ?? new Error('Autocompact checkpoint became stale.');\n }\n if (!checkpoint.trim()) throw new Error('Summarization returned an empty checkpoint.');\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {\n ...attributes,\n 'autocompact.checkpoint.characters': checkpoint.length,\n });\n return checkpoint;\n } catch (error) {\n if (active && generation === sessionGeneration) {\n await telemetry.recordError(AUTOCOMPACT_EVENT.checkpointFailed, error, attributes);\n }\n throw error;\n }\n })\n .then((checkpoint) => {\n if (\n !active ||\n generation !== sessionGeneration ||\n requestId !== state.requestId ||\n state.phase !== STATE_PHASE.checkpointPending\n ) {\n return;\n }\n state.phase = STATE_PHASE.checkpointReady;\n state.pendingCheckpoint = checkpoint.trim();\n persist();\n notify(currentContext, `Doom autocompact summarization pass ${pass} completed.`);\n if (currentContext) processProgress(currentContext);\n })\n .catch((error: unknown) => {\n if (active && generation === sessionGeneration) failCheckpoint(requestId, error);\n });\n checkpointWork.add(operation);\n void operation.finally(() => checkpointWork.delete(operation));\n };\n\n const evaluateUsage = (ctx: ExtensionContext): boolean => {\n if (!active || state.phase !== STATE_PHASE.waiting || ctx.hasPendingMessages()) return false;\n const usage = ctx.getContextUsage();\n if (!usage || usage.tokens === null) return false;\n if (state.baselinePending) {\n // Reported usage still describes the pre-compaction context until an assistant\n // responds against the projected one, and capturing it early poisons every threshold.\n if (!baselineUsageIsSettled(ctx.sessionManager.getBranch())) return false;\n state.baselineTokens = usage.tokens;\n state.baselinePending = false;\n persist();\n notify(ctx, `Doom autocompact baseline captured at ${state.baselineTokens} tokens.`);\n return false;\n }\n const leafId = workingLeafId(ctx);\n if (state.lastAttemptLeafId === leafId) return false;\n\n for (const pass of [1, 2, 3] as const) {\n if (pass < state.pass || state.checkpointQueue.includes(pass) || state.exhaustedPasses.includes(pass)) continue;\n if (usage.tokens >= thresholdTokens(pass, usage.contextWindow, state.baselineTokens)) {\n state.checkpointQueue.push(pass);\n }\n }\n const nextPass = state.checkpointQueue[0];\n if (!nextPass) return false;\n requestCheckpoint(nextPass, ctx, usage.tokens);\n return true;\n };\n\n // Staged checkpoints seed the next summarization pass only. They are appended as plain\n // session entries so they never enter the agent's LLM context: delivering them as messages\n // reads like a user instruction and derails the run (\"Checkpoint acknowledged...\").\n const stageCheckpoint = (pass: 1 | 2, summary: string): void => {\n if (!active) return;\n const checkpointSnapshotLeafId = state.snapshotLeafId;\n pi.appendEntry(CHECKPOINT_MESSAGE_TYPE, {\n ...checkpointRequestDetails(state.cycle, pass, state.requestId ?? 'completed'),\n summary,\n });\n if (checkpointSnapshotLeafId) state.latestCheckpointSnapshotLeafId = checkpointSnapshotLeafId;\n };\n\n const captureReadyCheckpoint = (ctx: ExtensionContext): CheckpointCapture => {\n if (!active || state.phase !== STATE_PHASE.checkpointReady || !state.requestId || !state.pendingCheckpoint) {\n return 'none';\n }\n const pass = state.pass;\n const decision = parseCheckpointDecision(state.pendingCheckpoint);\n if (!isStructuredCheckpoint(decision.summary)) {\n const failedLeafId = state.snapshotLeafId;\n const invalidRequestId = state.requestId;\n // A queued pass is retried once per new leaf, so an output the summarizer never formats\n // correctly would otherwise burn a full summarization call every turn for the session.\n const attempts = state.invalidAttempts + 1;\n const exhausted = attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS;\n state.phase = STATE_PHASE.waiting;\n if (failedLeafId) state.lastAttemptLeafId = failedLeafId;\n if (exhausted) {\n completeQueuedPass(pass);\n state.exhaustedPasses = [...state.exhaustedPasses, pass];\n state.invalidAttempts = 0;\n } else {\n state.invalidAttempts = attempts;\n }\n clearPendingCheckpoint();\n persist();\n const error = new Error(`Summarization pass ${pass} returned an incomplete checkpoint.`);\n notify(\n ctx,\n exhausted\n ? `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint ${attempts} times and was abandoned.`\n : `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint.`,\n 'error',\n );\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.checkpointInvalid,\n error,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': exhausted,\n ...(invalidRequestId ? { 'autocompact.request.id': invalidRequestId } : {}),\n }),\n );\n return 'invalid';\n }\n\n state.invalidAttempts = 0;\n\n if (pass === 1) {\n stageCheckpoint(1, decision.summary);\n completeQueuedPass(1);\n state.phase = STATE_PHASE.waiting;\n state.pass = 2;\n clearPendingCheckpoint();\n persist();\n return 'pass1';\n }\n\n if (pass === 2 && decision.shouldCompact !== true) {\n stageCheckpoint(2, decision.summary);\n completeQueuedPass(2);\n state.phase = STATE_PHASE.waiting;\n state.pass = 3;\n clearPendingCheckpoint();\n persist();\n return 'deferred';\n }\n\n state.pendingCheckpoint = decision.summary;\n return commitCheckpoint(pass, ctx) ? 'committed' : 'invalid';\n };\n\n function processProgress(ctx: ExtensionContext): void {\n if (!active) return;\n currentContext = ctx;\n if (!ctx.isIdle()) return;\n if (captureReadyCheckpoint(ctx) !== 'committed') evaluateUsage(ctx);\n }\n\n pi.on('context', (event, ctx) => {\n if (!active) return undefined;\n const projection = projectContextMessages(event.messages, ctx.sessionManager.getBranch());\n if (projection.invalidMarker) {\n const leafId = ctx.sessionManager.getLeafId() ?? ROOT_WORKING_LEAF;\n if (!invalidContextLeaves.has(leafId)) {\n invalidContextLeaves.add(leafId);\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.contextMarkerInvalid,\n new Error('Doom autocompact context marker is malformed.'),\n telemetryAttributes(ctx, { 'autocompact.leaf_id': leafId }),\n );\n }\n return undefined;\n }\n if (!projection.marker) return undefined;\n if (!appliedContextRequests.has(projection.marker.requestId)) {\n appliedContextRequests.add(projection.marker.requestId);\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextApplied,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': projection.marker.requestId,\n 'autocompact.cycle': projection.marker.cycle,\n 'autocompact.pass': projection.marker.pass,\n 'autocompact.snapshot_leaf_id': projection.marker.snapshotLeafId,\n 'autocompact.tokens_before': projection.marker.tokensBefore,\n 'autocompact.message_count.before': event.messages.length,\n 'autocompact.message_count.after': projection.messages.length,\n 'autocompact.message_count.retained': projection.retainedMessageCount,\n }),\n );\n }\n return { messages: projection.messages };\n });\n\n const beginSessionGeneration = (ctx: ExtensionContext): void => {\n if (!active) return;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact session generation was replaced.'));\n checkpointController = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n currentContext = ctx;\n restore(ctx);\n processProgress(ctx);\n };\n\n pi.on('session_start', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('session_tree', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('turn_end', (event, ctx) => {\n if (!active) return;\n currentContext = ctx;\n if (ctx.isIdle()) {\n processProgress(ctx);\n return;\n }\n // A ready checkpoint must be applied without waiting for the run to finish, otherwise\n // context keeps growing past the window for the rest of a long autonomous run. Tool\n // results confirm the run continues, so the queued marker lands before the next request.\n const canApplyDuringRun =\n state.phase === STATE_PHASE.checkpointReady && (event.toolResults?.length ?? 0) > 0 && !ctx.hasPendingMessages();\n if (canApplyDuringRun && captureReadyCheckpoint(ctx) !== 'none') return;\n evaluateUsage(ctx);\n });\n\n pi.on('agent_settled', (_event, ctx) => {\n if (!active) return;\n processProgress(ctx);\n });\n\n pi.on('session_before_compact', (event) => {\n if (!active || event.reason !== 'threshold') return undefined;\n // Native compaction stays cancelled while our own machinery is working, and stays\n // available as the emergency backstop once that machinery has stalled or declined.\n const machineryActive =\n state.phase === STATE_PHASE.checkpointPending ||\n state.phase === STATE_PHASE.checkpointReady ||\n state.baselinePending;\n return machineryActive ? { cancel: true } : undefined;\n });\n\n pi.on('session_compact', (event, ctx) => {\n if (!active) return;\n sessionGeneration += 1;\n // Native compaction supersedes any summarization still in flight.\n checkpointController?.abort();\n checkpointController = undefined;\n const eventDetails = fileDetailsFromUnknown(event.compactionEntry.details);\n const cumulative = mergeFileDetails(state, undefined, eventDetails);\n state.readFiles = cumulative.readFiles;\n state.modifiedFiles = cumulative.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n // Reported usage still describes the pre-compaction context here too, so the baseline\n // waits for the first assistant response measured against the compacted one.\n state.baselinePending = true;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n state.checkpointQueue = [];\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n delete state.lastAttemptLeafId;\n\n pi.setLabel(event.compactionEntry.id, `autocompact:c${state.cycle}:external`);\n const completedCycle = state.cycle;\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, ctx.sessionManager.getBranch(), runtimeAttributes);\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.nativeCompactionCompleted,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n 'autocompact.native.from_extension': event.fromExtension,\n 'autocompact.tokens_before': event.compactionEntry.tokensBefore,\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n notify(\n ctx,\n `Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${state.pass}.`,\n );\n });\n}\n\n/** The package's single standard Pi factory. */\nexport async function autocompactExtension(pi: ExtensionAPI): Promise<void> {\n const connection = await connectDoomCordisHost(pi, PACKAGE_SOURCE);\n const fiber = connection.root.plugin(autocompactPlugin, { pi });\n try {\n await fiber;\n } catch (error) {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n throw error;\n }\n let disposal: Promise<void> | undefined;\n pi.on(\n 'session_shutdown',\n () =>\n (disposal ??= (async () => {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n })()),\n );\n}\n\ninterface AutocompactPluginConfig {\n readonly pi: ExtensionAPI;\n}\n\nfunction autocompactPlugin(cordis: Context, config: AutocompactPluginConfig): void {\n installAutocompactRuntime(cordis, config.pi);\n}\n\nexport default autocompactExtension;\n"],"mappings":"koBAwDA,MAAM,EAAoB,QAGpB,EAAgB,mBAGhB,EAAc,CAClB,QAAS,UACT,kBAAmB,qBACnB,gBAAiB,mBACjB,WAAY,aACb,CAwED,SAAS,EACP,EACA,EAAyC,EAAE,CACf,CAC5B,MAAO,CACL,gBAAiB,EAAQ,eAAe,cAAc,CACtD,GAAG,EACJ,CAGH,SAAS,EAAqB,EAAsD,CAClF,IAAK,IAAI,EAAQ,EAAO,OAAS,EAAG,GAAS,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AA;EAC9C,SAAA,GAAY,oBAAA;EACZ,gBAAA;AAAA;AAAA,iBAyVc,yBAAA,CACd,MAAA,EAAQ,OAAA,EACR,EAAA,EAAI,YAAA,EACJ,YAAA,GAAc,uBAAA;;iBA0jBM,oBAAA,CAAqB,EAAA,EAAI,YAAA,GAAe,OAAA"}
1
+ {"version":3,"file":"extension.d.cts","names":[],"sources":["../../../../src/adapters/pi/extension.ts"],"mappings":";;;;;;;;KAqEK,kBAAA,GAAqB,UAAA,QAAkB,mBAAA;AAAA,UAOlC,YAAA;EACR,KAAA,EAAO,IAAA;EACP,KAAA;AAAA;AAAA,UAGQ,YAAA;EACR,OAAA,GAAU,kBAAA;EACV,KAAA;AAAA;AAAA,UAkCQ,yBAAA;EACR,QAAA,EAAU,kBAAA;EACV,YAAA;EACA,kBAAA;EACA,OAAA,EAAS,gBAAA;EACT,MAAA,EAAQ,WAAA;AAAA;AAAA,UAQO,uBAAA;EACf,kBAAA,IAAsB,KAAA,EAAO,yBAAA,KAA8B,OAAA;EAC3D,gBAAA,IAAoB,OAAA,EAAS,gBAAA,KAAqB,YAAA;EAClD,gBAAA,SAAyB,YAAA;EACzB,YAAA,IAAgB,OAAA,EAAS,gBAAA,KAAqB,kBAAA;EAC9C,SAAA,GAAY,oBAAA;EACZ,gBAAA;AAAA;AAAA,iBAyVc,yBAAA,CACd,MAAA,EAAQ,OAAA,EACR,EAAA,EAAI,YAAA,EACJ,YAAA,GAAc,uBAAA;;iBAgkBM,oBAAA,CAAqB,EAAA,EAAI,YAAA,GAAe,OAAA"}
@@ -1,9 +1,9 @@
1
1
  import { SummarizationModel } from "../../services/summarizationModel.mjs";
2
2
  import { AutocompactTelemetry } from "../telemetry/logSinkTelemetry.mjs";
3
3
  import { TeamMemberSnapshot } from "@agimon-ai/doompi-team/api/team-snapshot";
4
- import { Context } from "@deepseek-ai/cordis";
5
4
  import { ExtensionAPI, ExtensionContext, buildSessionContext } from "@earendil-works/pi-coding-agent";
6
5
  import { Task } from "@agimon-ai/doompi-task/store/types";
6
+ import { Context } from "@deepseek-ai/cordis";
7
7
 
8
8
  //#region src/adapters/pi/extension.d.ts
9
9
  type CheckpointMessages = ReturnType<typeof buildSessionContext>['messages'];
@@ -1 +1 @@
1
- {"version":3,"file":"extension.d.mts","names":[],"sources":["../../../../src/adapters/pi/extension.ts"],"mappings":";;;;;;;;KAkEK,kBAAA,GAAqB,UAAA,QAAkB,mBAAA;AAAA,UAOlC,YAAA;EACR,KAAA,EAAO,IAAA;EACP,KAAA;AAAA;AAAA,UAGQ,YAAA;EACR,OAAA,GAAU,kBAAA;EACV,KAAA;AAAA;AAAA,UAkCQ,yBAAA;EACR,QAAA,EAAU,kBAAA;EACV,YAAA;EACA,kBAAA;EACA,OAAA,EAAS,gBAAA;EACT,MAAA,EAAQ,WAAA;AAAA;AAAA,UAQO,uBAAA;EACf,kBAAA,IAAsB,KAAA,EAAO,yBAAA,KAA8B,OAAA;EAC3D,gBAAA,IAAoB,OAAA,EAAS,gBAAA,KAAqB,YAAA;EAClD,gBAAA,SAAyB,YAAA;EACzB,YAAA,IAAgB,OAAA,EAAS,gBAAA,KAAqB,kBAAA;EAC9C,SAAA,GAAY,oBAAA;EACZ,gBAAA;AAAA;AAAA,iBAyVc,yBAAA,CACd,MAAA,EAAQ,OAAA,EACR,EAAA,EAAI,YAAA,EACJ,YAAA,GAAc,uBAAA;;iBA0jBM,oBAAA,CAAqB,EAAA,EAAI,YAAA,GAAe,OAAA"}
1
+ {"version":3,"file":"extension.d.mts","names":[],"sources":["../../../../src/adapters/pi/extension.ts"],"mappings":";;;;;;;;KAqEK,kBAAA,GAAqB,UAAA,QAAkB,mBAAA;AAAA,UAOlC,YAAA;EACR,KAAA,EAAO,IAAA;EACP,KAAA;AAAA;AAAA,UAGQ,YAAA;EACR,OAAA,GAAU,kBAAA;EACV,KAAA;AAAA;AAAA,UAkCQ,yBAAA;EACR,QAAA,EAAU,kBAAA;EACV,YAAA;EACA,kBAAA;EACA,OAAA,EAAS,gBAAA;EACT,MAAA,EAAQ,WAAA;AAAA;AAAA,UAQO,uBAAA;EACf,kBAAA,IAAsB,KAAA,EAAO,yBAAA,KAA8B,OAAA;EAC3D,gBAAA,IAAoB,OAAA,EAAS,gBAAA,KAAqB,YAAA;EAClD,gBAAA,SAAyB,YAAA;EACzB,YAAA,IAAgB,OAAA,EAAS,gBAAA,KAAqB,kBAAA;EAC9C,SAAA,GAAY,oBAAA;EACZ,gBAAA;AAAA;AAAA,iBAyVc,yBAAA,CACd,MAAA,EAAQ,OAAA,EACR,EAAA,EAAI,YAAA,EACJ,YAAA,GAAc,uBAAA;;iBAgkBM,oBAAA,CAAqB,EAAA,EAAI,YAAA,GAAe,OAAA"}
@@ -1,17 +1,17 @@
1
- import{CHECKPOINT_MESSAGE_TYPE as e,CONTEXT_MESSAGE_TYPE as t,RESUME_MESSAGE_TYPE as n,RUNTIME_STATE_MESSAGE_TYPE as r,STATE_CUSTOM_TYPE as i}from"../../types/constants.mjs";import{baselineUsageIsSettled as a,checkpointRequestDetails as o,checkpointSummaryFromEntry as s,createInitialState as c,createRequestId as l,fileDetailsFromUnknown as u,fileOperationsFromMessages as d,isStructuredCheckpoint as f,latestCheckpointArtifactEntry as p,mergeFileDetails as m,parseCheckpointDecision as h,parseState as g,projectContextMessages as _,retainedMessagesAfterSnapshot as ee,thresholdTokens as te,withCanonicalFileSections as ne}from"../compaction/policy.mjs";import{parseModelReference as v}from"../../services/summarizationModel.mjs";import{AUTOCOMPACT_EVENT as y,createAutocompactTelemetry as re}from"../telemetry/logSinkTelemetry.mjs";import{existsSync as b}from"node:fs";import{dirname as x,join as S}from"node:path";import{fileURLToPath as C,pathToFileURL as w}from"node:url";import{Worker as T}from"node:worker_threads";import{getHarnessState as E,loadDoomConfig as D}from"@agimon-ai/doompi-config";import{resolveSessionKey as O}from"@agimon-ai/doompi-task/store/paths";import{TaskStore as k}from"@agimon-ai/doompi-task/store/taskStore";import{readActiveTeamSnapshot as A}from"@agimon-ai/doompi-team/api/team-snapshot";import{registerDoomFooterContribution as ie}from"@agimon-ai/doompi-ui/footer";import{Context as j}from"@deepseek-ai/cordis";import{DEFAULT_COMPACTION_SETTINGS as M,buildSessionContext as N,sessionEntryToContextMessages as P}from"@earendil-works/pi-coding-agent";const ae=`@root`,F=`doom-autocompact`,I={waiting:`waiting`,checkpointPending:`checkpoint_pending`,checkpointReady:`checkpoint_ready`,compacting:`compacting`};function L(e,t={}){return{"pi.session.id":e.sessionManager.getSessionId(),...t}}function oe(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.type!==`custom`||n.customType!==`doom-autocompact-state`)continue;let r=g(n.data);if(r)return r}}function R(e){for(let t of e.sessionManager.getBranch().toReversed())if(!(t.type===`custom`&&t.customType===`doom-autocompact-state`)&&t.type!==`label`)return t.id;return ae}function z(e){return e instanceof Error?e.message:String(e)}function B(e){for(let t of e.toReversed()){if(t.type!==`custom`||t.customType!==`agent-harness-plan-document`)continue;if(!t.data||typeof t.data!=`object`)return;let e=t.data;return typeof e.content!=`string`||typeof e.path!=`string`?void 0:{content:e.content,path:e.path}}}function se(e){let t=[];try{let n=new k({cwd:e.cwd,report:{error:(e,n)=>t.push(`${e}: ${z(n)}`),warn:(e,n)=>t.push(`${e}: ${z(n)}`),event:()=>void 0}});return n.configureSession(O(e.sessionManager.getSessionId())),{tasks:n.read().tasks,...t.length>0?{error:t.join(`; `)}:{}}}catch(e){return{tasks:[],error:z(e)}}}function ce(){try{let e=A();return e?{members:e.members}:{}}catch(e){return{error:z(e)}}}function V(e){return e.tasks.filter(e=>e.status===`pending`||e.status===`in_progress`||e.status===`failed`).map(e=>({id:e.id,status:e.status,subject:e.subject,...e.activeForm?{activeForm:e.activeForm}:{},...e.owner?{owner:e.owner}:{},...e.blockedBy?.length?{blockedBy:e.blockedBy}:{},...e.delegation?{delegation:{agent:e.delegation.agent,state:e.delegation.state,...e.delegation.result?.error?{error:e.delegation.result.error}:{}}}:{}}))}function H(e,t){let n=e.map(e=>{let t=[e.activeForm?`active: ${e.activeForm}`:void 0,e.owner?`owner: ${e.owner}`:void 0,e.blockedBy?.length?`blocked by: ${e.blockedBy.join(`, `)}`:void 0,e.delegation?`delegation: ${e.delegation.agent} (${e.delegation.state})`:void 0,e.delegation?.error?`error: ${e.delegation.error}`:void 0].filter(e=>!!e);return`- #${e.id} [${e.status}] ${e.subject}${t.length>0?` | ${t.join(` | `)}`:``}`});return t&&n.push(`- Task snapshot error: ${t}`),n.length>0?n.join(`
2
- `):`(no active tasks)`}function U(e){let t=(e.members??[]).map(e=>{let t=[`role: ${e.role}`,e.agent?`agent: ${e.agent}`:void 0,e.runId?`run: ${e.runId}`:void 0,e.task?`task ${e.task.id}: ${e.task.subject}`:void 0].filter(e=>!!e);return`- ${e.name} | ${t.join(` | `)}`});return e.error&&t.push(`- Team snapshot error: ${e.error}`),t.length>0?t.join(`
3
- `):e.members?`(no active team members)`:`(team runtime unavailable)`}function le(e,t,n){let r=B(e);return{...r?{planPath:r.path}:{},tasks:V(t),...t.error?{taskError:t.error}:{},teamAvailable:!!n.members,teamMembers:n.members??[],...n.error?{teamError:n.error}:{}}}function ue(e){let t=e.planPath?`Source: ${e.planPath}\nExact plan content is restored separately by Doom Plan.`:`(no active plan document)`,n={...e.teamAvailable?{members:e.teamMembers}:{},...e.teamError?{error:e.teamError}:{}};return`<compaction-runtime-state>
1
+ import{CHECKPOINT_MESSAGE_TYPE as e,CONTEXT_MESSAGE_TYPE as t,RESUME_MESSAGE_TYPE as n,RUNTIME_STATE_MESSAGE_TYPE as r,STATE_CUSTOM_TYPE as i}from"../../types/constants.mjs";import{baselineUsageIsSettled as a,checkpointRequestDetails as o,checkpointSummaryFromEntry as s,createInitialState as c,createRequestId as l,fileDetailsFromUnknown as u,fileOperationsFromMessages as d,isStructuredCheckpoint as f,latestCheckpointArtifactEntry as p,mergeFileDetails as m,parseCheckpointDecision as h,parseState as g,projectContextMessages as _,retainedMessagesAfterSnapshot as ee,thresholdTokens as te,withCanonicalFileSections as ne}from"../compaction/policy.mjs";import{parseModelReference as v}from"../../services/summarizationModel.mjs";import{AUTOCOMPACT_EVENT as y,createAutocompactTelemetry as re}from"../telemetry/logSinkTelemetry.mjs";import{existsSync as b}from"node:fs";import{dirname as x,join as S}from"node:path";import{fileURLToPath as C,pathToFileURL as w}from"node:url";import{Worker as T}from"node:worker_threads";import{getHarnessState as E,loadDoomConfig as D}from"@agimon-ai/doompi-config";import{connectDoomCordisHost as O}from"@agimon-ai/doompi-extension-contracts/cordis-host";import{resolveSessionKey as k}from"@agimon-ai/doompi-task/store/paths";import{TaskStore as A}from"@agimon-ai/doompi-task/store/taskStore";import{readActiveTeamSnapshot as j}from"@agimon-ai/doompi-team/api/team-snapshot";import{DOOM_UI_HUB_SERVICE as ie,requireDoomUiHub as ae}from"@agimon-ai/doompi-extension-contracts/ui-hub";import{DEFAULT_COMPACTION_SETTINGS as M,buildSessionContext as N,sessionEntryToContextMessages as P}from"@earendil-works/pi-coding-agent";const F=`@root`,I=`doom-autocompact`,L={waiting:`waiting`,checkpointPending:`checkpoint_pending`,checkpointReady:`checkpoint_ready`,compacting:`compacting`};function R(e,t={}){return{"pi.session.id":e.sessionManager.getSessionId(),...t}}function oe(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.type!==`custom`||n.customType!==`doom-autocompact-state`)continue;let r=g(n.data);if(r)return r}}function z(e){for(let t of e.sessionManager.getBranch().toReversed())if(!(t.type===`custom`&&t.customType===`doom-autocompact-state`)&&t.type!==`label`)return t.id;return F}function B(e){return e instanceof Error?e.message:String(e)}function V(e){for(let t of e.toReversed()){if(t.type!==`custom`||t.customType!==`agent-harness-plan-document`)continue;if(!t.data||typeof t.data!=`object`)return;let e=t.data;return typeof e.content!=`string`||typeof e.path!=`string`?void 0:{content:e.content,path:e.path}}}function se(e){let t=[];try{let n=new A({cwd:e.cwd,report:{error:(e,n)=>t.push(`${e}: ${B(n)}`),warn:(e,n)=>t.push(`${e}: ${B(n)}`),event:()=>void 0}});return n.configureSession(k(e.sessionManager.getSessionId())),{tasks:n.read().tasks,...t.length>0?{error:t.join(`; `)}:{}}}catch(e){return{tasks:[],error:B(e)}}}function ce(){try{let e=j();return e?{members:e.members}:{}}catch(e){return{error:B(e)}}}function H(e){return e.tasks.filter(e=>e.status===`pending`||e.status===`in_progress`||e.status===`failed`).map(e=>({id:e.id,status:e.status,subject:e.subject,...e.activeForm?{activeForm:e.activeForm}:{},...e.owner?{owner:e.owner}:{},...e.blockedBy?.length?{blockedBy:e.blockedBy}:{},...e.delegation?{delegation:{agent:e.delegation.agent,state:e.delegation.state,...e.delegation.result?.error?{error:e.delegation.result.error}:{}}}:{}}))}function U(e,t){let n=e.map(e=>{let t=[e.activeForm?`active: ${e.activeForm}`:void 0,e.owner?`owner: ${e.owner}`:void 0,e.blockedBy?.length?`blocked by: ${e.blockedBy.join(`, `)}`:void 0,e.delegation?`delegation: ${e.delegation.agent} (${e.delegation.state})`:void 0,e.delegation?.error?`error: ${e.delegation.error}`:void 0].filter(e=>!!e);return`- #${e.id} [${e.status}] ${e.subject}${t.length>0?` | ${t.join(` | `)}`:``}`});return t&&n.push(`- Task snapshot error: ${t}`),n.length>0?n.join(`
2
+ `):`(no active tasks)`}function W(e){let t=(e.members??[]).map(e=>{let t=[`role: ${e.role}`,e.agent?`agent: ${e.agent}`:void 0,e.runId?`run: ${e.runId}`:void 0,e.task?`task ${e.task.id}: ${e.task.subject}`:void 0].filter(e=>!!e);return`- ${e.name} | ${t.join(` | `)}`});return e.error&&t.push(`- Team snapshot error: ${e.error}`),t.length>0?t.join(`
3
+ `):e.members?`(no active team members)`:`(team runtime unavailable)`}function le(e,t,n){let r=V(e);return{...r?{planPath:r.path}:{},tasks:H(t),...t.error?{taskError:t.error}:{},teamAvailable:!!n.members,teamMembers:n.members??[],...n.error?{teamError:n.error}:{}}}function ue(e){let t=e.planPath?`Source: ${e.planPath}\nExact plan content is restored separately by Doom Plan.`:`(no active plan document)`,n={...e.teamAvailable?{members:e.teamMembers}:{},...e.teamError?{error:e.teamError}:{}};return`<compaction-runtime-state>
4
4
  Authoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.
5
5
  <active-plan>
6
6
  ${t}
7
7
  </active-plan>
8
8
  <active-tasks>
9
- ${H(e.tasks,e.taskError)}
9
+ ${U(e.tasks,e.taskError)}
10
10
  </active-tasks>
11
11
  <active-team>
12
- ${U(n)}
12
+ ${W(n)}
13
13
  </active-team>
14
- </compaction-runtime-state>`}function W(e){return{"autocompact.runtime.plan_present":!!e.planPath,"autocompact.runtime.task_count":e.tasks.length,"autocompact.runtime.team_available":e.teamAvailable,"autocompact.runtime.team_member_count":e.teamMembers.length}}function G(e){let t=e.plan?`Source: ${e.plan.path}\n\n${e.plan.content}`:`(no active plan document)`,n=[e.readFiles.length>0?`Read files: ${e.readFiles.join(`, `)}`:void 0,e.modifiedFiles.length>0?`Modified files: ${e.modifiedFiles.join(`, `)}`:void 0].filter(e=>!!e);return`<compaction-steering priority="user,plan,tasks,team,important-context,recent-messages">
14
+ </compaction-runtime-state>`}function G(e){return{"autocompact.runtime.plan_present":!!e.planPath,"autocompact.runtime.task_count":e.tasks.length,"autocompact.runtime.team_available":e.teamAvailable,"autocompact.runtime.team_member_count":e.teamMembers.length}}function K(e){let t=e.plan?`Source: ${e.plan.path}\n\n${e.plan.content}`:`(no active plan document)`,n=[e.readFiles.length>0?`Read files: ${e.readFiles.join(`, `)}`:void 0,e.modifiedFiles.length>0?`Modified files: ${e.modifiedFiles.join(`, `)}`:void 0].filter(e=>!!e);return`<compaction-steering priority="user,plan,tasks,team,important-context,recent-messages">
15
15
  <user-prompt source="conversation">
16
16
  Treat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.
17
17
  </user-prompt>
@@ -19,10 +19,10 @@ Treat the user's explicit goals, constraints, corrections, and preferences in th
19
19
  ${t}
20
20
  </active-plan>
21
21
  <active-tasks>
22
- ${H(V(e.taskSnapshot),e.taskSnapshot.error)}
22
+ ${U(H(e.taskSnapshot),e.taskSnapshot.error)}
23
23
  </active-tasks>
24
24
  <active-team>
25
- ${U(e.teamSnapshot)}
25
+ ${W(e.teamSnapshot)}
26
26
  </active-team>
27
27
  <important-context>
28
28
  ${n.length>0?n.join(`
@@ -32,7 +32,7 @@ ${n.length>0?n.join(`
32
32
 
33
33
  `:``;return`Create Doom autocompact checkpoint pass ${e}.
34
34
 
35
- ${G(t)}
35
+ ${K(t)}
36
36
 
37
37
  Apply the steering evidence in priority order. Do not invent plan, task, or team state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.
38
38
 
@@ -46,5 +46,5 @@ ${n}Return only the decision tag when required, followed by a concise structured
46
46
  ### Blocked
47
47
  ## Key Decisions
48
48
  ## Next Steps
49
- ## Critical Context`}function fe(e,t,n){let r=_(N(t).messages,t).messages;if(e===1||!n)return r;let i=t.findIndex(e=>e.id===n);return i===-1?r:t.slice(i+1).filter(e=>e.type!==`custom_message`||e.customType!==`doom-autocompact-checkpoint`).flatMap(e=>P(e))}function K(e){let t=C(e),n=x(t);for(;;){let e=S(n,`checkpointWorker.mjs`);if(b(e))return w(e);let t=x(n);if(t===n)break;n=t}throw Error(`Cannot find checkpointWorker.mjs by walking from ${t}.`)}function q(e,t){return new Promise((n,r)=>{let i=new T(K(import.meta.url),{workerData:e}),a=!1,o=e=>{a||(a=!0,t.removeEventListener(`abort`,s),e())},s=()=>{o(()=>{i.terminate(),r(t.reason instanceof Error?t.reason:Error(`Autocompact summarization aborted.`))})};i.once(`message`,e=>{o(()=>{typeof e.checkpoint==`string`?n(e.checkpoint):r(Error(e.error??`Autocompact summarization worker returned no checkpoint.`))})}),i.once(`error`,e=>o(()=>r(e))),i.once(`exit`,e=>{e!==0&&o(()=>r(Error(`Autocompact summarization worker exited with code ${e}.`)))}),t.addEventListener(`abort`,s,{once:!0}),i.unref(),t.aborted&&s()})}function J(e){try{return D(E().root??e).modes?.planning?.subagents}catch{process.emitWarning(`Doom autocompact planning configuration could not be loaded; using the active session model instead.`);return}}function pe(e){let t=J(e.cwd),n=t?.model?v(t.model):void 0,r=n?e.modelRegistry.find(n.provider,n.modelId):void 0,i=r??e.model;if(!i)return;let a=t?.thinking??(r?n?.thinking:void 0)??e.thinkingLevel;return{model:i,...a?{thinkingLevel:a}:{}}}async function me(e,t){let n=t(e.context);if(!n)throw Error(`No active model is available for autocompact summarization.`);let r=await e.context.modelRegistry.getApiKeyAndHeaders(n.model);if(!r.ok)throw Error(r.error);return q({messages:e.messages,model:n.model,reserveTokens:M.reserveTokens,apiKey:r.apiKey,headers:r.headers,instructions:e.instructions,previousCheckpoint:e.previousCheckpoint,thinkingLevel:n.thinkingLevel,env:r.env},e.signal)}function Y(e,t,n=`info`){e?.hasUI&&e.ui.notify(t,n)}function X(g,v,b={}){let x=b.resolveModel??pe,S=b.generateCheckpoint??(e=>me(e,x)),C=b.readTaskSnapshot??se,w=b.readTeamSnapshot??ce,T=b.telemetry??re(),E=b.doomIntegrations??!0,D=new Set,O=new Set,k=new Set,A=!0,j=0,M=c(),P,z,V;g.effect(()=>async()=>{A=!1,j+=1,z?.abort(Error(`Autocompact runtime is shutting down.`)),z=void 0,await Promise.allSettled(k),V?.dispose(),V=void 0,P=void 0,D.clear(),O.clear(),M=c(),await T.shutdown()},`${F}/runtime`),V=E?ie(v,{source:F,id:`autocompact`,order:20}):{update:()=>void 0,dispose:()=>void 0};let H=e=>{if(!A)return;let t=M.phase===I.checkpointPending?`summarizing`:M.phase===I.checkpointReady?`applying`:void 0;V?.update(t?{fullText:`Compacting p${M.pass}`,compactText:`C${M.pass}`}:void 0);let n=e??P;n?.hasUI&&n.ui.setStatus(`doom-autocompact`,t?`Compacting pass ${M.pass} (${t})…`:void 0)},U=()=>{A&&(v.appendEntry(i,{...M}),H())},G=()=>{delete M.requestId,delete M.snapshotLeafId,delete M.snapshotTokens,delete M.pendingCheckpoint,delete M.compactionPass},K=e=>{M.checkpointQueue=M.checkpointQueue.filter(t=>t!==e)},q=e=>{A&&(M=oe(e.sessionManager.getBranch())??c(),!(M.phase===I.checkpointReady&&M.requestId&&M.snapshotLeafId&&M.pendingCheckpoint||M.phase===I.waiting)&&(z?.abort(),z=void 0,M.phase=I.waiting,G(),U()))},J=e=>{A&&v.sendMessage({customType:n,content:`${e} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,display:!1,details:{version:2,cycle:M.cycle,pass:M.pass}},{triggerTurn:!0,deliverAs:`steer`})},X=(e,t)=>{if(!A||e!==M.requestId||M.phase!==I.checkpointPending)return;let n=M.snapshotLeafId;M.phase=I.waiting,n&&(M.lastAttemptLeafId=n),G(),U(),Y(P,`Doom autocompact summarization pass ${M.pass} failed: ${t instanceof Error?t.message:String(t)}`,`error`)},Z=(e,t,n,r)=>{A&&(t.error&&(Y(e,`Doom autocompact task steering degraded: ${t.error}`,`warning`),T.recordWarning(y.taskSnapshotDegraded,Error(t.error),r)),n.error&&(Y(e,`Doom autocompact team steering degraded: ${n.error}`,`warning`),T.recordWarning(y.teamSnapshotDegraded,Error(n.error),r)))},Q=(e,t,n)=>{if(!A)return{tasks:[],teamAvailable:!1,teamMembers:[]};let i=C(e),a=w();Z(e,i,a,n);let o=le(t,i,a);return v.sendMessage({customType:r,content:ue(o),display:!1,details:{version:1,...o}}),o},he=(e,n)=>{if(!A||!M.requestId||!M.snapshotLeafId||!M.pendingCheckpoint)return!1;let r=n.sessionManager.getBranch(),i=_(N(r).messages,r).messages,a=m(M,d(i)),o=M.requestId,s=M.cycle,c=ne(M.pendingCheckpoint,a),l={...a,doomAutocompact:{version:2,cycle:s,pass:e,requestId:o,snapshotLeafId:M.snapshotLeafId,tokensBefore:M.snapshotTokens??n.getContextUsage()?.tokens??0},retainedMessages:ee(r,M.snapshotLeafId)};Y(n,`Doom autocompact pass ${e} context commit started.`);let u=n.isIdle();v.sendMessage({customType:t,content:c,display:!1,details:l});let f=R(n),p=Q(n,r,L(n,{"autocompact.request.id":o,"autocompact.cycle":s,"autocompact.pass":e}));return u&&v.setLabel(f,`autocompact:c${s}:p${e}`),M.readFiles=a.readFiles,M.modifiedFiles=a.modifiedFiles,delete M.latestCheckpointSnapshotLeafId,M.phase=I.waiting,M.checkpointQueue=[],M.exhaustedPasses=[],M.invalidAttempts=0,M.baselinePending=!0,delete M.lastAttemptLeafId,G(),M.cycle+=1,M.pass=1,U(),T.recordEvent(y.contextCommitted,L(n,{"autocompact.request.id":o,"autocompact.cycle":s,"autocompact.pass":e,"autocompact.snapshot_leaf_id":l.doomAutocompact.snapshotLeafId,"autocompact.tokens_before":l.doomAutocompact.tokensBefore,"autocompact.message_count.before":i.length,"autocompact.message_count.retained":l.retainedMessages.length,"autocompact.apply_mode":u?`idle`:`turn_end`,...W(p)})),Y(n,`Doom autocompact context committed. Baseline will be captured from the next settled context.`),u&&J(`Asynchronous compaction completed.`),!0},ge=(e,t,n)=>{if(!A)return;let r=j,i=t.sessionManager.getBranch(),a=R(t),o=l(t.sessionManager.getSessionId(),M.cycle,e,a),c=e>1?s(p(i)):void 0,u=fe(e,i,M.latestCheckpointSnapshotLeafId),d=C(t),f=w(),m=L(t,{"autocompact.request.id":o,"autocompact.cycle":M.cycle,"autocompact.pass":e,"autocompact.snapshot_leaf_id":a,"autocompact.tokens_before":n,"autocompact.message_count.before":u.length});Z(t,d,f,m),M.phase=I.checkpointPending,M.pass=e,M.requestId=o,M.snapshotLeafId=a,M.snapshotTokens=n,delete M.pendingCheckpoint,delete M.compactionPass,delete M.lastAttemptLeafId,U(),z?.abort(),z=new AbortController;let h=z.signal;Y(t,`Doom autocompact summarization pass ${e} started.`);let g=T.runInSpan(`doom_autocompact.checkpoint`,m,async()=>{await T.recordEvent(y.checkpointStarted,m);try{let n=await S({messages:u,instructions:de(e,{plan:B(i),taskSnapshot:d,teamSnapshot:f,readFiles:M.readFiles,modifiedFiles:M.modifiedFiles}),...c?{previousCheckpoint:c}:{},context:t,signal:h});if(!A||r!==j)throw h.reason??Error(`Autocompact checkpoint became stale.`);if(!n.trim())throw Error(`Summarization returned an empty checkpoint.`);return await T.recordEvent(y.checkpointCompleted,{...m,"autocompact.checkpoint.characters":n.length}),n}catch(e){throw A&&r===j&&await T.recordError(y.checkpointFailed,e,m),e}}).then(t=>{!A||r!==j||o!==M.requestId||M.phase!==I.checkpointPending||(M.phase=I.checkpointReady,M.pendingCheckpoint=t.trim(),U(),Y(P,`Doom autocompact summarization pass ${e} completed.`),P&&$(P))}).catch(e=>{A&&r===j&&X(o,e)});k.add(g),g.finally(()=>k.delete(g))},_e=e=>{if(!A||M.phase!==I.waiting||e.hasPendingMessages())return!1;let t=e.getContextUsage();if(!t||t.tokens===null)return!1;if(M.baselinePending)return a(e.sessionManager.getBranch())?(M.baselineTokens=t.tokens,M.baselinePending=!1,U(),Y(e,`Doom autocompact baseline captured at ${M.baselineTokens} tokens.`),!1):!1;let n=R(e);if(M.lastAttemptLeafId===n)return!1;for(let e of[1,2,3])e<M.pass||M.checkpointQueue.includes(e)||M.exhaustedPasses.includes(e)||t.tokens>=te(e,t.contextWindow,M.baselineTokens)&&M.checkpointQueue.push(e);let r=M.checkpointQueue[0];return r?(ge(r,e,t.tokens),!0):!1},ve=(t,n)=>{if(!A)return;let r=M.snapshotLeafId;v.appendEntry(e,{...o(M.cycle,t,M.requestId??`completed`),summary:n}),r&&(M.latestCheckpointSnapshotLeafId=r)},ye=e=>{if(!A||M.phase!==I.checkpointReady||!M.requestId||!M.pendingCheckpoint)return`none`;let t=M.pass,n=h(M.pendingCheckpoint);if(!f(n.summary)){let n=M.snapshotLeafId,r=M.requestId,i=M.invalidAttempts+1,a=i>=3;M.phase=I.waiting,n&&(M.lastAttemptLeafId=n),a?(K(t),M.exhaustedPasses=[...M.exhaustedPasses,t],M.invalidAttempts=0):M.invalidAttempts=i,G(),U();let o=Error(`Summarization pass ${t} returned an incomplete checkpoint.`);return Y(e,a?`Doom autocompact summarization pass ${t} returned an incomplete checkpoint ${i} times and was abandoned.`:`Doom autocompact summarization pass ${t} returned an incomplete checkpoint.`,`error`),T.recordError(y.checkpointInvalid,o,L(e,{"autocompact.cycle":M.cycle,"autocompact.pass":t,"autocompact.checkpoint.attempts":i,"autocompact.checkpoint.exhausted":a,...r?{"autocompact.request.id":r}:{}})),`invalid`}return M.invalidAttempts=0,t===1?(ve(1,n.summary),K(1),M.phase=I.waiting,M.pass=2,G(),U(),`pass1`):t===2&&n.shouldCompact!==!0?(ve(2,n.summary),K(2),M.phase=I.waiting,M.pass=3,G(),U(),`deferred`):(M.pendingCheckpoint=n.summary,he(t,e)?`committed`:`invalid`)};function $(e){A&&(P=e,e.isIdle()&&ye(e)!==`committed`&&_e(e))}v.on(`context`,(e,t)=>{if(!A)return;let n=_(e.messages,t.sessionManager.getBranch());if(n.invalidMarker){let e=t.sessionManager.getLeafId()??ae;O.has(e)||(O.add(e),T.recordError(y.contextMarkerInvalid,Error(`Doom autocompact context marker is malformed.`),L(t,{"autocompact.leaf_id":e})));return}if(n.marker)return D.has(n.marker.requestId)||(D.add(n.marker.requestId),T.recordEvent(y.contextApplied,L(t,{"autocompact.request.id":n.marker.requestId,"autocompact.cycle":n.marker.cycle,"autocompact.pass":n.marker.pass,"autocompact.snapshot_leaf_id":n.marker.snapshotLeafId,"autocompact.tokens_before":n.marker.tokensBefore,"autocompact.message_count.before":e.messages.length,"autocompact.message_count.after":n.messages.length,"autocompact.message_count.retained":n.retainedMessageCount}))),{messages:n.messages}});let be=e=>{A&&(j+=1,z?.abort(Error(`Autocompact session generation was replaced.`)),z=void 0,D.clear(),O.clear(),P=e,q(e),$(e))};v.on(`session_start`,(e,t)=>be(t)),v.on(`session_tree`,(e,t)=>be(t)),v.on(`turn_end`,(e,t)=>{if(A){if(P=t,t.isIdle()){$(t);return}M.phase===I.checkpointReady&&(e.toolResults?.length??0)>0&&!t.hasPendingMessages()&&ye(t)!==`none`||_e(t)}}),v.on(`agent_settled`,(e,t)=>{A&&$(t)}),v.on(`session_before_compact`,e=>{if(!(!A||e.reason!==`threshold`))return M.phase===I.checkpointPending||M.phase===I.checkpointReady||M.baselinePending?{cancel:!0}:void 0}),v.on(`session_compact`,(e,t)=>{if(!A)return;j+=1,z?.abort(),z=void 0;let n=u(e.compactionEntry.details),r=m(M,void 0,n);M.readFiles=r.readFiles,M.modifiedFiles=r.modifiedFiles,delete M.latestCheckpointSnapshotLeafId,M.baselinePending=!0,M.phase=I.waiting,G(),M.checkpointQueue=[],M.exhaustedPasses=[],M.invalidAttempts=0,delete M.lastAttemptLeafId,v.setLabel(e.compactionEntry.id,`autocompact:c${M.cycle}:external`);let i=M.cycle,a=L(t,{"autocompact.cycle":i,"autocompact.native.reason":e.reason}),o=Q(t,t.sessionManager.getBranch(),a);M.cycle+=1,M.pass=1,U(),T.recordEvent(y.nativeCompactionCompleted,L(t,{"autocompact.cycle":i,"autocompact.native.reason":e.reason,"autocompact.native.from_extension":e.fromExtension,"autocompact.tokens_before":e.compactionEntry.tokensBefore,...W(o)})),Y(t,`Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${M.pass}.`)})}async function Z(e){let t=new j,n,r=()=>(n??=t.fiber.dispose(),n);try{X(t,e)}catch(e){throw await r(),e}e.on(`session_shutdown`,r)}export{Z as default,X as installAutocompactRuntime};
49
+ ## Critical Context`}function fe(e,t,n){let r=_(N(t).messages,t).messages;if(e===1||!n)return r;let i=t.findIndex(e=>e.id===n);return i===-1?r:t.slice(i+1).filter(e=>e.type!==`custom_message`||e.customType!==`doom-autocompact-checkpoint`).flatMap(e=>P(e))}function q(e){let t=C(e),n=x(t);for(;;){let e=S(n,`checkpointWorker.mjs`);if(b(e))return w(e);let t=x(n);if(t===n)break;n=t}throw Error(`Cannot find checkpointWorker.mjs by walking from ${t}.`)}function pe(e,t){return new Promise((n,r)=>{let i=new T(q(import.meta.url),{workerData:e}),a=!1,o=e=>{a||(a=!0,t.removeEventListener(`abort`,s),e())},s=()=>{o(()=>{i.terminate(),r(t.reason instanceof Error?t.reason:Error(`Autocompact summarization aborted.`))})};i.once(`message`,e=>{o(()=>{typeof e.checkpoint==`string`?n(e.checkpoint):r(Error(e.error??`Autocompact summarization worker returned no checkpoint.`))})}),i.once(`error`,e=>o(()=>r(e))),i.once(`exit`,e=>{e!==0&&o(()=>r(Error(`Autocompact summarization worker exited with code ${e}.`)))}),t.addEventListener(`abort`,s,{once:!0}),i.unref(),t.aborted&&s()})}function me(e){try{return D(E().root??e).modes?.planning?.subagents}catch{process.emitWarning(`Doom autocompact planning configuration could not be loaded; using the active session model instead.`);return}}function he(e){let t=me(e.cwd),n=t?.model?v(t.model):void 0,r=n?e.modelRegistry.find(n.provider,n.modelId):void 0,i=r??e.model;if(!i)return;let a=t?.thinking??(r?n?.thinking:void 0)??e.thinkingLevel;return{model:i,...a?{thinkingLevel:a}:{}}}async function ge(e,t){let n=t(e.context);if(!n)throw Error(`No active model is available for autocompact summarization.`);let r=await e.context.modelRegistry.getApiKeyAndHeaders(n.model);if(!r.ok)throw Error(r.error);return pe({messages:e.messages,model:n.model,reserveTokens:M.reserveTokens,apiKey:r.apiKey,headers:r.headers,instructions:e.instructions,previousCheckpoint:e.previousCheckpoint,thinkingLevel:n.thinkingLevel,env:r.env},e.signal)}function J(e,t,n=`info`){e?.hasUI&&e.ui.notify(t,n)}function Y(g,v,b={}){let x=b.resolveModel??he,S=b.generateCheckpoint??(e=>ge(e,x)),C=b.readTaskSnapshot??se,w=b.readTeamSnapshot??ce,T=b.telemetry??re(),E=b.doomIntegrations??!0,D=new Set,O=new Set,k=new Set,A=!0,j=0,M=c(),P,B,H;g.effect(()=>async()=>{A=!1,j+=1,B?.abort(Error(`Autocompact runtime is shutting down.`)),B=void 0,await Promise.allSettled(k),H=void 0,P=void 0,D.clear(),O.clear(),M=c(),await T.shutdown()},`${I}/runtime`),E&&g.inject([ie],e=>{let t=ae(e).registerFooter({source:I,id:`autocompact`,order:20});return H=t,()=>{t.dispose(),H===t&&(H=void 0)}});let U=e=>{if(!A)return;let t=M.phase===L.checkpointPending?`summarizing`:M.phase===L.checkpointReady?`applying`:void 0;H?.update(t?{fullText:`Compacting p${M.pass}`,compactText:`C${M.pass}`}:void 0);let n=e??P;n?.hasUI&&n.ui.setStatus(`doom-autocompact`,t?`Compacting pass ${M.pass} (${t})…`:void 0)},W=()=>{A&&(v.appendEntry(i,{...M}),U())},K=()=>{delete M.requestId,delete M.snapshotLeafId,delete M.snapshotTokens,delete M.pendingCheckpoint,delete M.compactionPass},q=e=>{M.checkpointQueue=M.checkpointQueue.filter(t=>t!==e)},pe=e=>{A&&(M=oe(e.sessionManager.getBranch())??c(),!(M.phase===L.checkpointReady&&M.requestId&&M.snapshotLeafId&&M.pendingCheckpoint||M.phase===L.waiting)&&(B?.abort(),B=void 0,M.phase=L.waiting,K(),W()))},me=e=>{A&&v.sendMessage({customType:n,content:`${e} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,display:!1,details:{version:2,cycle:M.cycle,pass:M.pass}},{triggerTurn:!0,deliverAs:`steer`})},Y=(e,t)=>{if(!A||e!==M.requestId||M.phase!==L.checkpointPending)return;let n=M.snapshotLeafId;M.phase=L.waiting,n&&(M.lastAttemptLeafId=n),K(),W(),J(P,`Doom autocompact summarization pass ${M.pass} failed: ${t instanceof Error?t.message:String(t)}`,`error`)},X=(e,t,n,r)=>{A&&(t.error&&(J(e,`Doom autocompact task steering degraded: ${t.error}`,`warning`),T.recordWarning(y.taskSnapshotDegraded,Error(t.error),r)),n.error&&(J(e,`Doom autocompact team steering degraded: ${n.error}`,`warning`),T.recordWarning(y.teamSnapshotDegraded,Error(n.error),r)))},Z=(e,t,n)=>{if(!A)return{tasks:[],teamAvailable:!1,teamMembers:[]};let i=C(e),a=w();X(e,i,a,n);let o=le(t,i,a);return v.sendMessage({customType:r,content:ue(o),display:!1,details:{version:1,...o}}),o},_e=(e,n)=>{if(!A||!M.requestId||!M.snapshotLeafId||!M.pendingCheckpoint)return!1;let r=n.sessionManager.getBranch(),i=_(N(r).messages,r).messages,a=m(M,d(i)),o=M.requestId,s=M.cycle,c=ne(M.pendingCheckpoint,a),l={...a,doomAutocompact:{version:2,cycle:s,pass:e,requestId:o,snapshotLeafId:M.snapshotLeafId,tokensBefore:M.snapshotTokens??n.getContextUsage()?.tokens??0},retainedMessages:ee(r,M.snapshotLeafId)};J(n,`Doom autocompact pass ${e} context commit started.`);let u=n.isIdle();v.sendMessage({customType:t,content:c,display:!1,details:l});let f=z(n),p=Z(n,r,R(n,{"autocompact.request.id":o,"autocompact.cycle":s,"autocompact.pass":e}));return u&&v.setLabel(f,`autocompact:c${s}:p${e}`),M.readFiles=a.readFiles,M.modifiedFiles=a.modifiedFiles,delete M.latestCheckpointSnapshotLeafId,M.phase=L.waiting,M.checkpointQueue=[],M.exhaustedPasses=[],M.invalidAttempts=0,M.baselinePending=!0,delete M.lastAttemptLeafId,K(),M.cycle+=1,M.pass=1,W(),T.recordEvent(y.contextCommitted,R(n,{"autocompact.request.id":o,"autocompact.cycle":s,"autocompact.pass":e,"autocompact.snapshot_leaf_id":l.doomAutocompact.snapshotLeafId,"autocompact.tokens_before":l.doomAutocompact.tokensBefore,"autocompact.message_count.before":i.length,"autocompact.message_count.retained":l.retainedMessages.length,"autocompact.apply_mode":u?`idle`:`turn_end`,...G(p)})),J(n,`Doom autocompact context committed. Baseline will be captured from the next settled context.`),u&&me(`Asynchronous compaction completed.`),!0},ve=(e,t,n)=>{if(!A)return;let r=j,i=t.sessionManager.getBranch(),a=z(t),o=l(t.sessionManager.getSessionId(),M.cycle,e,a),c=e>1?s(p(i)):void 0,u=fe(e,i,M.latestCheckpointSnapshotLeafId),d=C(t),f=w(),m=R(t,{"autocompact.request.id":o,"autocompact.cycle":M.cycle,"autocompact.pass":e,"autocompact.snapshot_leaf_id":a,"autocompact.tokens_before":n,"autocompact.message_count.before":u.length});X(t,d,f,m),M.phase=L.checkpointPending,M.pass=e,M.requestId=o,M.snapshotLeafId=a,M.snapshotTokens=n,delete M.pendingCheckpoint,delete M.compactionPass,delete M.lastAttemptLeafId,W(),B?.abort(),B=new AbortController;let h=B.signal;J(t,`Doom autocompact summarization pass ${e} started.`);let g=T.runInSpan(`doom_autocompact.checkpoint`,m,async()=>{await T.recordEvent(y.checkpointStarted,m);try{let n=await S({messages:u,instructions:de(e,{plan:V(i),taskSnapshot:d,teamSnapshot:f,readFiles:M.readFiles,modifiedFiles:M.modifiedFiles}),...c?{previousCheckpoint:c}:{},context:t,signal:h});if(!A||r!==j)throw h.reason??Error(`Autocompact checkpoint became stale.`);if(!n.trim())throw Error(`Summarization returned an empty checkpoint.`);return await T.recordEvent(y.checkpointCompleted,{...m,"autocompact.checkpoint.characters":n.length}),n}catch(e){throw A&&r===j&&await T.recordError(y.checkpointFailed,e,m),e}}).then(t=>{!A||r!==j||o!==M.requestId||M.phase!==L.checkpointPending||(M.phase=L.checkpointReady,M.pendingCheckpoint=t.trim(),W(),J(P,`Doom autocompact summarization pass ${e} completed.`),P&&Q(P))}).catch(e=>{A&&r===j&&Y(o,e)});k.add(g),g.finally(()=>k.delete(g))},ye=e=>{if(!A||M.phase!==L.waiting||e.hasPendingMessages())return!1;let t=e.getContextUsage();if(!t||t.tokens===null)return!1;if(M.baselinePending)return a(e.sessionManager.getBranch())?(M.baselineTokens=t.tokens,M.baselinePending=!1,W(),J(e,`Doom autocompact baseline captured at ${M.baselineTokens} tokens.`),!1):!1;let n=z(e);if(M.lastAttemptLeafId===n)return!1;for(let e of[1,2,3])e<M.pass||M.checkpointQueue.includes(e)||M.exhaustedPasses.includes(e)||t.tokens>=te(e,t.contextWindow,M.baselineTokens)&&M.checkpointQueue.push(e);let r=M.checkpointQueue[0];return r?(ve(r,e,t.tokens),!0):!1},be=(t,n)=>{if(!A)return;let r=M.snapshotLeafId;v.appendEntry(e,{...o(M.cycle,t,M.requestId??`completed`),summary:n}),r&&(M.latestCheckpointSnapshotLeafId=r)},xe=e=>{if(!A||M.phase!==L.checkpointReady||!M.requestId||!M.pendingCheckpoint)return`none`;let t=M.pass,n=h(M.pendingCheckpoint);if(!f(n.summary)){let n=M.snapshotLeafId,r=M.requestId,i=M.invalidAttempts+1,a=i>=3;M.phase=L.waiting,n&&(M.lastAttemptLeafId=n),a?(q(t),M.exhaustedPasses=[...M.exhaustedPasses,t],M.invalidAttempts=0):M.invalidAttempts=i,K(),W();let o=Error(`Summarization pass ${t} returned an incomplete checkpoint.`);return J(e,a?`Doom autocompact summarization pass ${t} returned an incomplete checkpoint ${i} times and was abandoned.`:`Doom autocompact summarization pass ${t} returned an incomplete checkpoint.`,`error`),T.recordError(y.checkpointInvalid,o,R(e,{"autocompact.cycle":M.cycle,"autocompact.pass":t,"autocompact.checkpoint.attempts":i,"autocompact.checkpoint.exhausted":a,...r?{"autocompact.request.id":r}:{}})),`invalid`}return M.invalidAttempts=0,t===1?(be(1,n.summary),q(1),M.phase=L.waiting,M.pass=2,K(),W(),`pass1`):t===2&&n.shouldCompact!==!0?(be(2,n.summary),q(2),M.phase=L.waiting,M.pass=3,K(),W(),`deferred`):(M.pendingCheckpoint=n.summary,_e(t,e)?`committed`:`invalid`)};function Q(e){A&&(P=e,e.isIdle()&&xe(e)!==`committed`&&ye(e))}v.on(`context`,(e,t)=>{if(!A)return;let n=_(e.messages,t.sessionManager.getBranch());if(n.invalidMarker){let e=t.sessionManager.getLeafId()??F;O.has(e)||(O.add(e),T.recordError(y.contextMarkerInvalid,Error(`Doom autocompact context marker is malformed.`),R(t,{"autocompact.leaf_id":e})));return}if(n.marker)return D.has(n.marker.requestId)||(D.add(n.marker.requestId),T.recordEvent(y.contextApplied,R(t,{"autocompact.request.id":n.marker.requestId,"autocompact.cycle":n.marker.cycle,"autocompact.pass":n.marker.pass,"autocompact.snapshot_leaf_id":n.marker.snapshotLeafId,"autocompact.tokens_before":n.marker.tokensBefore,"autocompact.message_count.before":e.messages.length,"autocompact.message_count.after":n.messages.length,"autocompact.message_count.retained":n.retainedMessageCount}))),{messages:n.messages}});let $=e=>{A&&(j+=1,B?.abort(Error(`Autocompact session generation was replaced.`)),B=void 0,D.clear(),O.clear(),P=e,pe(e),Q(e))};v.on(`session_start`,(e,t)=>$(t)),v.on(`session_tree`,(e,t)=>$(t)),v.on(`turn_end`,(e,t)=>{if(A){if(P=t,t.isIdle()){Q(t);return}M.phase===L.checkpointReady&&(e.toolResults?.length??0)>0&&!t.hasPendingMessages()&&xe(t)!==`none`||ye(t)}}),v.on(`agent_settled`,(e,t)=>{A&&Q(t)}),v.on(`session_before_compact`,e=>{if(!(!A||e.reason!==`threshold`))return M.phase===L.checkpointPending||M.phase===L.checkpointReady||M.baselinePending?{cancel:!0}:void 0}),v.on(`session_compact`,(e,t)=>{if(!A)return;j+=1,B?.abort(),B=void 0;let n=u(e.compactionEntry.details),r=m(M,void 0,n);M.readFiles=r.readFiles,M.modifiedFiles=r.modifiedFiles,delete M.latestCheckpointSnapshotLeafId,M.baselinePending=!0,M.phase=L.waiting,K(),M.checkpointQueue=[],M.exhaustedPasses=[],M.invalidAttempts=0,delete M.lastAttemptLeafId,v.setLabel(e.compactionEntry.id,`autocompact:c${M.cycle}:external`);let i=M.cycle,a=R(t,{"autocompact.cycle":i,"autocompact.native.reason":e.reason}),o=Z(t,t.sessionManager.getBranch(),a);M.cycle+=1,M.pass=1,W(),T.recordEvent(y.nativeCompactionCompleted,R(t,{"autocompact.cycle":i,"autocompact.native.reason":e.reason,"autocompact.native.from_extension":e.fromExtension,"autocompact.tokens_before":e.compactionEntry.tokensBefore,...G(o)})),J(t,`Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${M.pass}.`)})}async function X(e){let t=await O(e,`@agimon-ai/doompi-autocompact`),n=t.root.plugin(Z,{pi:e});try{await n}catch(e){try{await n.dispose()}finally{await t.dispose()}throw e}let r;e.on(`session_shutdown`,()=>r??=(async()=>{try{await n.dispose()}finally{await t.dispose()}})())}function Z(e,t){Y(e,t.pi)}export{X as default,Y as installAutocompactRuntime};
50
50
  //# sourceMappingURL=extension.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"extension.mjs","names":[],"sources":["../../../../src/adapters/pi/extension.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { Worker } from 'node:worker_threads';\n\nimport { getHarnessState, loadDoomConfig, type PlanningAgentConfig } from '@agimon-ai/doompi-config';\nimport { resolveSessionKey } from '@agimon-ai/doompi-task/store/paths';\nimport { TaskStore } from '@agimon-ai/doompi-task/store/taskStore';\nimport type { Task } from '@agimon-ai/doompi-task/store/types';\nimport { readActiveTeamSnapshot, type TeamMemberSnapshot } from '@agimon-ai/doompi-team/api/team-snapshot';\nimport { registerDoomFooterContribution } from '@agimon-ai/doompi-ui/footer';\nimport { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent';\nimport {\n buildSessionContext,\n DEFAULT_COMPACTION_SETTINGS,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n createInitialState,\n createRequestId,\n fileDetailsFromUnknown,\n fileOperationsFromMessages,\n isStructuredCheckpoint,\n latestCheckpointArtifactEntry,\n mergeFileDetails,\n parseCheckpointDecision,\n parseState,\n projectContextMessages,\n retainedMessagesAfterSnapshot,\n thresholdTokens,\n withCanonicalFileSections,\n} from '../../adapters/compaction/policy';\nimport { parseModelReference, type SummarizationModel } from '../../services/summarizationModel.ts';\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type { AutocompactEventAttributes, AutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\n\nexport type { ModelReference, SummarizationModel } from '../../services/summarizationModel.ts';\nexport { parseModelReference, resolveSummarizationModel } from '../../services/summarizationModel.ts';\n\nimport type { AutocompactContextDetails, AutocompactPass, AutocompactState } from '../../types/index.ts';\n\nconst ROOT_WORKING_LEAF = '@root';\nconst PLAN_DOCUMENT_ENTRY = 'agent-harness-plan-document';\nconst FOOTER_SOURCE = 'doom-autocompact';\nconst FOOTER_ORDER = 20;\nconst STATUS_KEY = 'doom-autocompact';\nconst STATE_PHASE = {\n waiting: 'waiting',\n checkpointPending: 'checkpoint_pending',\n checkpointReady: 'checkpoint_ready',\n compacting: 'compacting',\n} as const;\ntype CheckpointCapture = 'none' | 'pass1' | 'committed' | 'deferred' | 'invalid';\ntype CheckpointMessages = ReturnType<typeof buildSessionContext>['messages'];\n\ninterface PlanSnapshot {\n content: string;\n path: string;\n}\n\ninterface TaskSnapshot {\n tasks: Task[];\n error?: string;\n}\n\ninterface TeamSnapshot {\n members?: TeamMemberSnapshot[];\n error?: string;\n}\n\ninterface SteeringSnapshot {\n plan?: PlanSnapshot;\n taskSnapshot: TaskSnapshot;\n teamSnapshot: TeamSnapshot;\n readFiles: string[];\n modifiedFiles: string[];\n}\n\ninterface RuntimeTaskSnapshot {\n id: number;\n status: Task['status'];\n subject: string;\n activeForm?: string;\n owner?: string;\n blockedBy?: number[];\n delegation?: {\n agent: string;\n state: NonNullable<Task['delegation']>['state'];\n error?: string;\n };\n}\n\ninterface RuntimeStateSnapshot {\n planPath?: string;\n tasks: RuntimeTaskSnapshot[];\n taskError?: string;\n teamAvailable: boolean;\n teamMembers: TeamMemberSnapshot[];\n teamError?: string;\n}\n\ninterface CheckpointGenerationInput {\n messages: CheckpointMessages;\n instructions: string;\n previousCheckpoint?: string;\n context: ExtensionContext;\n signal: AbortSignal;\n}\n\ninterface CheckpointWorkerResult {\n checkpoint?: string;\n error?: string;\n}\n\nexport interface AutocompactDependencies {\n generateCheckpoint?: (input: CheckpointGenerationInput) => Promise<string>;\n readTaskSnapshot?: (context: ExtensionContext) => TaskSnapshot;\n readTeamSnapshot?: () => TeamSnapshot;\n resolveModel?: (context: ExtensionContext) => SummarizationModel | undefined;\n telemetry?: AutocompactTelemetry;\n doomIntegrations?: boolean;\n}\n\nfunction telemetryAttributes(\n context: ExtensionContext,\n attributes: AutocompactEventAttributes = {},\n): AutocompactEventAttributes {\n return {\n 'pi.session.id': context.sessionManager.getSessionId(),\n ...attributes,\n };\n}\n\nfunction latestPersistedState(branch: SessionEntry[]): AutocompactState | undefined {\n for (let index = branch.length - 1; index >= 0; index -= 1) {\n const entry = branch[index];\n if (entry?.type !== 'custom' || entry.customType !== STATE_CUSTOM_TYPE) continue;\n const parsed = parseState(entry.data);\n if (parsed) return parsed;\n }\n return undefined;\n}\n\nfunction workingLeafId(ctx: ExtensionContext): string {\n for (const entry of ctx.sessionManager.getBranch().toReversed()) {\n if (entry.type === 'custom' && entry.customType === STATE_CUSTOM_TYPE) continue;\n if (entry.type === 'label') continue;\n return entry.id;\n }\n return ROOT_WORKING_LEAF;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction latestPlanSnapshot(branch: SessionEntry[]): PlanSnapshot | undefined {\n for (const entry of branch.toReversed()) {\n if (entry.type !== 'custom' || entry.customType !== PLAN_DOCUMENT_ENTRY) continue;\n if (!entry.data || typeof entry.data !== 'object') return undefined;\n const data = entry.data as Record<string, unknown>;\n if (typeof data.content !== 'string' || typeof data.path !== 'string') return undefined;\n return { content: data.content, path: data.path };\n }\n return undefined;\n}\n\nfunction readTaskSnapshotWithDoomTask(context: ExtensionContext): TaskSnapshot {\n const failures: string[] = [];\n try {\n const store = new TaskStore({\n cwd: context.cwd,\n report: {\n error: (event, error) => failures.push(`${event}: ${errorMessage(error)}`),\n warn: (event, error) => failures.push(`${event}: ${errorMessage(error)}`),\n event: () => undefined,\n },\n });\n store.configureSession(resolveSessionKey(context.sessionManager.getSessionId()));\n const tasks = store.read().tasks;\n return { tasks, ...(failures.length > 0 ? { error: failures.join('; ') } : {}) };\n } catch (error) {\n return { tasks: [], error: errorMessage(error) };\n }\n}\n\nfunction readTeamSnapshotWithDoomTeam(): TeamSnapshot {\n try {\n const snapshot = readActiveTeamSnapshot();\n return snapshot ? { members: snapshot.members } : {};\n } catch (error) {\n return { error: errorMessage(error) };\n }\n}\n\nfunction activeTaskSnapshots(snapshot: TaskSnapshot): RuntimeTaskSnapshot[] {\n return snapshot.tasks\n .filter((task) => task.status === 'pending' || task.status === 'in_progress' || task.status === 'failed')\n .map((task) => ({\n id: task.id,\n status: task.status,\n subject: task.subject,\n ...(task.activeForm ? { activeForm: task.activeForm } : {}),\n ...(task.owner ? { owner: task.owner } : {}),\n ...(task.blockedBy?.length ? { blockedBy: task.blockedBy } : {}),\n ...(task.delegation\n ? {\n delegation: {\n agent: task.delegation.agent,\n state: task.delegation.state,\n ...(task.delegation.result?.error ? { error: task.delegation.result.error } : {}),\n },\n }\n : {}),\n }));\n}\n\nfunction formatRuntimeTasks(tasks: RuntimeTaskSnapshot[], error?: string): string {\n const lines = tasks.map((task) => {\n const details = [\n task.activeForm ? `active: ${task.activeForm}` : undefined,\n task.owner ? `owner: ${task.owner}` : undefined,\n task.blockedBy?.length ? `blocked by: ${task.blockedBy.join(', ')}` : undefined,\n task.delegation ? `delegation: ${task.delegation.agent} (${task.delegation.state})` : undefined,\n task.delegation?.error ? `error: ${task.delegation.error}` : undefined,\n ].filter((value): value is string => Boolean(value));\n return `- #${task.id} [${task.status}] ${task.subject}${details.length > 0 ? ` | ${details.join(' | ')}` : ''}`;\n });\n if (error) lines.push(`- Task snapshot error: ${error}`);\n return lines.length > 0 ? lines.join('\\n') : '(no active tasks)';\n}\n\nfunction formatTeamSnapshot(snapshot: TeamSnapshot): string {\n const lines = (snapshot.members ?? []).map((member) => {\n const details = [\n `role: ${member.role}`,\n member.agent ? `agent: ${member.agent}` : undefined,\n member.runId ? `run: ${member.runId}` : undefined,\n member.task ? `task ${member.task.id}: ${member.task.subject}` : undefined,\n ].filter((value): value is string => Boolean(value));\n return `- ${member.name} | ${details.join(' | ')}`;\n });\n if (snapshot.error) lines.push(`- Team snapshot error: ${snapshot.error}`);\n if (lines.length > 0) return lines.join('\\n');\n return snapshot.members ? '(no active team members)' : '(team runtime unavailable)';\n}\n\nfunction runtimeStateSnapshot(\n branch: SessionEntry[],\n taskSnapshot: TaskSnapshot,\n teamSnapshot: TeamSnapshot,\n): RuntimeStateSnapshot {\n const plan = latestPlanSnapshot(branch);\n return {\n ...(plan ? { planPath: plan.path } : {}),\n tasks: activeTaskSnapshots(taskSnapshot),\n ...(taskSnapshot.error ? { taskError: taskSnapshot.error } : {}),\n teamAvailable: Boolean(teamSnapshot.members),\n teamMembers: teamSnapshot.members ?? [],\n ...(teamSnapshot.error ? { teamError: teamSnapshot.error } : {}),\n };\n}\n\nfunction formatRuntimeState(snapshot: RuntimeStateSnapshot): string {\n const plan = snapshot.planPath\n ? `Source: ${snapshot.planPath}\\nExact plan content is restored separately by Doom Plan.`\n : '(no active plan document)';\n const teamSnapshot: TeamSnapshot = {\n ...(snapshot.teamAvailable ? { members: snapshot.teamMembers } : {}),\n ...(snapshot.teamError ? { error: snapshot.teamError } : {}),\n };\n return `<compaction-runtime-state>\nAuthoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.\n<active-plan>\n${plan}\n</active-plan>\n<active-tasks>\n${formatRuntimeTasks(snapshot.tasks, snapshot.taskError)}\n</active-tasks>\n<active-team>\n${formatTeamSnapshot(teamSnapshot)}\n</active-team>\n</compaction-runtime-state>`;\n}\n\nfunction runtimeTelemetryAttributes(snapshot: RuntimeStateSnapshot): AutocompactEventAttributes {\n return {\n 'autocompact.runtime.plan_present': Boolean(snapshot.planPath),\n 'autocompact.runtime.task_count': snapshot.tasks.length,\n 'autocompact.runtime.team_available': snapshot.teamAvailable,\n 'autocompact.runtime.team_member_count': snapshot.teamMembers.length,\n };\n}\n\nfunction steeringEnvelope(snapshot: SteeringSnapshot): string {\n const plan = snapshot.plan\n ? `Source: ${snapshot.plan.path}\\n\\n${snapshot.plan.content}`\n : '(no active plan document)';\n const importantContext = [\n snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(', ')}` : undefined,\n snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(', ')}` : undefined,\n ].filter((value): value is string => Boolean(value));\n\n return `<compaction-steering priority=\"user,plan,tasks,team,important-context,recent-messages\">\n<user-prompt source=\"conversation\">\nTreat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.\n</user-prompt>\n<active-plan>\n${plan}\n</active-plan>\n<active-tasks>\n${formatRuntimeTasks(activeTaskSnapshots(snapshot.taskSnapshot), snapshot.taskSnapshot.error)}\n</active-tasks>\n<active-team>\n${formatTeamSnapshot(snapshot.teamSnapshot)}\n</active-team>\n<important-context>\n${importantContext.length > 0 ? importantContext.join('\\n') : '(none recorded outside the conversation)'}\n</important-context>\n</compaction-steering>`;\n}\n\nfunction checkpointInstructions(pass: AutocompactPass, steering: SteeringSnapshot): string {\n const decision =\n pass === 2\n ? 'Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\\n\\n'\n : '';\n\n // Summarization is a tool-less single LLM call, so instructions describe only what to\n // produce. Directives aimed at an implementing agent leak into the checkpoint body.\n return `Create Doom autocompact checkpoint pass ${pass}.\n\n${steeringEnvelope(steering)}\n\nApply the steering evidence in priority order. Do not invent plan, task, or team state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.\n\n${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.\n\n## Goal\n## Constraints & Preferences\n## Progress\n### Done\n### In Progress\n### Blocked\n## Key Decisions\n## Next Steps\n## Critical Context`;\n}\n\nfunction messagesForCheckpoint(\n pass: AutocompactPass,\n branch: SessionEntry[],\n previousSnapshotLeafId: string | undefined,\n): CheckpointMessages {\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n if (pass === 1 || !previousSnapshotLeafId) return projected;\n const snapshotIndex = branch.findIndex((entry) => entry.id === previousSnapshotLeafId);\n if (snapshotIndex === -1) return projected;\n return branch\n .slice(snapshotIndex + 1)\n .filter((entry) => entry.type !== 'custom_message' || entry.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap((entry) => sessionEntryToContextMessages(entry));\n}\n\nexport function findCheckpointWorkerUrl(importFileUrl: string | URL): URL {\n const importFilePath = fileURLToPath(importFileUrl);\n let directory = dirname(importFilePath);\n\n while (true) {\n const workerPath = join(directory, 'checkpointWorker.mjs');\n if (existsSync(workerPath)) return pathToFileURL(workerPath);\n\n const parent = dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n\n throw new Error(`Cannot find checkpointWorker.mjs by walking from ${importFilePath}.`);\n}\n\nfunction runCheckpointWorker(workerInput: Record<string, unknown>, signal: AbortSignal): Promise<string> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(findCheckpointWorkerUrl(import.meta.url), { workerData: workerInput });\n let settled = false;\n\n const settle = (complete: () => void): void => {\n if (settled) return;\n settled = true;\n signal.removeEventListener('abort', abort);\n complete();\n };\n const abort = (): void => {\n settle(() => {\n void worker.terminate();\n reject(signal.reason instanceof Error ? signal.reason : new Error('Autocompact summarization aborted.'));\n });\n };\n\n worker.once('message', (result: CheckpointWorkerResult) => {\n settle(() => {\n if (typeof result.checkpoint === 'string') resolve(result.checkpoint);\n else reject(new Error(result.error ?? 'Autocompact summarization worker returned no checkpoint.'));\n });\n });\n worker.once('error', (error) => settle(() => reject(error)));\n worker.once('exit', (code) => {\n if (code !== 0) settle(() => reject(new Error(`Autocompact summarization worker exited with code ${code}.`)));\n });\n signal.addEventListener('abort', abort, { once: true });\n worker.unref();\n if (signal.aborted) abort();\n });\n}\n\nfunction subagentModelConfig(cwd: string): PlanningAgentConfig | undefined {\n try {\n return loadDoomConfig(getHarnessState().root ?? cwd).modes?.planning?.subagents;\n } catch {\n process.emitWarning(\n 'Doom autocompact planning configuration could not be loaded; using the active session model instead.',\n );\n return undefined;\n }\n}\n\n/** Explicit Doom model selection honors the configured planning subagent model. */\nexport function resolveDoomSummarizationModel(ctx: ExtensionContext): SummarizationModel | undefined {\n const configured = subagentModelConfig(ctx.cwd);\n const reference = configured?.model ? parseModelReference(configured.model) : undefined;\n const configuredModel = reference ? ctx.modelRegistry.find(reference.provider, reference.modelId) : undefined;\n const model = configuredModel ?? ctx.model;\n if (!model) return undefined;\n const thinkingLevel =\n configured?.thinking ?? (configuredModel ? reference?.thinking : undefined) ?? ctx.thinkingLevel;\n return { model, ...(thinkingLevel ? { thinkingLevel } : {}) };\n}\n\nasync function generateCheckpointWithPi(\n input: CheckpointGenerationInput,\n resolveModel: (context: ExtensionContext) => SummarizationModel | undefined,\n): Promise<string> {\n const selection = resolveModel(input.context);\n if (!selection) throw new Error('No active model is available for autocompact summarization.');\n const auth = await input.context.modelRegistry.getApiKeyAndHeaders(selection.model);\n if (!auth.ok) throw new Error(auth.error);\n return runCheckpointWorker(\n {\n messages: input.messages,\n model: selection.model,\n reserveTokens: DEFAULT_COMPACTION_SETTINGS.reserveTokens,\n apiKey: auth.apiKey,\n headers: auth.headers,\n instructions: input.instructions,\n previousCheckpoint: input.previousCheckpoint,\n thinkingLevel: selection.thinkingLevel,\n env: auth.env,\n },\n input.signal,\n );\n}\n\nfunction notify(ctx: ExtensionContext | undefined, message: string, level: 'info' | 'warning' | 'error' = 'info') {\n if (ctx?.hasUI) ctx.ui.notify(message, level);\n}\n\nexport function installAutocompactRuntime(\n cordis: Context,\n pi: ExtensionAPI,\n dependencies: AutocompactDependencies = {},\n): void {\n const resolveModel = dependencies.resolveModel ?? resolveDoomSummarizationModel;\n const generateCheckpoint =\n dependencies.generateCheckpoint ??\n ((input: CheckpointGenerationInput) => generateCheckpointWithPi(input, resolveModel));\n const readTaskSnapshot = dependencies.readTaskSnapshot ?? readTaskSnapshotWithDoomTask;\n const readTeamSnapshot = dependencies.readTeamSnapshot ?? readTeamSnapshotWithDoomTeam;\n const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();\n const doomIntegrations = dependencies.doomIntegrations ?? true;\n const appliedContextRequests = new Set<string>();\n const invalidContextLeaves = new Set<string>();\n const checkpointWork = new Set<Promise<void>>();\n let active = true;\n let sessionGeneration = 0;\n let state = createInitialState();\n let currentContext: ExtensionContext | undefined;\n let checkpointController: AbortController | undefined;\n let footerContribution: ReturnType<typeof registerDoomFooterContribution> | undefined;\n\n cordis.effect(\n () => async () => {\n active = false;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact runtime is shutting down.'));\n checkpointController = undefined;\n await Promise.allSettled(checkpointWork);\n footerContribution?.dispose();\n footerContribution = undefined;\n currentContext = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n state = createInitialState();\n await telemetry.shutdown();\n },\n `${FOOTER_SOURCE}/runtime`,\n );\n\n footerContribution = doomIntegrations\n ? registerDoomFooterContribution(pi, {\n source: FOOTER_SOURCE,\n id: 'autocompact',\n order: FOOTER_ORDER,\n })\n : { update: () => undefined, dispose: () => undefined };\n\n /** Compaction runs off the main thread, so the phase is the only signal the user gets. */\n const refreshStatus = (ctx?: ExtensionContext): void => {\n if (!active) return;\n const phase =\n state.phase === STATE_PHASE.checkpointPending\n ? 'summarizing'\n : state.phase === STATE_PHASE.checkpointReady\n ? 'applying'\n : undefined;\n footerContribution?.update(\n phase ? { fullText: `Compacting p${state.pass}`, compactText: `C${state.pass}` } : undefined,\n );\n const target = ctx ?? currentContext;\n if (target?.hasUI) target.ui.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : undefined);\n };\n\n // Every phase transition persists, so this is the one place that keeps the status honest.\n const persist = (): void => {\n if (!active) return;\n pi.appendEntry(STATE_CUSTOM_TYPE, { ...state });\n refreshStatus();\n };\n\n const clearPendingCheckpoint = (): void => {\n delete state.requestId;\n delete state.snapshotLeafId;\n delete state.snapshotTokens;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n };\n\n const completeQueuedPass = (pass: AutocompactPass): void => {\n state.checkpointQueue = state.checkpointQueue.filter((queuedPass) => queuedPass !== pass);\n };\n\n const restore = (ctx: ExtensionContext): void => {\n if (!active) return;\n state = latestPersistedState(ctx.sessionManager.getBranch()) ?? createInitialState();\n const resumablePending =\n state.phase === STATE_PHASE.checkpointReady && state.requestId && state.snapshotLeafId && state.pendingCheckpoint;\n if (resumablePending || state.phase === STATE_PHASE.waiting) return;\n\n checkpointController?.abort();\n checkpointController = undefined;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n persist();\n };\n\n const resumeAgent = (message: string): void => {\n if (!active) return;\n pi.sendMessage(\n {\n customType: RESUME_MESSAGE_TYPE,\n content: `${message} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,\n display: false,\n details: { version: STATE_VERSION, cycle: state.cycle, pass: state.pass },\n },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n };\n\n const failCheckpoint = (requestId: string, error: unknown): void => {\n if (!active || requestId !== state.requestId || state.phase !== STATE_PHASE.checkpointPending) return;\n const failedLeafId = state.snapshotLeafId;\n state.phase = STATE_PHASE.waiting;\n if (failedLeafId) state.lastAttemptLeafId = failedLeafId;\n clearPendingCheckpoint();\n persist();\n notify(\n currentContext,\n `Doom autocompact summarization pass ${state.pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n 'error',\n );\n };\n\n const reportSnapshotFailures = (\n ctx: ExtensionContext,\n taskSnapshot: TaskSnapshot,\n teamSnapshot: TeamSnapshot,\n attributes: AutocompactEventAttributes,\n ): void => {\n if (!active) return;\n if (taskSnapshot.error) {\n notify(ctx, `Doom autocompact task steering degraded: ${taskSnapshot.error}`, 'warning');\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.taskSnapshotDegraded, new Error(taskSnapshot.error), attributes);\n }\n if (teamSnapshot.error) {\n notify(ctx, `Doom autocompact team steering degraded: ${teamSnapshot.error}`, 'warning');\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.teamSnapshotDegraded, new Error(teamSnapshot.error), attributes);\n }\n };\n\n const preserveRuntimeState = (\n ctx: ExtensionContext,\n branch: SessionEntry[],\n attributes: AutocompactEventAttributes,\n ): RuntimeStateSnapshot => {\n if (!active) {\n return { tasks: [], teamAvailable: false, teamMembers: [] };\n }\n const taskSnapshot = readTaskSnapshot(ctx);\n const teamSnapshot = readTeamSnapshot();\n reportSnapshotFailures(ctx, taskSnapshot, teamSnapshot, attributes);\n const snapshot = runtimeStateSnapshot(branch, taskSnapshot, teamSnapshot);\n pi.sendMessage({\n customType: RUNTIME_STATE_MESSAGE_TYPE,\n content: formatRuntimeState(snapshot),\n display: false,\n details: { version: 1, ...snapshot },\n });\n return snapshot;\n };\n\n const commitCheckpoint = (pass: 2 | 3, ctx: ExtensionContext): boolean => {\n if (!active || !state.requestId || !state.snapshotLeafId || !state.pendingCheckpoint) return false;\n const branch = ctx.sessionManager.getBranch();\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n const fileDetails = mergeFileDetails(state, fileOperationsFromMessages(projected));\n const requestId = state.requestId;\n const cycle = state.cycle;\n const summary = withCanonicalFileSections(state.pendingCheckpoint, fileDetails);\n const details: AutocompactContextDetails = {\n ...fileDetails,\n doomAutocompact: {\n version: STATE_VERSION,\n cycle,\n pass,\n requestId,\n snapshotLeafId: state.snapshotLeafId,\n tokensBefore: state.snapshotTokens ?? ctx.getContextUsage()?.tokens ?? 0,\n },\n retainedMessages: retainedMessagesAfterSnapshot(branch, state.snapshotLeafId),\n };\n\n notify(ctx, `Doom autocompact pass ${pass} context commit started.`);\n const committedWhileIdle = ctx.isIdle();\n pi.sendMessage({ customType: CONTEXT_MESSAGE_TYPE, content: summary, display: false, details });\n const contextMessageLeafId = workingLeafId(ctx);\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, branch, runtimeAttributes);\n // Mid-run the marker is queued as a steering message, so its entry id is not resolvable yet.\n if (committedWhileIdle) pi.setLabel(contextMessageLeafId, `autocompact:c${cycle}:p${pass}`);\n\n state.readFiles = fileDetails.readFiles;\n state.modifiedFiles = fileDetails.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n state.phase = STATE_PHASE.waiting;\n state.checkpointQueue = [];\n // A compacted context is a fresh ladder: passes abandoned in the previous cycle are eligible again.\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n state.baselinePending = true;\n delete state.lastAttemptLeafId;\n clearPendingCheckpoint();\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextCommitted,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': details.doomAutocompact.snapshotLeafId,\n 'autocompact.tokens_before': details.doomAutocompact.tokensBefore,\n 'autocompact.message_count.before': projected.length,\n 'autocompact.message_count.retained': details.retainedMessages.length,\n 'autocompact.apply_mode': committedWhileIdle ? 'idle' : 'turn_end',\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n notify(ctx, `Doom autocompact context committed. Baseline will be captured from the next settled context.`);\n // A mid-run commit needs no resume steer: the agent is already continuing.\n if (committedWhileIdle) resumeAgent('Asynchronous compaction completed.');\n return true;\n };\n\n const requestCheckpoint = (pass: AutocompactPass, ctx: ExtensionContext, tokensBefore: number): void => {\n if (!active) return;\n const generation = sessionGeneration;\n const branch = ctx.sessionManager.getBranch();\n const snapshotLeafId = workingLeafId(ctx);\n const requestId = createRequestId(ctx.sessionManager.getSessionId(), state.cycle, pass, snapshotLeafId);\n const previousCheckpoint = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(branch)) : undefined;\n const messages = messagesForCheckpoint(pass, branch, state.latestCheckpointSnapshotLeafId);\n const taskSnapshot = readTaskSnapshot(ctx);\n const teamSnapshot = readTeamSnapshot();\n const attributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': snapshotLeafId,\n 'autocompact.tokens_before': tokensBefore,\n 'autocompact.message_count.before': messages.length,\n });\n reportSnapshotFailures(ctx, taskSnapshot, teamSnapshot, attributes);\n\n state.phase = STATE_PHASE.checkpointPending;\n state.pass = pass;\n state.requestId = requestId;\n state.snapshotLeafId = snapshotLeafId;\n state.snapshotTokens = tokensBefore;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n delete state.lastAttemptLeafId;\n persist();\n\n checkpointController?.abort();\n checkpointController = new AbortController();\n const checkpointSignal = checkpointController.signal;\n notify(ctx, `Doom autocompact summarization pass ${pass} started.`);\n const operation = telemetry\n .runInSpan('doom_autocompact.checkpoint', attributes, async () => {\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, attributes);\n try {\n const checkpoint = await generateCheckpoint({\n messages,\n instructions: checkpointInstructions(pass, {\n plan: latestPlanSnapshot(branch),\n taskSnapshot,\n teamSnapshot,\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n }),\n ...(previousCheckpoint ? { previousCheckpoint } : {}),\n context: ctx,\n signal: checkpointSignal,\n });\n if (!active || generation !== sessionGeneration) {\n throw checkpointSignal.reason ?? new Error('Autocompact checkpoint became stale.');\n }\n if (!checkpoint.trim()) throw new Error('Summarization returned an empty checkpoint.');\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {\n ...attributes,\n 'autocompact.checkpoint.characters': checkpoint.length,\n });\n return checkpoint;\n } catch (error) {\n if (active && generation === sessionGeneration) {\n await telemetry.recordError(AUTOCOMPACT_EVENT.checkpointFailed, error, attributes);\n }\n throw error;\n }\n })\n .then((checkpoint) => {\n if (\n !active ||\n generation !== sessionGeneration ||\n requestId !== state.requestId ||\n state.phase !== STATE_PHASE.checkpointPending\n ) {\n return;\n }\n state.phase = STATE_PHASE.checkpointReady;\n state.pendingCheckpoint = checkpoint.trim();\n persist();\n notify(currentContext, `Doom autocompact summarization pass ${pass} completed.`);\n if (currentContext) processProgress(currentContext);\n })\n .catch((error: unknown) => {\n if (active && generation === sessionGeneration) failCheckpoint(requestId, error);\n });\n checkpointWork.add(operation);\n void operation.finally(() => checkpointWork.delete(operation));\n };\n\n const evaluateUsage = (ctx: ExtensionContext): boolean => {\n if (!active || state.phase !== STATE_PHASE.waiting || ctx.hasPendingMessages()) return false;\n const usage = ctx.getContextUsage();\n if (!usage || usage.tokens === null) return false;\n if (state.baselinePending) {\n // Reported usage still describes the pre-compaction context until an assistant\n // responds against the projected one, and capturing it early poisons every threshold.\n if (!baselineUsageIsSettled(ctx.sessionManager.getBranch())) return false;\n state.baselineTokens = usage.tokens;\n state.baselinePending = false;\n persist();\n notify(ctx, `Doom autocompact baseline captured at ${state.baselineTokens} tokens.`);\n return false;\n }\n const leafId = workingLeafId(ctx);\n if (state.lastAttemptLeafId === leafId) return false;\n\n for (const pass of [1, 2, 3] as const) {\n if (pass < state.pass || state.checkpointQueue.includes(pass) || state.exhaustedPasses.includes(pass)) continue;\n if (usage.tokens >= thresholdTokens(pass, usage.contextWindow, state.baselineTokens)) {\n state.checkpointQueue.push(pass);\n }\n }\n const nextPass = state.checkpointQueue[0];\n if (!nextPass) return false;\n requestCheckpoint(nextPass, ctx, usage.tokens);\n return true;\n };\n\n // Staged checkpoints seed the next summarization pass only. They are appended as plain\n // session entries so they never enter the agent's LLM context: delivering them as messages\n // reads like a user instruction and derails the run (\"Checkpoint acknowledged...\").\n const stageCheckpoint = (pass: 1 | 2, summary: string): void => {\n if (!active) return;\n const checkpointSnapshotLeafId = state.snapshotLeafId;\n pi.appendEntry(CHECKPOINT_MESSAGE_TYPE, {\n ...checkpointRequestDetails(state.cycle, pass, state.requestId ?? 'completed'),\n summary,\n });\n if (checkpointSnapshotLeafId) state.latestCheckpointSnapshotLeafId = checkpointSnapshotLeafId;\n };\n\n const captureReadyCheckpoint = (ctx: ExtensionContext): CheckpointCapture => {\n if (!active || state.phase !== STATE_PHASE.checkpointReady || !state.requestId || !state.pendingCheckpoint) {\n return 'none';\n }\n const pass = state.pass;\n const decision = parseCheckpointDecision(state.pendingCheckpoint);\n if (!isStructuredCheckpoint(decision.summary)) {\n const failedLeafId = state.snapshotLeafId;\n const invalidRequestId = state.requestId;\n // A queued pass is retried once per new leaf, so an output the summarizer never formats\n // correctly would otherwise burn a full summarization call every turn for the session.\n const attempts = state.invalidAttempts + 1;\n const exhausted = attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS;\n state.phase = STATE_PHASE.waiting;\n if (failedLeafId) state.lastAttemptLeafId = failedLeafId;\n if (exhausted) {\n completeQueuedPass(pass);\n state.exhaustedPasses = [...state.exhaustedPasses, pass];\n state.invalidAttempts = 0;\n } else {\n state.invalidAttempts = attempts;\n }\n clearPendingCheckpoint();\n persist();\n const error = new Error(`Summarization pass ${pass} returned an incomplete checkpoint.`);\n notify(\n ctx,\n exhausted\n ? `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint ${attempts} times and was abandoned.`\n : `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint.`,\n 'error',\n );\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.checkpointInvalid,\n error,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': exhausted,\n ...(invalidRequestId ? { 'autocompact.request.id': invalidRequestId } : {}),\n }),\n );\n return 'invalid';\n }\n\n state.invalidAttempts = 0;\n\n if (pass === 1) {\n stageCheckpoint(1, decision.summary);\n completeQueuedPass(1);\n state.phase = STATE_PHASE.waiting;\n state.pass = 2;\n clearPendingCheckpoint();\n persist();\n return 'pass1';\n }\n\n if (pass === 2 && decision.shouldCompact !== true) {\n stageCheckpoint(2, decision.summary);\n completeQueuedPass(2);\n state.phase = STATE_PHASE.waiting;\n state.pass = 3;\n clearPendingCheckpoint();\n persist();\n return 'deferred';\n }\n\n state.pendingCheckpoint = decision.summary;\n return commitCheckpoint(pass, ctx) ? 'committed' : 'invalid';\n };\n\n function processProgress(ctx: ExtensionContext): void {\n if (!active) return;\n currentContext = ctx;\n if (!ctx.isIdle()) return;\n if (captureReadyCheckpoint(ctx) !== 'committed') evaluateUsage(ctx);\n }\n\n pi.on('context', (event, ctx) => {\n if (!active) return undefined;\n const projection = projectContextMessages(event.messages, ctx.sessionManager.getBranch());\n if (projection.invalidMarker) {\n const leafId = ctx.sessionManager.getLeafId() ?? ROOT_WORKING_LEAF;\n if (!invalidContextLeaves.has(leafId)) {\n invalidContextLeaves.add(leafId);\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.contextMarkerInvalid,\n new Error('Doom autocompact context marker is malformed.'),\n telemetryAttributes(ctx, { 'autocompact.leaf_id': leafId }),\n );\n }\n return undefined;\n }\n if (!projection.marker) return undefined;\n if (!appliedContextRequests.has(projection.marker.requestId)) {\n appliedContextRequests.add(projection.marker.requestId);\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextApplied,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': projection.marker.requestId,\n 'autocompact.cycle': projection.marker.cycle,\n 'autocompact.pass': projection.marker.pass,\n 'autocompact.snapshot_leaf_id': projection.marker.snapshotLeafId,\n 'autocompact.tokens_before': projection.marker.tokensBefore,\n 'autocompact.message_count.before': event.messages.length,\n 'autocompact.message_count.after': projection.messages.length,\n 'autocompact.message_count.retained': projection.retainedMessageCount,\n }),\n );\n }\n return { messages: projection.messages };\n });\n\n const beginSessionGeneration = (ctx: ExtensionContext): void => {\n if (!active) return;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact session generation was replaced.'));\n checkpointController = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n currentContext = ctx;\n restore(ctx);\n processProgress(ctx);\n };\n\n pi.on('session_start', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('session_tree', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('turn_end', (event, ctx) => {\n if (!active) return;\n currentContext = ctx;\n if (ctx.isIdle()) {\n processProgress(ctx);\n return;\n }\n // A ready checkpoint must be applied without waiting for the run to finish, otherwise\n // context keeps growing past the window for the rest of a long autonomous run. Tool\n // results confirm the run continues, so the queued marker lands before the next request.\n const canApplyDuringRun =\n state.phase === STATE_PHASE.checkpointReady && (event.toolResults?.length ?? 0) > 0 && !ctx.hasPendingMessages();\n if (canApplyDuringRun && captureReadyCheckpoint(ctx) !== 'none') return;\n evaluateUsage(ctx);\n });\n\n pi.on('agent_settled', (_event, ctx) => {\n if (!active) return;\n processProgress(ctx);\n });\n\n pi.on('session_before_compact', (event) => {\n if (!active || event.reason !== 'threshold') return undefined;\n // Native compaction stays cancelled while our own machinery is working, and stays\n // available as the emergency backstop once that machinery has stalled or declined.\n const machineryActive =\n state.phase === STATE_PHASE.checkpointPending ||\n state.phase === STATE_PHASE.checkpointReady ||\n state.baselinePending;\n return machineryActive ? { cancel: true } : undefined;\n });\n\n pi.on('session_compact', (event, ctx) => {\n if (!active) return;\n sessionGeneration += 1;\n // Native compaction supersedes any summarization still in flight.\n checkpointController?.abort();\n checkpointController = undefined;\n const eventDetails = fileDetailsFromUnknown(event.compactionEntry.details);\n const cumulative = mergeFileDetails(state, undefined, eventDetails);\n state.readFiles = cumulative.readFiles;\n state.modifiedFiles = cumulative.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n // Reported usage still describes the pre-compaction context here too, so the baseline\n // waits for the first assistant response measured against the compacted one.\n state.baselinePending = true;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n state.checkpointQueue = [];\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n delete state.lastAttemptLeafId;\n\n pi.setLabel(event.compactionEntry.id, `autocompact:c${state.cycle}:external`);\n const completedCycle = state.cycle;\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, ctx.sessionManager.getBranch(), runtimeAttributes);\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.nativeCompactionCompleted,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n 'autocompact.native.from_extension': event.fromExtension,\n 'autocompact.tokens_before': event.compactionEntry.tokensBefore,\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n notify(\n ctx,\n `Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${state.pass}.`,\n );\n });\n}\n\n/** The package's single standard Pi factory. */\nexport async function autocompactExtension(pi: ExtensionAPI): Promise<void> {\n const cordis = new Context();\n let disposal: Promise<void> | undefined;\n const dispose = (): Promise<void> => {\n disposal ??= cordis.fiber.dispose();\n return disposal;\n };\n\n try {\n installAutocompactRuntime(cordis, pi);\n } catch (error) {\n await dispose();\n throw error;\n }\n\n pi.on('session_shutdown', dispose);\n}\n\nexport default autocompactExtension;\n"],"mappings":"+iDAsDA,MAAM,GAAoB,QAEpB,EAAgB,mBAGhB,EAAc,CAClB,QAAS,UACT,kBAAmB,qBACnB,gBAAiB,mBACjB,WAAY,aACb,CAwED,SAAS,EACP,EACA,EAAyC,EAAE,CACf,CAC5B,MAAO,CACL,gBAAiB,EAAQ,eAAe,cAAc,CACtD,GAAG,EACJ,CAGH,SAAS,GAAqB,EAAsD,CAClF,IAAK,IAAI,EAAQ,EAAO,OAAS,EAAG,GAAS,EAAG,IAAY,CAC1D,IAAM,EAAQ,EAAO,GACrB,GAAI,GAAO,OAAS,UAAY,EAAM,aAAA,yBAAkC,SACxE,IAAM,EAAS,EA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jC,OAAO,EAAM,+BAGb,EAAM,gBAAkB,GACxB,EAAM,MAAQ,EAAY,QAC1B,GAAwB,CACxB,EAAM,gBAAkB,EAAE,CAC1B,EAAM,gBAAkB,EAAE,CAC1B,EAAM,gBAAkB,EACxB,OAAO,EAAM,kBAEb,EAAG,SAAS,EAAM,gBAAgB,GAAI,gBAAgB,EAAM,MAAM,WAAW,CAC7E,IAAM,EAAiB,EAAM,MACvB,EAAoB,EAAoB,EAAK,CACjD,oBAAqB,EACrB,4BAA6B,EAAM,OACpC,CAAC,CACI,EAAkB,EAAqB,EAAK,EAAI,eAAe,WAAW,CAAE,EAAkB,CACpG,EAAM,OAAS,EACf,EAAM,KAAO,EACb,GAAS,CACJ,EAAU,YACb,EAAkB,0BAClB,EAAoB,EAAK,CACvB,oBAAqB,EACrB,4BAA6B,EAAM,OACnC,oCAAqC,EAAM,cAC3C,4BAA6B,EAAM,gBAAgB,aACnD,GAAG,EAA2B,EAAgB,CAC/C,CAAC,CACH,CACD,EACE,EACA,mGAAmG,EAAM,KAAK,GAC/G,EACD,CAIJ,eAAsB,EAAqB,EAAiC,CAC1E,IAAM,EAAS,IAAI,EACf,EACE,OACJ,IAAa,EAAO,MAAM,SAAS,CAC5B,GAGT,GAAI,CACF,EAA0B,EAAQ,EAAG,OAC9B,EAAO,CAEd,MADA,MAAM,GAAS,CACT,EAGR,EAAG,GAAG,mBAAoB,EAAQ"}
1
+ {"version":3,"file":"extension.mjs","names":[],"sources":["../../../../src/adapters/pi/extension.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { Worker } from 'node:worker_threads';\n\nimport { getHarnessState, loadDoomConfig, type PlanningAgentConfig } from '@agimon-ai/doompi-config';\nimport { connectDoomCordisHost } from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport { resolveSessionKey } from '@agimon-ai/doompi-task/store/paths';\nimport { TaskStore } from '@agimon-ai/doompi-task/store/taskStore';\nimport type { Task } from '@agimon-ai/doompi-task/store/types';\nimport { readActiveTeamSnapshot, type TeamMemberSnapshot } from '@agimon-ai/doompi-team/api/team-snapshot';\nimport type { DoomFooterContributionHandle } from '@agimon-ai/doompi-extension-contracts/footer';\nimport { DOOM_UI_HUB_SERVICE, requireDoomUiHub } from '@agimon-ai/doompi-extension-contracts/ui-hub';\nimport type { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent';\nimport {\n buildSessionContext,\n DEFAULT_COMPACTION_SETTINGS,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n createInitialState,\n createRequestId,\n fileDetailsFromUnknown,\n fileOperationsFromMessages,\n isStructuredCheckpoint,\n latestCheckpointArtifactEntry,\n mergeFileDetails,\n parseCheckpointDecision,\n parseState,\n projectContextMessages,\n retainedMessagesAfterSnapshot,\n thresholdTokens,\n withCanonicalFileSections,\n} from '../../adapters/compaction/policy';\nimport { parseModelReference, type SummarizationModel } from '../../services/summarizationModel.ts';\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../types/constants.ts';\nimport type { AutocompactEventAttributes, AutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../telemetry/logSinkTelemetry.ts';\n\nexport type { ModelReference, SummarizationModel } from '../../services/summarizationModel.ts';\nexport { parseModelReference, resolveSummarizationModel } from '../../services/summarizationModel.ts';\n\nimport type { AutocompactContextDetails, AutocompactPass, AutocompactState } from '../../types/index.ts';\n\nconst ROOT_WORKING_LEAF = '@root';\nconst PACKAGE_SOURCE = '@agimon-ai/doompi-autocompact';\nconst PLAN_DOCUMENT_ENTRY = 'agent-harness-plan-document';\nconst FOOTER_SOURCE = 'doom-autocompact';\nconst FOOTER_ORDER = 20;\nconst STATUS_KEY = 'doom-autocompact';\nconst STATE_PHASE = {\n waiting: 'waiting',\n checkpointPending: 'checkpoint_pending',\n checkpointReady: 'checkpoint_ready',\n compacting: 'compacting',\n} as const;\ntype CheckpointCapture = 'none' | 'pass1' | 'committed' | 'deferred' | 'invalid';\ntype CheckpointMessages = ReturnType<typeof buildSessionContext>['messages'];\n\ninterface PlanSnapshot {\n content: string;\n path: string;\n}\n\ninterface TaskSnapshot {\n tasks: Task[];\n error?: string;\n}\n\ninterface TeamSnapshot {\n members?: TeamMemberSnapshot[];\n error?: string;\n}\n\ninterface SteeringSnapshot {\n plan?: PlanSnapshot;\n taskSnapshot: TaskSnapshot;\n teamSnapshot: TeamSnapshot;\n readFiles: string[];\n modifiedFiles: string[];\n}\n\ninterface RuntimeTaskSnapshot {\n id: number;\n status: Task['status'];\n subject: string;\n activeForm?: string;\n owner?: string;\n blockedBy?: number[];\n delegation?: {\n agent: string;\n state: NonNullable<Task['delegation']>['state'];\n error?: string;\n };\n}\n\ninterface RuntimeStateSnapshot {\n planPath?: string;\n tasks: RuntimeTaskSnapshot[];\n taskError?: string;\n teamAvailable: boolean;\n teamMembers: TeamMemberSnapshot[];\n teamError?: string;\n}\n\ninterface CheckpointGenerationInput {\n messages: CheckpointMessages;\n instructions: string;\n previousCheckpoint?: string;\n context: ExtensionContext;\n signal: AbortSignal;\n}\n\ninterface CheckpointWorkerResult {\n checkpoint?: string;\n error?: string;\n}\n\nexport interface AutocompactDependencies {\n generateCheckpoint?: (input: CheckpointGenerationInput) => Promise<string>;\n readTaskSnapshot?: (context: ExtensionContext) => TaskSnapshot;\n readTeamSnapshot?: () => TeamSnapshot;\n resolveModel?: (context: ExtensionContext) => SummarizationModel | undefined;\n telemetry?: AutocompactTelemetry;\n doomIntegrations?: boolean;\n}\n\nfunction telemetryAttributes(\n context: ExtensionContext,\n attributes: AutocompactEventAttributes = {},\n): AutocompactEventAttributes {\n return {\n 'pi.session.id': context.sessionManager.getSessionId(),\n ...attributes,\n };\n}\n\nfunction latestPersistedState(branch: SessionEntry[]): AutocompactState | undefined {\n for (let index = branch.length - 1; index >= 0; index -= 1) {\n const entry = branch[index];\n if (entry?.type !== 'custom' || entry.customType !== STATE_CUSTOM_TYPE) continue;\n const parsed = parseState(entry.data);\n if (parsed) return parsed;\n }\n return undefined;\n}\n\nfunction workingLeafId(ctx: ExtensionContext): string {\n for (const entry of ctx.sessionManager.getBranch().toReversed()) {\n if (entry.type === 'custom' && entry.customType === STATE_CUSTOM_TYPE) continue;\n if (entry.type === 'label') continue;\n return entry.id;\n }\n return ROOT_WORKING_LEAF;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction latestPlanSnapshot(branch: SessionEntry[]): PlanSnapshot | undefined {\n for (const entry of branch.toReversed()) {\n if (entry.type !== 'custom' || entry.customType !== PLAN_DOCUMENT_ENTRY) continue;\n if (!entry.data || typeof entry.data !== 'object') return undefined;\n const data = entry.data as Record<string, unknown>;\n if (typeof data.content !== 'string' || typeof data.path !== 'string') return undefined;\n return { content: data.content, path: data.path };\n }\n return undefined;\n}\n\nfunction readTaskSnapshotWithDoomTask(context: ExtensionContext): TaskSnapshot {\n const failures: string[] = [];\n try {\n const store = new TaskStore({\n cwd: context.cwd,\n report: {\n error: (event, error) => failures.push(`${event}: ${errorMessage(error)}`),\n warn: (event, error) => failures.push(`${event}: ${errorMessage(error)}`),\n event: () => undefined,\n },\n });\n store.configureSession(resolveSessionKey(context.sessionManager.getSessionId()));\n const tasks = store.read().tasks;\n return { tasks, ...(failures.length > 0 ? { error: failures.join('; ') } : {}) };\n } catch (error) {\n return { tasks: [], error: errorMessage(error) };\n }\n}\n\nfunction readTeamSnapshotWithDoomTeam(): TeamSnapshot {\n try {\n const snapshot = readActiveTeamSnapshot();\n return snapshot ? { members: snapshot.members } : {};\n } catch (error) {\n return { error: errorMessage(error) };\n }\n}\n\nfunction activeTaskSnapshots(snapshot: TaskSnapshot): RuntimeTaskSnapshot[] {\n return snapshot.tasks\n .filter((task) => task.status === 'pending' || task.status === 'in_progress' || task.status === 'failed')\n .map((task) => ({\n id: task.id,\n status: task.status,\n subject: task.subject,\n ...(task.activeForm ? { activeForm: task.activeForm } : {}),\n ...(task.owner ? { owner: task.owner } : {}),\n ...(task.blockedBy?.length ? { blockedBy: task.blockedBy } : {}),\n ...(task.delegation\n ? {\n delegation: {\n agent: task.delegation.agent,\n state: task.delegation.state,\n ...(task.delegation.result?.error ? { error: task.delegation.result.error } : {}),\n },\n }\n : {}),\n }));\n}\n\nfunction formatRuntimeTasks(tasks: RuntimeTaskSnapshot[], error?: string): string {\n const lines = tasks.map((task) => {\n const details = [\n task.activeForm ? `active: ${task.activeForm}` : undefined,\n task.owner ? `owner: ${task.owner}` : undefined,\n task.blockedBy?.length ? `blocked by: ${task.blockedBy.join(', ')}` : undefined,\n task.delegation ? `delegation: ${task.delegation.agent} (${task.delegation.state})` : undefined,\n task.delegation?.error ? `error: ${task.delegation.error}` : undefined,\n ].filter((value): value is string => Boolean(value));\n return `- #${task.id} [${task.status}] ${task.subject}${details.length > 0 ? ` | ${details.join(' | ')}` : ''}`;\n });\n if (error) lines.push(`- Task snapshot error: ${error}`);\n return lines.length > 0 ? lines.join('\\n') : '(no active tasks)';\n}\n\nfunction formatTeamSnapshot(snapshot: TeamSnapshot): string {\n const lines = (snapshot.members ?? []).map((member) => {\n const details = [\n `role: ${member.role}`,\n member.agent ? `agent: ${member.agent}` : undefined,\n member.runId ? `run: ${member.runId}` : undefined,\n member.task ? `task ${member.task.id}: ${member.task.subject}` : undefined,\n ].filter((value): value is string => Boolean(value));\n return `- ${member.name} | ${details.join(' | ')}`;\n });\n if (snapshot.error) lines.push(`- Team snapshot error: ${snapshot.error}`);\n if (lines.length > 0) return lines.join('\\n');\n return snapshot.members ? '(no active team members)' : '(team runtime unavailable)';\n}\n\nfunction runtimeStateSnapshot(\n branch: SessionEntry[],\n taskSnapshot: TaskSnapshot,\n teamSnapshot: TeamSnapshot,\n): RuntimeStateSnapshot {\n const plan = latestPlanSnapshot(branch);\n return {\n ...(plan ? { planPath: plan.path } : {}),\n tasks: activeTaskSnapshots(taskSnapshot),\n ...(taskSnapshot.error ? { taskError: taskSnapshot.error } : {}),\n teamAvailable: Boolean(teamSnapshot.members),\n teamMembers: teamSnapshot.members ?? [],\n ...(teamSnapshot.error ? { teamError: teamSnapshot.error } : {}),\n };\n}\n\nfunction formatRuntimeState(snapshot: RuntimeStateSnapshot): string {\n const plan = snapshot.planPath\n ? `Source: ${snapshot.planPath}\\nExact plan content is restored separately by Doom Plan.`\n : '(no active plan document)';\n const teamSnapshot: TeamSnapshot = {\n ...(snapshot.teamAvailable ? { members: snapshot.teamMembers } : {}),\n ...(snapshot.teamError ? { error: snapshot.teamError } : {}),\n };\n return `<compaction-runtime-state>\nAuthoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.\n<active-plan>\n${plan}\n</active-plan>\n<active-tasks>\n${formatRuntimeTasks(snapshot.tasks, snapshot.taskError)}\n</active-tasks>\n<active-team>\n${formatTeamSnapshot(teamSnapshot)}\n</active-team>\n</compaction-runtime-state>`;\n}\n\nfunction runtimeTelemetryAttributes(snapshot: RuntimeStateSnapshot): AutocompactEventAttributes {\n return {\n 'autocompact.runtime.plan_present': Boolean(snapshot.planPath),\n 'autocompact.runtime.task_count': snapshot.tasks.length,\n 'autocompact.runtime.team_available': snapshot.teamAvailable,\n 'autocompact.runtime.team_member_count': snapshot.teamMembers.length,\n };\n}\n\nfunction steeringEnvelope(snapshot: SteeringSnapshot): string {\n const plan = snapshot.plan\n ? `Source: ${snapshot.plan.path}\\n\\n${snapshot.plan.content}`\n : '(no active plan document)';\n const importantContext = [\n snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(', ')}` : undefined,\n snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(', ')}` : undefined,\n ].filter((value): value is string => Boolean(value));\n\n return `<compaction-steering priority=\"user,plan,tasks,team,important-context,recent-messages\">\n<user-prompt source=\"conversation\">\nTreat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.\n</user-prompt>\n<active-plan>\n${plan}\n</active-plan>\n<active-tasks>\n${formatRuntimeTasks(activeTaskSnapshots(snapshot.taskSnapshot), snapshot.taskSnapshot.error)}\n</active-tasks>\n<active-team>\n${formatTeamSnapshot(snapshot.teamSnapshot)}\n</active-team>\n<important-context>\n${importantContext.length > 0 ? importantContext.join('\\n') : '(none recorded outside the conversation)'}\n</important-context>\n</compaction-steering>`;\n}\n\nfunction checkpointInstructions(pass: AutocompactPass, steering: SteeringSnapshot): string {\n const decision =\n pass === 2\n ? 'Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\\n\\n'\n : '';\n\n // Summarization is a tool-less single LLM call, so instructions describe only what to\n // produce. Directives aimed at an implementing agent leak into the checkpoint body.\n return `Create Doom autocompact checkpoint pass ${pass}.\n\n${steeringEnvelope(steering)}\n\nApply the steering evidence in priority order. Do not invent plan, task, or team state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.\n\n${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.\n\n## Goal\n## Constraints & Preferences\n## Progress\n### Done\n### In Progress\n### Blocked\n## Key Decisions\n## Next Steps\n## Critical Context`;\n}\n\nfunction messagesForCheckpoint(\n pass: AutocompactPass,\n branch: SessionEntry[],\n previousSnapshotLeafId: string | undefined,\n): CheckpointMessages {\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n if (pass === 1 || !previousSnapshotLeafId) return projected;\n const snapshotIndex = branch.findIndex((entry) => entry.id === previousSnapshotLeafId);\n if (snapshotIndex === -1) return projected;\n return branch\n .slice(snapshotIndex + 1)\n .filter((entry) => entry.type !== 'custom_message' || entry.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap((entry) => sessionEntryToContextMessages(entry));\n}\n\nexport function findCheckpointWorkerUrl(importFileUrl: string | URL): URL {\n const importFilePath = fileURLToPath(importFileUrl);\n let directory = dirname(importFilePath);\n\n while (true) {\n const workerPath = join(directory, 'checkpointWorker.mjs');\n if (existsSync(workerPath)) return pathToFileURL(workerPath);\n\n const parent = dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n\n throw new Error(`Cannot find checkpointWorker.mjs by walking from ${importFilePath}.`);\n}\n\nfunction runCheckpointWorker(workerInput: Record<string, unknown>, signal: AbortSignal): Promise<string> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(findCheckpointWorkerUrl(import.meta.url), { workerData: workerInput });\n let settled = false;\n\n const settle = (complete: () => void): void => {\n if (settled) return;\n settled = true;\n signal.removeEventListener('abort', abort);\n complete();\n };\n const abort = (): void => {\n settle(() => {\n void worker.terminate();\n reject(signal.reason instanceof Error ? signal.reason : new Error('Autocompact summarization aborted.'));\n });\n };\n\n worker.once('message', (result: CheckpointWorkerResult) => {\n settle(() => {\n if (typeof result.checkpoint === 'string') resolve(result.checkpoint);\n else reject(new Error(result.error ?? 'Autocompact summarization worker returned no checkpoint.'));\n });\n });\n worker.once('error', (error) => settle(() => reject(error)));\n worker.once('exit', (code) => {\n if (code !== 0) settle(() => reject(new Error(`Autocompact summarization worker exited with code ${code}.`)));\n });\n signal.addEventListener('abort', abort, { once: true });\n worker.unref();\n if (signal.aborted) abort();\n });\n}\n\nfunction subagentModelConfig(cwd: string): PlanningAgentConfig | undefined {\n try {\n return loadDoomConfig(getHarnessState().root ?? cwd).modes?.planning?.subagents;\n } catch {\n process.emitWarning(\n 'Doom autocompact planning configuration could not be loaded; using the active session model instead.',\n );\n return undefined;\n }\n}\n\n/** Explicit Doom model selection honors the configured planning subagent model. */\nexport function resolveDoomSummarizationModel(ctx: ExtensionContext): SummarizationModel | undefined {\n const configured = subagentModelConfig(ctx.cwd);\n const reference = configured?.model ? parseModelReference(configured.model) : undefined;\n const configuredModel = reference ? ctx.modelRegistry.find(reference.provider, reference.modelId) : undefined;\n const model = configuredModel ?? ctx.model;\n if (!model) return undefined;\n const thinkingLevel =\n configured?.thinking ?? (configuredModel ? reference?.thinking : undefined) ?? ctx.thinkingLevel;\n return { model, ...(thinkingLevel ? { thinkingLevel } : {}) };\n}\n\nasync function generateCheckpointWithPi(\n input: CheckpointGenerationInput,\n resolveModel: (context: ExtensionContext) => SummarizationModel | undefined,\n): Promise<string> {\n const selection = resolveModel(input.context);\n if (!selection) throw new Error('No active model is available for autocompact summarization.');\n const auth = await input.context.modelRegistry.getApiKeyAndHeaders(selection.model);\n if (!auth.ok) throw new Error(auth.error);\n return runCheckpointWorker(\n {\n messages: input.messages,\n model: selection.model,\n reserveTokens: DEFAULT_COMPACTION_SETTINGS.reserveTokens,\n apiKey: auth.apiKey,\n headers: auth.headers,\n instructions: input.instructions,\n previousCheckpoint: input.previousCheckpoint,\n thinkingLevel: selection.thinkingLevel,\n env: auth.env,\n },\n input.signal,\n );\n}\n\nfunction notify(ctx: ExtensionContext | undefined, message: string, level: 'info' | 'warning' | 'error' = 'info') {\n if (ctx?.hasUI) ctx.ui.notify(message, level);\n}\n\nexport function installAutocompactRuntime(\n cordis: Context,\n pi: ExtensionAPI,\n dependencies: AutocompactDependencies = {},\n): void {\n const resolveModel = dependencies.resolveModel ?? resolveDoomSummarizationModel;\n const generateCheckpoint =\n dependencies.generateCheckpoint ??\n ((input: CheckpointGenerationInput) => generateCheckpointWithPi(input, resolveModel));\n const readTaskSnapshot = dependencies.readTaskSnapshot ?? readTaskSnapshotWithDoomTask;\n const readTeamSnapshot = dependencies.readTeamSnapshot ?? readTeamSnapshotWithDoomTeam;\n const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();\n const doomIntegrations = dependencies.doomIntegrations ?? true;\n const appliedContextRequests = new Set<string>();\n const invalidContextLeaves = new Set<string>();\n const checkpointWork = new Set<Promise<void>>();\n let active = true;\n let sessionGeneration = 0;\n let state = createInitialState();\n let currentContext: ExtensionContext | undefined;\n let checkpointController: AbortController | undefined;\n let footerContribution: DoomFooterContributionHandle | undefined;\n\n cordis.effect(\n () => async () => {\n active = false;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact runtime is shutting down.'));\n checkpointController = undefined;\n await Promise.allSettled(checkpointWork);\n footerContribution = undefined;\n currentContext = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n state = createInitialState();\n await telemetry.shutdown();\n },\n `${FOOTER_SOURCE}/runtime`,\n );\n\n if (doomIntegrations) {\n cordis.inject([DOOM_UI_HUB_SERVICE], (uiContext) => {\n const contribution = requireDoomUiHub(uiContext).registerFooter({\n source: FOOTER_SOURCE,\n id: 'autocompact',\n order: FOOTER_ORDER,\n });\n footerContribution = contribution;\n return () => {\n contribution.dispose();\n if (footerContribution === contribution) footerContribution = undefined;\n };\n });\n }\n\n /** Compaction runs off the main thread, so the phase is the only signal the user gets. */\n const refreshStatus = (ctx?: ExtensionContext): void => {\n if (!active) return;\n const phase =\n state.phase === STATE_PHASE.checkpointPending\n ? 'summarizing'\n : state.phase === STATE_PHASE.checkpointReady\n ? 'applying'\n : undefined;\n footerContribution?.update(\n phase ? { fullText: `Compacting p${state.pass}`, compactText: `C${state.pass}` } : undefined,\n );\n const target = ctx ?? currentContext;\n if (target?.hasUI) target.ui.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : undefined);\n };\n\n // Every phase transition persists, so this is the one place that keeps the status honest.\n const persist = (): void => {\n if (!active) return;\n pi.appendEntry(STATE_CUSTOM_TYPE, { ...state });\n refreshStatus();\n };\n\n const clearPendingCheckpoint = (): void => {\n delete state.requestId;\n delete state.snapshotLeafId;\n delete state.snapshotTokens;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n };\n\n const completeQueuedPass = (pass: AutocompactPass): void => {\n state.checkpointQueue = state.checkpointQueue.filter((queuedPass) => queuedPass !== pass);\n };\n\n const restore = (ctx: ExtensionContext): void => {\n if (!active) return;\n state = latestPersistedState(ctx.sessionManager.getBranch()) ?? createInitialState();\n const resumablePending =\n state.phase === STATE_PHASE.checkpointReady && state.requestId && state.snapshotLeafId && state.pendingCheckpoint;\n if (resumablePending || state.phase === STATE_PHASE.waiting) return;\n\n checkpointController?.abort();\n checkpointController = undefined;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n persist();\n };\n\n const resumeAgent = (message: string): void => {\n if (!active) return;\n pi.sendMessage(\n {\n customType: RESUME_MESSAGE_TYPE,\n content: `${message} Continue from the compacted checkpoint's immediate next action without repeating completed work.`,\n display: false,\n details: { version: STATE_VERSION, cycle: state.cycle, pass: state.pass },\n },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n };\n\n const failCheckpoint = (requestId: string, error: unknown): void => {\n if (!active || requestId !== state.requestId || state.phase !== STATE_PHASE.checkpointPending) return;\n const failedLeafId = state.snapshotLeafId;\n state.phase = STATE_PHASE.waiting;\n if (failedLeafId) state.lastAttemptLeafId = failedLeafId;\n clearPendingCheckpoint();\n persist();\n notify(\n currentContext,\n `Doom autocompact summarization pass ${state.pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n 'error',\n );\n };\n\n const reportSnapshotFailures = (\n ctx: ExtensionContext,\n taskSnapshot: TaskSnapshot,\n teamSnapshot: TeamSnapshot,\n attributes: AutocompactEventAttributes,\n ): void => {\n if (!active) return;\n if (taskSnapshot.error) {\n notify(ctx, `Doom autocompact task steering degraded: ${taskSnapshot.error}`, 'warning');\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.taskSnapshotDegraded, new Error(taskSnapshot.error), attributes);\n }\n if (teamSnapshot.error) {\n notify(ctx, `Doom autocompact team steering degraded: ${teamSnapshot.error}`, 'warning');\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.teamSnapshotDegraded, new Error(teamSnapshot.error), attributes);\n }\n };\n\n const preserveRuntimeState = (\n ctx: ExtensionContext,\n branch: SessionEntry[],\n attributes: AutocompactEventAttributes,\n ): RuntimeStateSnapshot => {\n if (!active) {\n return { tasks: [], teamAvailable: false, teamMembers: [] };\n }\n const taskSnapshot = readTaskSnapshot(ctx);\n const teamSnapshot = readTeamSnapshot();\n reportSnapshotFailures(ctx, taskSnapshot, teamSnapshot, attributes);\n const snapshot = runtimeStateSnapshot(branch, taskSnapshot, teamSnapshot);\n pi.sendMessage({\n customType: RUNTIME_STATE_MESSAGE_TYPE,\n content: formatRuntimeState(snapshot),\n display: false,\n details: { version: 1, ...snapshot },\n });\n return snapshot;\n };\n\n const commitCheckpoint = (pass: 2 | 3, ctx: ExtensionContext): boolean => {\n if (!active || !state.requestId || !state.snapshotLeafId || !state.pendingCheckpoint) return false;\n const branch = ctx.sessionManager.getBranch();\n const projected = projectContextMessages(buildSessionContext(branch).messages, branch).messages;\n const fileDetails = mergeFileDetails(state, fileOperationsFromMessages(projected));\n const requestId = state.requestId;\n const cycle = state.cycle;\n const summary = withCanonicalFileSections(state.pendingCheckpoint, fileDetails);\n const details: AutocompactContextDetails = {\n ...fileDetails,\n doomAutocompact: {\n version: STATE_VERSION,\n cycle,\n pass,\n requestId,\n snapshotLeafId: state.snapshotLeafId,\n tokensBefore: state.snapshotTokens ?? ctx.getContextUsage()?.tokens ?? 0,\n },\n retainedMessages: retainedMessagesAfterSnapshot(branch, state.snapshotLeafId),\n };\n\n notify(ctx, `Doom autocompact pass ${pass} context commit started.`);\n const committedWhileIdle = ctx.isIdle();\n pi.sendMessage({ customType: CONTEXT_MESSAGE_TYPE, content: summary, display: false, details });\n const contextMessageLeafId = workingLeafId(ctx);\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, branch, runtimeAttributes);\n // Mid-run the marker is queued as a steering message, so its entry id is not resolvable yet.\n if (committedWhileIdle) pi.setLabel(contextMessageLeafId, `autocompact:c${cycle}:p${pass}`);\n\n state.readFiles = fileDetails.readFiles;\n state.modifiedFiles = fileDetails.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n state.phase = STATE_PHASE.waiting;\n state.checkpointQueue = [];\n // A compacted context is a fresh ladder: passes abandoned in the previous cycle are eligible again.\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n state.baselinePending = true;\n delete state.lastAttemptLeafId;\n clearPendingCheckpoint();\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextCommitted,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': details.doomAutocompact.snapshotLeafId,\n 'autocompact.tokens_before': details.doomAutocompact.tokensBefore,\n 'autocompact.message_count.before': projected.length,\n 'autocompact.message_count.retained': details.retainedMessages.length,\n 'autocompact.apply_mode': committedWhileIdle ? 'idle' : 'turn_end',\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n notify(ctx, `Doom autocompact context committed. Baseline will be captured from the next settled context.`);\n // A mid-run commit needs no resume steer: the agent is already continuing.\n if (committedWhileIdle) resumeAgent('Asynchronous compaction completed.');\n return true;\n };\n\n const requestCheckpoint = (pass: AutocompactPass, ctx: ExtensionContext, tokensBefore: number): void => {\n if (!active) return;\n const generation = sessionGeneration;\n const branch = ctx.sessionManager.getBranch();\n const snapshotLeafId = workingLeafId(ctx);\n const requestId = createRequestId(ctx.sessionManager.getSessionId(), state.cycle, pass, snapshotLeafId);\n const previousCheckpoint = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(branch)) : undefined;\n const messages = messagesForCheckpoint(pass, branch, state.latestCheckpointSnapshotLeafId);\n const taskSnapshot = readTaskSnapshot(ctx);\n const teamSnapshot = readTeamSnapshot();\n const attributes = telemetryAttributes(ctx, {\n 'autocompact.request.id': requestId,\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.snapshot_leaf_id': snapshotLeafId,\n 'autocompact.tokens_before': tokensBefore,\n 'autocompact.message_count.before': messages.length,\n });\n reportSnapshotFailures(ctx, taskSnapshot, teamSnapshot, attributes);\n\n state.phase = STATE_PHASE.checkpointPending;\n state.pass = pass;\n state.requestId = requestId;\n state.snapshotLeafId = snapshotLeafId;\n state.snapshotTokens = tokensBefore;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n delete state.lastAttemptLeafId;\n persist();\n\n checkpointController?.abort();\n checkpointController = new AbortController();\n const checkpointSignal = checkpointController.signal;\n notify(ctx, `Doom autocompact summarization pass ${pass} started.`);\n const operation = telemetry\n .runInSpan('doom_autocompact.checkpoint', attributes, async () => {\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, attributes);\n try {\n const checkpoint = await generateCheckpoint({\n messages,\n instructions: checkpointInstructions(pass, {\n plan: latestPlanSnapshot(branch),\n taskSnapshot,\n teamSnapshot,\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n }),\n ...(previousCheckpoint ? { previousCheckpoint } : {}),\n context: ctx,\n signal: checkpointSignal,\n });\n if (!active || generation !== sessionGeneration) {\n throw checkpointSignal.reason ?? new Error('Autocompact checkpoint became stale.');\n }\n if (!checkpoint.trim()) throw new Error('Summarization returned an empty checkpoint.');\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {\n ...attributes,\n 'autocompact.checkpoint.characters': checkpoint.length,\n });\n return checkpoint;\n } catch (error) {\n if (active && generation === sessionGeneration) {\n await telemetry.recordError(AUTOCOMPACT_EVENT.checkpointFailed, error, attributes);\n }\n throw error;\n }\n })\n .then((checkpoint) => {\n if (\n !active ||\n generation !== sessionGeneration ||\n requestId !== state.requestId ||\n state.phase !== STATE_PHASE.checkpointPending\n ) {\n return;\n }\n state.phase = STATE_PHASE.checkpointReady;\n state.pendingCheckpoint = checkpoint.trim();\n persist();\n notify(currentContext, `Doom autocompact summarization pass ${pass} completed.`);\n if (currentContext) processProgress(currentContext);\n })\n .catch((error: unknown) => {\n if (active && generation === sessionGeneration) failCheckpoint(requestId, error);\n });\n checkpointWork.add(operation);\n void operation.finally(() => checkpointWork.delete(operation));\n };\n\n const evaluateUsage = (ctx: ExtensionContext): boolean => {\n if (!active || state.phase !== STATE_PHASE.waiting || ctx.hasPendingMessages()) return false;\n const usage = ctx.getContextUsage();\n if (!usage || usage.tokens === null) return false;\n if (state.baselinePending) {\n // Reported usage still describes the pre-compaction context until an assistant\n // responds against the projected one, and capturing it early poisons every threshold.\n if (!baselineUsageIsSettled(ctx.sessionManager.getBranch())) return false;\n state.baselineTokens = usage.tokens;\n state.baselinePending = false;\n persist();\n notify(ctx, `Doom autocompact baseline captured at ${state.baselineTokens} tokens.`);\n return false;\n }\n const leafId = workingLeafId(ctx);\n if (state.lastAttemptLeafId === leafId) return false;\n\n for (const pass of [1, 2, 3] as const) {\n if (pass < state.pass || state.checkpointQueue.includes(pass) || state.exhaustedPasses.includes(pass)) continue;\n if (usage.tokens >= thresholdTokens(pass, usage.contextWindow, state.baselineTokens)) {\n state.checkpointQueue.push(pass);\n }\n }\n const nextPass = state.checkpointQueue[0];\n if (!nextPass) return false;\n requestCheckpoint(nextPass, ctx, usage.tokens);\n return true;\n };\n\n // Staged checkpoints seed the next summarization pass only. They are appended as plain\n // session entries so they never enter the agent's LLM context: delivering them as messages\n // reads like a user instruction and derails the run (\"Checkpoint acknowledged...\").\n const stageCheckpoint = (pass: 1 | 2, summary: string): void => {\n if (!active) return;\n const checkpointSnapshotLeafId = state.snapshotLeafId;\n pi.appendEntry(CHECKPOINT_MESSAGE_TYPE, {\n ...checkpointRequestDetails(state.cycle, pass, state.requestId ?? 'completed'),\n summary,\n });\n if (checkpointSnapshotLeafId) state.latestCheckpointSnapshotLeafId = checkpointSnapshotLeafId;\n };\n\n const captureReadyCheckpoint = (ctx: ExtensionContext): CheckpointCapture => {\n if (!active || state.phase !== STATE_PHASE.checkpointReady || !state.requestId || !state.pendingCheckpoint) {\n return 'none';\n }\n const pass = state.pass;\n const decision = parseCheckpointDecision(state.pendingCheckpoint);\n if (!isStructuredCheckpoint(decision.summary)) {\n const failedLeafId = state.snapshotLeafId;\n const invalidRequestId = state.requestId;\n // A queued pass is retried once per new leaf, so an output the summarizer never formats\n // correctly would otherwise burn a full summarization call every turn for the session.\n const attempts = state.invalidAttempts + 1;\n const exhausted = attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS;\n state.phase = STATE_PHASE.waiting;\n if (failedLeafId) state.lastAttemptLeafId = failedLeafId;\n if (exhausted) {\n completeQueuedPass(pass);\n state.exhaustedPasses = [...state.exhaustedPasses, pass];\n state.invalidAttempts = 0;\n } else {\n state.invalidAttempts = attempts;\n }\n clearPendingCheckpoint();\n persist();\n const error = new Error(`Summarization pass ${pass} returned an incomplete checkpoint.`);\n notify(\n ctx,\n exhausted\n ? `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint ${attempts} times and was abandoned.`\n : `Doom autocompact summarization pass ${pass} returned an incomplete checkpoint.`,\n 'error',\n );\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.checkpointInvalid,\n error,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': pass,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': exhausted,\n ...(invalidRequestId ? { 'autocompact.request.id': invalidRequestId } : {}),\n }),\n );\n return 'invalid';\n }\n\n state.invalidAttempts = 0;\n\n if (pass === 1) {\n stageCheckpoint(1, decision.summary);\n completeQueuedPass(1);\n state.phase = STATE_PHASE.waiting;\n state.pass = 2;\n clearPendingCheckpoint();\n persist();\n return 'pass1';\n }\n\n if (pass === 2 && decision.shouldCompact !== true) {\n stageCheckpoint(2, decision.summary);\n completeQueuedPass(2);\n state.phase = STATE_PHASE.waiting;\n state.pass = 3;\n clearPendingCheckpoint();\n persist();\n return 'deferred';\n }\n\n state.pendingCheckpoint = decision.summary;\n return commitCheckpoint(pass, ctx) ? 'committed' : 'invalid';\n };\n\n function processProgress(ctx: ExtensionContext): void {\n if (!active) return;\n currentContext = ctx;\n if (!ctx.isIdle()) return;\n if (captureReadyCheckpoint(ctx) !== 'committed') evaluateUsage(ctx);\n }\n\n pi.on('context', (event, ctx) => {\n if (!active) return undefined;\n const projection = projectContextMessages(event.messages, ctx.sessionManager.getBranch());\n if (projection.invalidMarker) {\n const leafId = ctx.sessionManager.getLeafId() ?? ROOT_WORKING_LEAF;\n if (!invalidContextLeaves.has(leafId)) {\n invalidContextLeaves.add(leafId);\n void telemetry.recordError(\n AUTOCOMPACT_EVENT.contextMarkerInvalid,\n new Error('Doom autocompact context marker is malformed.'),\n telemetryAttributes(ctx, { 'autocompact.leaf_id': leafId }),\n );\n }\n return undefined;\n }\n if (!projection.marker) return undefined;\n if (!appliedContextRequests.has(projection.marker.requestId)) {\n appliedContextRequests.add(projection.marker.requestId);\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.contextApplied,\n telemetryAttributes(ctx, {\n 'autocompact.request.id': projection.marker.requestId,\n 'autocompact.cycle': projection.marker.cycle,\n 'autocompact.pass': projection.marker.pass,\n 'autocompact.snapshot_leaf_id': projection.marker.snapshotLeafId,\n 'autocompact.tokens_before': projection.marker.tokensBefore,\n 'autocompact.message_count.before': event.messages.length,\n 'autocompact.message_count.after': projection.messages.length,\n 'autocompact.message_count.retained': projection.retainedMessageCount,\n }),\n );\n }\n return { messages: projection.messages };\n });\n\n const beginSessionGeneration = (ctx: ExtensionContext): void => {\n if (!active) return;\n sessionGeneration += 1;\n checkpointController?.abort(new Error('Autocompact session generation was replaced.'));\n checkpointController = undefined;\n appliedContextRequests.clear();\n invalidContextLeaves.clear();\n currentContext = ctx;\n restore(ctx);\n processProgress(ctx);\n };\n\n pi.on('session_start', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('session_tree', (_event, ctx) => beginSessionGeneration(ctx));\n\n pi.on('turn_end', (event, ctx) => {\n if (!active) return;\n currentContext = ctx;\n if (ctx.isIdle()) {\n processProgress(ctx);\n return;\n }\n // A ready checkpoint must be applied without waiting for the run to finish, otherwise\n // context keeps growing past the window for the rest of a long autonomous run. Tool\n // results confirm the run continues, so the queued marker lands before the next request.\n const canApplyDuringRun =\n state.phase === STATE_PHASE.checkpointReady && (event.toolResults?.length ?? 0) > 0 && !ctx.hasPendingMessages();\n if (canApplyDuringRun && captureReadyCheckpoint(ctx) !== 'none') return;\n evaluateUsage(ctx);\n });\n\n pi.on('agent_settled', (_event, ctx) => {\n if (!active) return;\n processProgress(ctx);\n });\n\n pi.on('session_before_compact', (event) => {\n if (!active || event.reason !== 'threshold') return undefined;\n // Native compaction stays cancelled while our own machinery is working, and stays\n // available as the emergency backstop once that machinery has stalled or declined.\n const machineryActive =\n state.phase === STATE_PHASE.checkpointPending ||\n state.phase === STATE_PHASE.checkpointReady ||\n state.baselinePending;\n return machineryActive ? { cancel: true } : undefined;\n });\n\n pi.on('session_compact', (event, ctx) => {\n if (!active) return;\n sessionGeneration += 1;\n // Native compaction supersedes any summarization still in flight.\n checkpointController?.abort();\n checkpointController = undefined;\n const eventDetails = fileDetailsFromUnknown(event.compactionEntry.details);\n const cumulative = mergeFileDetails(state, undefined, eventDetails);\n state.readFiles = cumulative.readFiles;\n state.modifiedFiles = cumulative.modifiedFiles;\n delete state.latestCheckpointSnapshotLeafId;\n // Reported usage still describes the pre-compaction context here too, so the baseline\n // waits for the first assistant response measured against the compacted one.\n state.baselinePending = true;\n state.phase = STATE_PHASE.waiting;\n clearPendingCheckpoint();\n state.checkpointQueue = [];\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n delete state.lastAttemptLeafId;\n\n pi.setLabel(event.compactionEntry.id, `autocompact:c${state.cycle}:external`);\n const completedCycle = state.cycle;\n const runtimeAttributes = telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n });\n const runtimeSnapshot = preserveRuntimeState(ctx, ctx.sessionManager.getBranch(), runtimeAttributes);\n state.cycle += 1;\n state.pass = 1;\n persist();\n void telemetry.recordEvent(\n AUTOCOMPACT_EVENT.nativeCompactionCompleted,\n telemetryAttributes(ctx, {\n 'autocompact.cycle': completedCycle,\n 'autocompact.native.reason': event.reason,\n 'autocompact.native.from_extension': event.fromExtension,\n 'autocompact.tokens_before': event.compactionEntry.tokensBefore,\n ...runtimeTelemetryAttributes(runtimeSnapshot),\n }),\n );\n notify(\n ctx,\n `Doom autocompact completed. Baseline will be captured from the next settled context. Next pass: ${state.pass}.`,\n );\n });\n}\n\n/** The package's single standard Pi factory. */\nexport async function autocompactExtension(pi: ExtensionAPI): Promise<void> {\n const connection = await connectDoomCordisHost(pi, PACKAGE_SOURCE);\n const fiber = connection.root.plugin(autocompactPlugin, { pi });\n try {\n await fiber;\n } catch (error) {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n throw error;\n }\n let disposal: Promise<void> | undefined;\n pi.on(\n 'session_shutdown',\n () =>\n (disposal ??= (async () => {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n })()),\n );\n}\n\ninterface AutocompactPluginConfig {\n readonly pi: ExtensionAPI;\n}\n\nfunction autocompactPlugin(cordis: Context, config: AutocompactPluginConfig): void {\n installAutocompactRuntime(cordis, config.pi);\n}\n\nexport default autocompactExtension;\n"],"mappings":"wnDAwDA,MAAM,EAAoB,QAGpB,EAAgB,mBAGhB,EAAc,CAClB,QAAS,UACT,kBAAmB,qBACnB,gBAAiB,mBACjB,WAAY,aACb,CAwED,SAAS,EACP,EACA,EAAyC,EAAE,CACf,CAC5B,MAAO,CACL,gBAAiB,EAAQ,eAAe,cAAc,CACtD,GAAG,EACJ,CAGH,SAAS,GAA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CACR,MAAM,EAAW,SAAS,KAE1B,CACP,CAOH,SAAS,EAAkB,EAAiB,EAAuC,CACjF,EAA0B,EAAQ,EAAO,GAAG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/doompi-autocompact",
3
- "version": "0.0.1-alpha.24",
3
+ "version": "0.0.1-alpha.26",
4
4
  "description": "Iterative context compaction and checkpoint summaries for Pi and DoomPi agent sessions.",
5
5
  "keywords": [
6
6
  "ai",
@@ -42,11 +42,11 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@deepseek-ai/cordis": "4.0.1",
45
- "@agimon-ai/doompi-config": "0.0.1-alpha.24",
46
- "@agimon-ai/doompi-task": "0.0.1-alpha.24",
47
- "@agimon-ai/doompi-telemetry": "0.0.1-alpha.24",
48
- "@agimon-ai/doompi-team": "0.0.1-alpha.24",
49
- "@agimon-ai/doompi-ui": "0.0.1-alpha.24"
45
+ "@agimon-ai/doompi-task": "0.0.1-alpha.26",
46
+ "@agimon-ai/doompi-extension-contracts": "0.0.1-alpha.26",
47
+ "@agimon-ai/doompi-telemetry": "0.0.1-alpha.26",
48
+ "@agimon-ai/doompi-team": "0.0.1-alpha.26",
49
+ "@agimon-ai/doompi-config": "0.0.1-alpha.26"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@earendil-works/pi-coding-agent": "0.84.2",