pi-tuck 1.1.0 → 1.1.2

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/src/run.ts CHANGED
@@ -75,18 +75,53 @@ export class StartingPrompt {
75
75
  }
76
76
  }
77
77
 
78
- export interface Run {
79
- phase: 'decided' | 'starting' | 'admitted' | 'failed';
80
- claimed: boolean;
81
- expired: boolean;
78
+ export type RunPhase = 'decided' | 'claimed' | 'expired' | 'starting' | 'admitted' | 'failed' | 'commit-failed';
79
+ /** Claim/expiry describe the input plan; a failed attempt cannot re-enter a live phase. */
80
+ export const RUN_TRANSITIONS: Readonly<Record<RunPhase, readonly RunPhase[]>> = {
81
+ decided: ['claimed', 'expired', 'starting', 'failed', 'commit-failed'],
82
+ claimed: ['claimed', 'starting', 'failed', 'commit-failed'],
83
+ expired: ['starting', 'failed', 'commit-failed'],
84
+ starting: ['admitted', 'failed', 'commit-failed'],
85
+ admitted: ['admitted', 'failed', 'commit-failed'],
86
+ failed: ['failed', 'commit-failed'],
87
+ 'commit-failed': ['commit-failed'],
88
+ };
89
+ let reportedInvalidTransition = false;
90
+ type RunState = { phase: Exclude<RunPhase, 'failed' | 'commit-failed'> } | { phase: 'failed' | 'commit-failed'; error: Error };
91
+
92
+ export class Run {
93
+ private state: RunState;
94
+ // Input-plan provenance survives starting/admission: later native threshold
95
+ // checks still choose the live view when the original input plan expired.
96
+ private expiredPlan = false;
97
+ constructor(phase: Exclude<RunPhase, 'failed' | 'commit-failed'>) { this.state = { phase }; }
98
+ get phase() { return this.state.phase; }
99
+ get expired() { return this.expiredPlan; }
100
+ /** Failure data, only present in a failed phase. The phase alone decides admission. */
101
+ get error() { return 'error' in this.state ? this.state.error : undefined; }
102
+ transition(phase: RunPhase, ctx?: Pick<ExtensionContext, 'hasUI'>, error?: Error): boolean {
103
+ if (!RUN_TRANSITIONS[this.phase].includes(phase) || ((phase === 'failed' || phase === 'commit-failed') && !error)) {
104
+ const message = `pi-tuck: invalid run transition ${this.phase} -> ${phase}`;
105
+ if (process.env.NODE_ENV === 'test') throw new Error(message);
106
+ if (ctx?.hasUI === false && !reportedInvalidTransition) {
107
+ reportedInvalidTransition = true;
108
+ try { process.stderr.write(message + '\n'); } catch { /* ended */ }
109
+ }
110
+ return false;
111
+ }
112
+ this.state = phase === 'failed' || phase === 'commit-failed' ? { phase, error: error! } : { phase };
113
+ if (phase === 'expired') this.expiredPlan = true;
114
+ return true;
115
+ }
82
116
  prompt?: StartingPrompt;
83
- cut: PendingCut;
84
- clips: Map<string, Clip>;
85
- pendingBoundaryCommit: boolean;
86
- pendingBoundaryReceipts: string[];
87
- thinkingRetryPending: boolean;
88
- failure?: Error;
89
- refusalReceipted: boolean;
117
+ cut = new PendingCut();
118
+ clips = new Map<string, Clip>();
119
+ pendingBoundaryReceipts: string[] = [];
120
+ thinkingRetryPending = false;
121
+ refusalReceipted = false;
122
+ clear() {
123
+ this.prompt = undefined; this.cut.clear(); this.clips.clear(); this.pendingBoundaryReceipts = [];
124
+ this.thinkingRetryPending = false; this.refusalReceipted = false; this.expiredPlan = false;
125
+ }
90
126
  }
91
- export const createRun = (phase: Run['phase']): Run => ({ phase, claimed: false, expired: false,
92
- cut: new PendingCut(), clips: new Map(), pendingBoundaryCommit: false, pendingBoundaryReceipts: [], thinkingRetryPending: false, refusalReceipted: false });
127
+ export const createRun = (phase: ConstructorParameters<typeof Run>[0]): Run => new Run(phase);
@@ -140,6 +140,18 @@ export function healDelayMs(attempts:number,integrity:boolean,delays:readonly nu
140
140
  const CHURN=/indexing incomplete|history changed|source changed before|branch or source changed|cancelled/i;
141
141
  export type SemanticState='disabled'|'unavailable'|'preparing'|'ready'|'waiting';
142
142
  export type SemanticSetup = 'off-settings' | 'off-user' | 'not-installed' | 'off-platform' | 'off-project' | 'starting' | 'failed' | 'ready';
143
+ const OFF_SETUP: readonly SemanticSetup[] = ['off-settings', 'off-user', 'off-platform', 'off-project'];
144
+ /** Host policy is re-evaluated at session start; only a start may publish ready. */
145
+ export const SEMANTIC_SETUP_TRANSITIONS: Readonly<Record<SemanticSetup, readonly SemanticSetup[]>> = {
146
+ 'off-settings': OFF_SETUP,
147
+ 'off-user': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
148
+ 'off-platform': [...OFF_SETUP, 'not-installed', 'starting'],
149
+ 'off-project': [...OFF_SETUP, 'not-installed', 'starting'],
150
+ 'not-installed': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
151
+ starting: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
152
+ failed: [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
153
+ ready: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
154
+ };
143
155
  interface SetupDetail { installed?: boolean; reason?: string; stage?: 'setup' | 'start'; notice?: string; announced?: boolean }
144
156
  /** Setup and operator wording have one owner; runtime indexing state remains separate. */
145
157
  export function semanticSetupMessage(setup: SemanticSetup, detail: SetupDetail = {}): string | null {
@@ -283,7 +295,11 @@ export class SemanticRecallController {
283
295
  // The fields below decide `status().state`; their setters announce a change to `onStateChange` listeners.
284
296
  private setup: SemanticSetup = 'off-user'; private setupDetail: SetupDetail = {};
285
297
  private _enabled=false;private _current?:Snapshot;private _task?:Promise<void>;private _timer?:ReturnType<typeof setTimeout>;private _error:string|null=null;
286
- private get enabled(){return this._enabled;}private set enabled(value:boolean){this._enabled=value;this.touch();}
298
+ private get enabled(){return this._enabled;}private set enabled(value:boolean){
299
+ this._enabled=value;
300
+ if(!value&&this.setup==='ready'){const reason=this.error??this.cleanupError;this.setSetup(reason?'failed':'off-user',reason?{stage:'start',reason}:{});}
301
+ this.touch();
302
+ }
287
303
  private get current(){return this._current;}private set current(value:Snapshot|undefined){this._current=value;this.touch();}
288
304
  private get task(){return this._task;}private set task(value:Promise<void>|undefined){this._task=value;this.touch();}
289
305
  private get timer(){return this._timer;}private set timer(value:ReturnType<typeof setTimeout>|undefined){this._timer=value;this.touch();}
@@ -303,7 +319,10 @@ export class SemanticRecallController {
303
319
  onStateChange(listener:(state:SemanticState,reason:string|null)=>void):()=>void{this.listeners.add(listener);return()=>{this.listeners.delete(listener);};}
304
320
  private touch(){if(this.announcing)return;this.announcing=true;queueMicrotask(()=>{this.announcing=false;const {state,lastError}=this.status(),key=state+'\0'+(lastError??'');if(key===this.announced)return;this.announced=key;for(const listener of [...this.listeners])try{listener(state,lastError);}catch{}});}
305
321
  /** A host that could not configure the runtime records why a requested start failed. The controller stays disabled and `lastError` carries the reason until the next `enable`. */
306
- setSetup(setup: SemanticSetup, detail: SetupDetail = {}) { const announced = setup === 'ready' && this.setupDetail.announced; this.setup = setup; this.setupDetail = announced ? { ...detail, announced: true } : detail; this.touch(); }
322
+ setSetup(setup: SemanticSetup, detail: SetupDetail = {}) {
323
+ if(!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes(setup))return;
324
+ const announced = setup === 'ready' && this.setupDetail.announced; this.setup = setup; this.setupDetail = announced ? { ...detail, announced: true } : detail; this.touch();
325
+ }
307
326
  /** Compatibility for hosts that already record an external start failure. */
308
327
  refuse(reason:string){this.setSetup('failed', { stage: 'start', reason });}
309
328
  setupNotice(){return semanticSetupNotice(this.setup, this.setupDetail);}
@@ -312,7 +331,13 @@ export class SemanticRecallController {
312
331
  * optional override is a current-process verified dependency, not Task data. */
313
332
  async configureExternal(project:string,selectedPath=runtimeConfigPath(defaultRoot()),runtime?:{nativeOwnerHelperPath?:string}){const path=resolve(selectedPath);outsideProject(project,path,'configuration');if(runtime?.nativeOwnerHelperPath!==undefined)outsideProject(project,runtime.nativeOwnerHelperPath,'runtime');const text=await readFile(path,'utf8').catch((error:NodeJS.ErrnoException)=>{throw error.code==='ENOENT'?new Error('Semantic recall is not set up yet: pi-tuck sets it up when a session starts, unless pi-tuck.json turns it off'):error;});
314
333
  this.configure({...JSON.parse(text) as SemanticRecallConfig,...(runtime?.nativeOwnerHelperPath===undefined?{}:{nativeOwnerHelperPath:runtime.nativeOwnerHelperPath})});}
315
- enable(){if(this.closing||this.joiningSearches||this.cleanupError)throw new Error('Semantic cleanup is unresolved; retry close before enable');if(!this.config)throw new Error('Optional local semantic runtime is not configured');this.setSetup('ready');this.enabled=true;this.error=null;this.healReason=null;this.healAttempts=0;this.cancelHeal();if(this.provider&&this.active)this.schedule(this.provider);}
334
+ enable(){
335
+ // Explicit opt-in can end off-user; project, platform and settings policy belongs to the host.
336
+ if(['off-user','not-installed','failed'].includes(this.setup))this.setSetup('starting');
337
+ if(!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes('ready'))return;
338
+ try{if(this.closing||this.joiningSearches||this.cleanupError)throw new Error('Semantic cleanup is unresolved; retry close before enable');if(!this.config)throw new Error('Optional local semantic runtime is not configured');this.setSetup('ready');this.enabled=true;this.error=null;this.healReason=null;this.healAttempts=0;this.cancelHeal();if(this.provider&&this.active)this.schedule(this.provider);}
339
+ catch(error){this.setSetup('failed',{stage:'start',reason:error instanceof Error?error.message:String(error)});throw error;}
340
+ }
316
341
  status(){return{setup:this.setup,setupMessage:semanticSetupMessage(this.setup,this.setupDetail),enabled:this.enabled,configured:Boolean(this.config),cleanupError:this.cleanupError,state:(!this.enabled?'disabled':this.healReason!==null||(this.error!==null&&!CHURN.test(this.error))?'unavailable':this.task||this.timer?'preparing':this.current?.complete?'ready':'waiting') as SemanticState,snapshotId:this.current?.id??null,throughEntryId:this.current?.throughEntryId??null,eligibleSources:this.current?.sources.length??0,totalUnits:this.current?.units.length??0,coveredUnits:this.current?.indexed.size??0,indexingComplete:Boolean(this.current?.complete),lastError:this.error??this.healReason??semanticSetupMessage(this.setup,this.setupDetail),window:this.current?windowCoverage(this.current):null,recovery:this.healReason===null?null:{attempts:this.healAttempts,integrity:this.healIntegrity,retryAt:this.healRetryAt===null?null:new Date(this.healRetryAt).toISOString()},operations:{...this.operations},limits:{keyword:16000,broad:20000}};}
317
342
  /** The existing model-facing coverage contract: setup metadata belongs to operator status, not the request. */
318
343
  requestCoverage(){const {setup,setupMessage,...coverage}=this.status();return coverage;}
package/src/status.ts CHANGED
@@ -15,6 +15,7 @@ export const LOADED_VERSION: string = (() => {
15
15
  export function statusText(input: {
16
16
  version: string;
17
17
  active: boolean;
18
+ compaction?: import('./compaction').CompactionState;
18
19
  branch: readonly { type: string; tokensBefore?: unknown; details?: unknown; customType?: unknown; data?: unknown }[];
19
20
  pending?: boolean;
20
21
  cutAt: number | undefined;
@@ -22,6 +23,7 @@ export function statusText(input: {
22
23
  semantic: { state: SemanticState; lastError: string | null };
23
24
  }): string {
24
25
  if (!input.active) return `pi-tuck ${input.version} is loaded but inactive in this host; Pi's own compaction runs.`;
26
+ if (input.compaction?.kind === 'standingDown') return `pi-tuck ${input.version}: standing down: ${input.compaction.reason}; Pi's own compaction runs.`;
25
27
  const cuts = input.branch.filter(e => e.type === "compaction"), ours = cuts.filter(e => (e.details as { compactor?: unknown } | null | undefined)?.compactor === "pi-tuck");
26
28
  const last = ours.at(-1), before = last?.tokensBefore, after = (last?.details as { tokensAfter?: unknown } | undefined)?.tokensAfter;
27
29
  const count = (n: number) => n.toLocaleString("en-US");