@devflow-tools/cli 0.16.14 → 0.16.16

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.
@@ -1,4 +1,4 @@
1
- import {getLocalApiKey,getProjectStateDir,resolveRuntimeEndpoint,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure}from'@devflow-tools/sdk';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {MemoryGate}from'@devflow-tools/memory-engine';import {existsSync as existsSync$1,readFileSync,rmSync as rmSync$1,mkdirSync as mkdirSync$1,writeFileSync as writeFileSync$1,linkSync,readdirSync,renameSync as renameSync$1,unlinkSync as unlinkSync$1}from'fs';import {join as join$1}from'path';import {homedir as homedir$1}from'os';import {request}from'node:http';import {mkdirSync,existsSync,writeFileSync,renameSync,unlinkSync,rmSync,lstatSync,openSync,constants,fstatSync,readSync,closeSync,appendFileSync}from'node:fs';import {join}from'node:path';import {homedir}from'node:os';import {createHash}from'node:crypto';import {randomUUID,createHash as createHash$1}from'crypto';function M(o){return o??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function _(o){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(M(o))}function N(o,t,e){try{let n=openGlobalDevFlowDatabase();try{n.insertEvent({kind:o,timestamp:Date.now(),duration:e,success:t.success!==!1,metadata:t});}finally{n.close();}}catch{}}var $e=getLocalApiKey(),q=join(homedir(),".devflow","errors");async function O(o,t,e={}){let n=e.endpoint??resolveRuntimeEndpoint().url,r=e.timeout??1500,i=e.durableMirror??true,s=e.maxRetries??(i?0:2),a=e.circuitBreaker??true,l=acquireRuntimeHttpCircuit(n,o);if(a&&!l.allowed)return {delivered:false,suppressed:true,fallbackReason:l.state.fallbackReason};let u;for(let g=0;g<=s;g+=1)try{return await Pe(n,o,t,r),a&&registerRuntimeHttpSuccess(n,o).transitioned&&N("http_circuit_transition",{endpoint:n,path:new URL(o,n).pathname,previous:l.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(f){u=f instanceof Error?f:new Error(String(f)),g<s&&await Me(Math.min(100*2**g,1e3));}if(!u)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return X(o,u),{delivered:false,suppressed:false,fallbackReason:u.message};let p=registerRuntimeHttpFailure(n,o,e.fallbackReason??(i?"local_durable_mirror":"http_delivery_failed"));return p.transitioned&&(X(o,u),N("http_circuit_transition",{endpoint:n,path:new URL(o,n).pathname,previous:l.state.status,status:"open",failures:p.state.failures,openUntil:p.state.openUntil,fallbackReason:p.state.fallbackReason})),{delivered:false,suppressed:false,fallbackReason:p.state.fallbackReason}}function Pe(o,t,e,n){return new Promise((r,i)=>{let s=JSON.stringify(e),a=new URL(t,o),l=false,u=g=>{l||(l=true,g?i(g):r());},p=request({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":$e,"Content-Length":Buffer.byteLength(s)},timeout:n},g=>{g.on("error",u),g.on("end",()=>{let f=g.statusCode??0;u(f>=200&&f<300?void 0:new Error(`HTTP ${f}`));}),g.resume();});p.on("error",u),p.on("timeout",()=>p.destroy(new Error(`HTTP mirror timed out after ${n}ms`))),p.write(s),p.end();})}function X(o,t){try{existsSync(q)||mkdirSync(q,{recursive:!0}),appendFileSync(join(q,"http-errors.log"),`${new Date().toISOString()} | ${o} | ${t.message}
2
- `);}catch{}}function Me(o){return new Promise(t=>setTimeout(t,o))}var ne=1e4,Ne=3e4,F=500,z=class{constructor(t){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=t?.apiUrl,this.cacheDir=t?.cacheDir??join$1(process.env.DEVFLOW_STATE_DIR??join$1(homedir$1(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=t?.legacyCacheDir??(t?.cacheDir?null:join$1(homedir$1(),".devflow","telemetry-cache")),this.database=t?.database??null,this.ownsDatabase=!t?.database;let e=t?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(e)&&e>=0?e:100;}async sendEvent(t){let e={...t,input:this.truncateInput(t.input)};return this.commitOrCache("tool_call",e)?(this.postHttp("/api/telemetry/tool-call",e),t.eventId):null}async sendExecutionStart(t,e,n,r,i=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:t,sessionId:e,skillName:n,startedAt:r,projectRoot:i,requiredMcpTools:s};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(t,e="completed",n=Date.now(),r){let i={executionId:t,status:e,finishedAt:n,metadata:r},s=this.commitOrCache("execution_complete",i);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",i),s}async sendSessionStart(t,e,n){let r={id:t,projectRoot:e,startedAt:n,label:e.split("/").pop()??"unknown"},i=this.commitOrCache("session_start",r);return i&&this.postHttp("/api/telemetry/sessions",r),i}async completeEvent(t){let e=this.commitOrCache("complete_event",t);return e&&(this.postHttp("/api/telemetry/tool-call/output",t),this.scheduleMetricAggregation()),e}async endSession(t,e=Date.now()){let n={sessionId:t,finishedAt:e},r=this.commitOrCache("session_end",n);return r&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:e})),r}async flushCache(){try{let n=this.getDatabase(),r=n.listTelemetryFailures({unresolvedOnly:!0,limit:F}).reverse();for(let i of r)try{this.applyOperation(i.operation,i.payload),n.resolveTelemetryFailure(i.id);}catch{}n.trimTelemetryFailures(F);}catch{}let e=[...new Set([this.cacheDir,this.legacyCacheDir].filter(n=>!!n))].filter(n=>existsSync$1(n)).flatMap(n=>readdirSync(n).filter(r=>r.endsWith(".json")).map(r=>{let i=join$1(n,r);try{return {cacheFile:i,envelope:qe(JSON.parse(readFileSync(i,"utf8")),r)}}catch{return null}})).filter(n=>n!==null).sort((n,r)=>n.envelope.timestamp-r.envelope.timestamp||ie(n.envelope.operation)-ie(r.envelope.operation));for(let{cacheFile:n,envelope:r}of e)try{let i=this.getDatabase();i.insertTelemetryFailure({id:r.id,operation:r.operation,payload:r.payload,error:r.failure,createdAt:r.timestamp}),this.applyOperation(r.operation,r.payload),i.resolveTelemetryFailure(r.id),unlinkSync$1(n);}catch{}this.database?.aggregatePendingToolMetrics();}aggregateMetrics(){return this.getDatabase().aggregatePendingToolMetrics()}async flushAndAggregate(){await this.flushCache(),this.aggregateMetrics();}close(){this.ownsDatabase&&this.database?.close(),this.database=null;}getDatabase(){return this.database??=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:this.busyTimeoutMs}),this.database}commitOrCache(t,e){try{return this.applyOperation(t,e),!0}catch(n){return this.cacheOperation(t,e,n),false}}applyOperation(t,e){let n=this.getDatabase();switch(t){case "tool_call":this.ensureParentSession(n,e),n.insertToolCallEvent(e);return;case "execution_start":this.ensureParentSession(n,e),n.insertSkillExecution({executionId:e.executionId,sessionId:e.sessionId,skillName:e.skillName,startedAt:e.startedAt,status:"running",requiredMcpTools:e.requiredMcpTools});return;case "execution_complete":n.reconcileSkillExecution(e.executionId,e.status,e.finishedAt,e.metadata);return;case "session_start":n.ensureSession(e),n.insertRun({id:re(e.id),source:"hook",tool:"session",input:{projectRoot:e.projectRoot},status:"active",startedAt:e.startedAt,tokenUsed:0,metadata:{sessionId:e.id,projectRoot:e.projectRoot}});return;case "complete_event":if(!n.updateToolCallEvent(e.eventId,{output:e.output===void 0?void 0:JSON.stringify(e.output),error:e.error,failureCategory:e.failureCategory,duration:e.duration}))throw new Error(`Tool call event ${e.eventId} is not available for completion`);return;case "session_end":n.closeSession(e.sessionId,e.finishedAt),n.updateRun(re(e.sessionId),{status:"completed",finishedAt:e.finishedAt});return}}ensureParentSession(t,e){let n=typeof e.sessionId=="string"?e.sessionId.trim():"";if(!n)throw new Error("Canonical session ID is required for telemetry");let r=typeof e.projectRoot=="string"&&e.projectRoot.trim()?e.projectRoot:typeof e.input?.projectRoot=="string"&&e.input.projectRoot.trim()?e.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";t.ensureSession({id:n,projectRoot:r,label:r==="unknown"?void 0:r.split("/").pop(),startedAt:Number(e.startedAt??e.timestamp??Date.now())});}cacheOperation(t,e,n){let r=Date.now(),i={id:`failure:${r}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:e,failure:n instanceof Error?n.message:String(n),timestamp:r};try{let s=this.getDatabase();s.insertTelemetryFailure({id:i.id,operation:t,payload:e,error:i.failure,createdAt:r}),s.trimTelemetryFailures(F),this.scheduleRetry();return}catch{}try{existsSync$1(this.cacheDir)||mkdirSync$1(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${r}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync$1(s,JSON.stringify(i,null,2),{mode:384}),this.trimCompatibilityCache(),this.scheduleRetry();}catch{}}trimCompatibilityCache(){try{let t=readdirSync(this.cacheDir).filter(e=>e.endsWith(".json")).sort();for(let e of t.slice(0,Math.max(0,t.length-F)))unlinkSync$1(join$1(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},Ne).unref());}scheduleMetricAggregation(){if(this.metricAggregationScheduled||process.env.DEVFLOW_HOOK_DEGRADED==="1")return;this.metricAggregationScheduled=true,setTimeout(()=>{this.metricAggregationScheduled=false;try{this.getDatabase().aggregatePendingToolMetrics(50)===50&&this.scheduleMetricAggregation();}catch{}},25).unref();}postHttp(t,e){O(t,e,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=ne?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,ne)}...`}}};function ie(o){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(o)}function re(o){return `hook-run:${o}`}function qe(o,t){if(!o||typeof o!="object")throw new Error("Invalid telemetry cache envelope");let e=o;if(typeof e.operation=="string"&&e.payload!==void 0)return e;let n=e.type==="tool_call"?"tool_call":e.type==="execution_start"?"execution_start":null;if(!n)throw new Error("Unknown legacy telemetry cache operation");let r=e.payload??{},i=Number(r.timestamp??r.startedAt??Date.now());return {id:`legacy-cache:${t}`,operation:n,payload:r,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:i}}async function oe(o){let t=!o.memory,e=o.memory??new MemoryGate(o.projectRoot),n=0,r=0;try{await e.forceWarmUp(),o.trigger==="session_end"&&(n=await e.releasePendingDistillLeases(o.sessionId)),r=e.getPendingEventCount(o.sessionId,o.trigger!=="session_end");}finally{t&&e.close();}let i={pendingEvents:r,releasedLeases:n,trigger:o.trigger,sessionId:o.sessionId,details:o.details};try{let s=openGlobalDevFlowDatabase();try{let a=Date.now(),l=o.trigger==="session_end"&&o.sessionId?`distill:session_end:${createHash("sha256").update(`${o.projectRoot}\0${o.sessionId}`).digest("hex").slice(0,24)}`:`distill:${a}:${Math.random().toString(36).slice(2,10)}`;s.recordMemoryDistillCheckpoint({id:l,projectRoot:o.projectRoot,sessionId:o.sessionId,trigger:o.trigger,pendingEvents:r,releasedLeases:n,details:o.details,createdAt:a}),s.insertEvent({kind:"memory_distill_requested",timestamp:a,success:!0,metadata:{...i,projectRoot:o.projectRoot}});}finally{s.close();}}catch(s){throw s}return i}function le(o){return Buffer.from(o,"utf8").toString("base64url")}function Ve(o,t,e){let n=t?.trim();if(n){let r=/^[a-zA-Z0-9:._-]{1,192}$/.test(n)?n:`tool-${createHash$1("sha256").update(n.slice(0,1024)).digest("hex").slice(0,32)}`;return `${o}:${r}`}return `${o}:legacy-${e}-${randomUUID().slice(0,8)}`}function fe(o){return `${o}:legacy-journal`}var D=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(_(t),"hook-sessions");}registerSession(t){let e=t.trim();if(!e)throw new Error("session_id_required");let n=this.get(e);if(n)return n.lastActivityAt=Date.now(),this.persist(n),n;let r=Date.now(),i={sessionId:e,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:r,lastActivityAt:r};return this.sessions.set(e,i),this.persist(i),i}startExecution(t,e,n){let r=this.registerSession(t);return (!r.executionId||r.skillName!==e)&&(r.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),r.skillName=e,r.requiredMcpTools=[...new Set(n)],r.lastActivityAt=Date.now(),this.persist(r),r}get(t){let e=t.trim();if(!e)return null;let n=this.sessions.get(e);if(n)return this.replayEvidenceJournal(n),n;let r=this.snapshotPath(e);if(!existsSync$1(r))return null;try{let i=JSON.parse(readFileSync(r,"utf8"));return i.sessionId!==e||i.projectRoot!==this.projectRoot?null:(i.requiredMcpTools=Array.isArray(i.requiredMcpTools)?i.requiredMcpTools:[],i.evidenceObligations=de(i.evidenceObligations),i.evidenceDegradations=ue(i.evidenceDegradations),i.evidenceOutcomes=pe(i.evidenceOutcomes),this.replayEvidenceJournal(i),this.sessions.set(e,i),i)}catch{return null}}completeExecution(t){let e=this.get(t);if(!e)return null;let n=structuredClone(e);return delete e.executionId,delete e.skillName,e.requiredMcpTools=[],e.lastActivityAt=Date.now(),this.persist(e),n}addEvidenceObligation(t,e,n=Date.now(),r){let i=this.registerSession(t),a=(r?void 0:i.evidenceObligations.find(u=>u.contractId===e.id))?.obligationId??Ve(e.id,r,n);this.appendEvidenceEvent(t,{kind:"add",obligationId:a,contractId:e.id,at:n,contract:e},`add\0${a}`),this.replayEvidenceJournal(i);let l=i.evidenceObligations.find(u=>u.obligationId===a);return l?(i.lastActivityAt=Date.now(),this.persist(i),structuredClone(l)):null}listEvidenceObligations(t){return (this.get(t)?.evidenceObligations??[]).map(e=>structuredClone(e))}markEvidenceCorrection(t,e,n,r,i=Date.now()){let s=this.get(t),a=s?.evidenceObligations.find(p=>p.obligationId===e);if(!s||!a)return null;let l=/^[a-f0-9]{64}$/.test(r)?r:"";if(!l)return null;this.appendEvidenceEvent(t,{kind:"correction",obligationId:e,contractId:a.contractId,at:i,fingerprint:l,violations:n.slice(0,16).map(p=>p.slice(0,240))},`correction\0${e}\0${l}`),this.replayEvidenceJournal(s),s.lastActivityAt=i,this.persist(s);let u=s.evidenceObligations.find(p=>p.obligationId===e);return u?structuredClone(u):null}resolveEvidenceObligation(t,e){let n=this.get(t);if(!n)return false;let r=n.evidenceObligations.find(s=>s.obligationId===e);if(!r)return false;let i=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:r.contractId,at:i},`resolve\0${e}`),this.replayEvidenceJournal(n),n.lastActivityAt=i,this.persist(n),true}degradeEvidenceObligation(t,e,n,r=Date.now()){let i=this.get(t),s=i?.evidenceObligations.find(l=>l.obligationId===e);if(!i||!s)return false;let a=n.slice(0,240);return this.appendEvidenceEvent(t,{kind:"degrade",obligationId:e,contractId:s.contractId,at:r,reason:a},`degrade\0${e}\0${a}`),this.replayEvidenceJournal(i),i.lastActivityAt=r,this.persist(i),true}removeSession(t){let e=t.trim();e&&(this.sessions.delete(e),rmSync$1(this.snapshotPath(e),{force:true}),rmSync$1(this.evidenceJournalDir(e),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(t){return join$1(this.sessionsDir,`${le(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",le(t))}appendEvidenceEvent(t,e,n){let r=this.evidenceJournalDir(t);mkdirSync$1(r,{recursive:true,mode:448});let i=createHash$1("sha256").update(n).digest("hex"),s=join$1(r,`${e.kind}-${i}.json`);if(existsSync$1(s))return;let a=join$1(r,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync$1(a,JSON.stringify(e),{mode:384});try{linkSync(a,s);}catch(l){if(l.code!=="EEXIST")throw l}finally{rmSync$1(a,{force:true});}}replayEvidenceJournal(t){t.evidenceObligations=de(t.evidenceObligations),t.evidenceDegradations=ue(t.evidenceDegradations),t.evidenceOutcomes=pe(t.evidenceOutcomes);let e=this.evidenceJournalDir(t.sessionId);if(!existsSync$1(e))return;let n;try{n=readdirSync(e).filter(i=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(i)).slice(0,4096);}catch{return}let r=n.flatMap(i=>{try{let s=readFileSync(join$1(e,i),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=Ze(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||ge(i.kind)-ge(s.kind));for(let i of r)this.applyEvidenceEvent(t,i);t.evidenceObligations=t.evidenceObligations.slice(-8),t.evidenceDegradations=t.evidenceDegradations.slice(-20),t.evidenceOutcomes=t.evidenceOutcomes.slice(-20);}applyEvidenceEvent(t,e){let n=t.evidenceOutcomes.find(s=>s.obligationId===e.obligationId);if(e.kind==="add"){if(n)return;let s=t.evidenceObligations.find(a=>a.obligationId===e.obligationId);s?(s.contract=e.contract,s.promptedAt=Math.min(s.promptedAt,e.at)):t.evidenceObligations.push({obligationId:e.obligationId,contractId:e.contractId,contract:e.contract,promptedAt:e.at,attempt:0,correctionRequested:false,violations:[]});return}let r=t.evidenceObligations.find(s=>s.obligationId===e.obligationId);if(e.kind==="correction"){if(!r||n||r.correctionFingerprint===e.fingerprint)return;r.attempt+=1,r.correctionRequested=true,r.correctionRequestedAt=e.at,r.correctionFingerprint=e.fingerprint,r.violations=e.violations;return}let i=r?.attempt??0;t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==e.obligationId),!n&&(e.kind==="degrade"&&t.evidenceDegradations.push({obligationId:e.obligationId,contractId:e.contractId,reason:e.reason,degradedAt:e.at,attempt:i}),t.evidenceOutcomes.push({obligationId:e.obligationId,contractId:e.contractId,status:e.kind==="resolve"?"resolved":"degraded",completedAt:e.at,attempt:i,...e.kind==="degrade"?{reason:e.reason}:{}}));}persist(t){mkdirSync$1(this.sessionsDir,{recursive:true,mode:448});let e=this.snapshotPath(t.sessionId),n=`${e}.${process.pid}.${randomUUID()}.tmp`;writeFileSync$1(n,JSON.stringify(t),{mode:384}),renameSync$1(n,e);}};function de(o){return Array.isArray(o)?o.flatMap(t=>{if(!t||typeof t!="object")return [];let e=t;if(typeof e.contractId!="string"||e.contractId.length===0||e.contractId.length>128||typeof e.promptedAt!="number"||typeof e.attempt!="number"||typeof e.correctionRequested!="boolean"||!Array.isArray(e.violations)||!he(e.contract))return [];let n=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:fe(e.contractId),r=typeof e.correctionTranscriptHash=="string"?e.correctionTranscriptHash:void 0,i=e.correctionFingerprint??r;return i!==void 0&&!/^[a-f0-9]{64}$/.test(i)?[]:[{...e,obligationId:n,correctionFingerprint:i}]}).slice(-8):[]}function ue(o){return Array.isArray(o)?o.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&typeof e.reason=="string"&&typeof e.degradedAt=="number"&&typeof e.attempt=="number"}).slice(-20):[]}function pe(o){return Array.isArray(o)?o.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&(e.status==="resolved"||e.status==="degraded")&&typeof e.completedAt=="number"&&typeof e.attempt=="number"&&(e.reason===void 0||typeof e.reason=="string")}).slice(-20):[]}function Ze(o){if(!o||typeof o!="object")return null;let t=o;if(!["add","correction","resolve","degrade"].includes(t.kind??"")||typeof t.contractId!="string"||t.contractId.length>128||typeof t.at!="number")return null;let e=typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:fe(t.contractId);if(t.kind==="add")return he(t.contract)?{...t,obligationId:e}:null;if(t.kind==="correction"){let n=typeof t.fingerprint=="string"?t.fingerprint:t.transcriptHash;return typeof n=="string"&&/^[a-f0-9]{64}$/.test(n)&&Array.isArray(t.violations)&&t.violations.every(r=>typeof r=="string"&&r.length<=240)?{...t,obligationId:e,fingerprint:n}:null}return t.kind==="resolve"?{...t,obligationId:e}:typeof t.reason=="string"&&t.reason.length<=240?{...t,obligationId:e}:null}function ge(o){return o==="add"?0:o==="correction"?1:2}function he(o){if(!o||typeof o!="object")return false;let t=o,e=t.requiredSections,n=t.prohibitedClaims;return t.version==="1.0"&&typeof t.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(t.id)&&typeof t.runtimeProfilingOccurred=="boolean"&&typeof t.samplingEvidenceOccurred=="boolean"&&Array.isArray(e)&&e.length===3&&e[0]==="\u5DE5\u5177\u53D1\u73B0"&&e[1]==="\u6A21\u578B\u5047\u8BBE"&&e[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(n)&&n.length<=16&&n.every(r=>typeof r=="string"&&r.length<=128)&&typeof t.canonicalReport=="string"&&Buffer.byteLength(t.canonicalReport,"utf8")<=48*1024&&!!t.correctionPolicy&&t.correctionPolicy.maxAttempts===1&&t.correctionPolicy.repeatedViolation==="fail_open"}function ve(o,t){let e=et(o);mkdirSync(e,{recursive:true,mode:448});let n=join(e,`${t.receiptId}.json`);if(existsSync(n))return t.receiptId;let r=`${n}.${process.pid}.tmp`;writeFileSync(r,JSON.stringify(t),{mode:384});try{renameSync(r,n);}catch(i){try{unlinkSync(r);}catch{}if(!existsSync(n))throw i}return t.receiptId}function et(o){return join(_(o),"session-finalize-pending")}var st=512*1024,at=500;function ct(o,t){if(!o||o.length>4096)return {degradationReason:"transcript_path_missing"};let e;try{let n=lstatSync(o);if(!n.isFile()||n.isSymbolicLink())return {degradationReason:"transcript_path_unsafe"};e=openSync(o,constants.O_RDONLY|(constants.O_NOFOLLOW??0));let r=fstatSync(e);if(!r.isFile()||r.dev!==n.dev||r.ino!==n.ino)return {degradationReason:"transcript_path_changed"};let i=Math.min(r.size,st),s=Buffer.alloc(i),a=0;for(;a<i;){let y=readSync(e,s,a,i-a,r.size-i+a);if(y===0)break;a+=y;}let l=s.subarray(0,a).toString("utf8");r.size>i&&(l=l.slice(Math.max(0,l.indexOf(`
3
- `)+1)));let u=l.split(/\r?\n/).slice(-at),p=t.length>0?Math.min(...t.map(y=>y.promptedAt)):0,g=lt(u,p),b=[...g].reverse().find(y=>t.every(S=>S.contract.requiredSections.every(w=>y.text.includes(w))))??g.at(-1);return b?.text?{answer:b.text,fingerprint:b.fingerprint}:{degradationReason:"transcript_answer_unavailable"}}catch{return {degradationReason:"transcript_unreadable"}}finally{e!==void 0&&closeSync(e);}}function we(o){return ct(o,[]).answer}function lt(o,t){let e=[];for(let n=0;n<o.length;n++){let r=o[n];if(r.trim())try{let i=JSON.parse(r),s=i.message;if(!s||typeof s!="object"||s.role!=="assistant")continue;let a=s,l=dt(i.timestamp);if(l>0&&l+5e3<t)continue;let u=s.content,p=typeof u=="string"?u:Array.isArray(u)?u.filter(g=>g&&typeof g=="object"&&g.type==="text").map(g=>g.text).filter(g=>typeof g=="string").join(`
4
- `):"";if(p.trim()){let g=p.trim(),f=typeof a.id=="string"&&a.id?`message:${a.id}`:typeof i.uuid=="string"&&i.uuid?`uuid:${i.uuid}`:`record:${String(i.timestamp??"")}:${n}:${createHash("sha256").update(r).digest("hex")}`,b=createHash("sha256").update(g).digest("hex"),y=createHash("sha256").update(`${f}\0${b}`).digest("hex");e.push({text:g,timestamp:l,fingerprint:y});}}catch{continue}}return e}function dt(o){if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o!="string")return 0;let t=Date.parse(o);return Number.isFinite(t)?t:0}function mt(o){let t={committed:0,skipped:0,pending:0},e=[];for(let n of o)t[n.status]+=1,n.receiptId&&e.push(n.receiptId);return {memoryReceiptIds:[...new Set(e)],missingMemoryDecisionCount:t.pending,memoryTurnOutcomes:t}}function C(o){return (o instanceof Error?o.message:String(o)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var k=class extends Error{constructor(t,e){super(`session_finalize_${t}:${e}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${t}`;}};function L(o){let t;try{t=openGlobalDevFlowDatabase();let e=(o.executionId?t.getSkillExecution(o.executionId):null)??t.getLatestSkillExecutionForSession(o.sessionId),n={stage:o.stage,reason:o.reason,degradedAt:Date.now()};e&&t.mergeSkillExecutionMetadata(e.executionId,{...o.metadata,sessionFinalizationDegradations:[n]}),t.insertEvent({kind:"session_finalize_degraded",timestamp:n.degradedAt,success:!1,metadata:{projectRoot:o.projectRoot,sessionId:o.sessionId,executionId:e?.executionId,...n}});}catch{}finally{t?.close();}}function ft(o,t=M(),e=true,n,r=true){let i;try{i=JSON.parse(o);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${t}\0${s}`).digest("hex").slice(0,24)}`,l={inputJson:o,sessionId:s,cleanupSharedState:e,executionId:n},u;try{u=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let p=u.requestSessionClosure({receiptId:a,projectRoot:t,sessionId:s,payload:l}),g=u.getWorkByIdempotencyKey(a);return {status:p.state==="closed"||p.state==="closed_with_pending_work"?"completed":"accepted",receiptId:a,workState:g?.state??"pending",closureState:p.state,pendingWorkCount:p.pendingWorkCount}}catch(p){if(!r)throw p;return ve(t,{receiptId:a,...l}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{u?.close();}}async function On(o,t=M(),e=true,n){let r;try{r=JSON.parse(o);}catch{return}let i=r.session_id?.trim();if(!i)return;let s=new D(t),a=s.get(i),l={evidenceDegradations:a?.evidenceDegradations??[],evidenceContractOutcomes:a?.evidenceOutcomes??[],pendingEvidenceContractIds:a?.evidenceObligations.map(b=>b.contractId)??[]},u=n?.telemetry??new z,p=!n?.telemetry,g=false,f;try{try{await u.flushAndAggregate();}catch{}let b=Date.now(),y=n?.executionId??a?.executionId,S;try{let m=openGlobalDevFlowDatabase();try{S=m.listSessionMemoryTurnsForReconciliation(t,i);for(let c of S){let h=`memory:${c.turnId}`,d=m.getSessionObligation(t,i,h);d?d.state==="open"&&c.status!=="pending"&&m.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:h,state:"satisfied",receiptId:c.receiptId,reason:c.reason,resolvedAt:c.decidedAt}):m.upsertSessionObligation({obligationId:h,projectRoot:t,sessionId:i,turnId:c.turnId,kind:"memory_decision",state:c.status==="pending"?"open":"satisfied",payload:{eventId:c.eventId,promptHash:c.promptHash},receiptId:c.receiptId,reason:c.reason,createdAt:c.createdAt,updatedAt:c.decidedAt??c.createdAt,resolvedAt:c.decidedAt});}}finally{m.close();}}catch(m){let c=C(m),h={...l,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:c,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw L({projectRoot:t,sessionId:i,executionId:y,stage:"turn_load",reason:c,metadata:h}),new k("turn_load",c)}let w=mt(S),$=n?.memory??(f=new MemoryGate(t)),P={status:"unknown",selected:0,adopted:0,unknown:0};try{let m=we(r.transcript_path),c=await $.attributeRetrievalBenefits({sessionId:i,executionId:y,finalAnswer:m});P={status:m?"evaluated":"unknown",...c};}catch(m){P={...P,status:"degraded",reason:C(m)};}let E;try{E=await $.reconcileDecidedTurnEventWindows(i,S,b);}catch(m){let c=C(m),h={...w,...l,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:c,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw L({projectRoot:t,sessionId:i,executionId:y,stage:"event_reconciliation",reason:c,metadata:h}),new k("event_reconciliation",c)}let A;try{A=await oe({projectRoot:t,sessionId:i,trigger:"session_end",memory:$,details:{eventReconciliation:E},strictPersistence:!0});}catch(m){let c=C(m),h={...w,...l,memoryEventReconciliation:{status:"completed",...E,checkpointPending:null},memoryCheckpointDegradation:c};throw L({projectRoot:t,sessionId:i,executionId:y,stage:"checkpoint",reason:c,metadata:h}),new k("checkpoint",c)}let B={memoryBenefitAttribution:P,memoryEventReconciliation:{status:"completed",...E,checkpointPending:A.pendingEvents},memoryDistillCheckpoint:A};try{let m=openGlobalDevFlowDatabase();try{let c=`session-finalize:${i}:events`,h=Math.max(Number(A.pendingEvents??0),Number(E.remainingUndecided??0)),d=m.getSessionObligation(t,i,c);h>0?m.upsertSessionObligation({obligationId:c,projectRoot:t,sessionId:i,executionId:y,kind:"session_finalize",state:"open",payload:{pendingEvents:h,reconciliation:E,checkpointId:A.id},reason:"active_unprocessed_session_events",createdAt:d?.createdAt??b,updatedAt:b}):d?.state==="open"&&m.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:c,state:"satisfied",reason:"session_events_reconciled",resolvedAt:b});}finally{m.close();}}catch(m){console.error("[devflow] Session finalization obligation persistence failed:",m.message);}try{await $.closeSession(i),f&&(f.close(),f=void 0);}catch(m){let c=C(m),h={...w,...l,...B,memorySessionCloseDegradation:c};throw L({projectRoot:t,sessionId:i,executionId:y,stage:"memory_close",reason:c,metadata:h}),new k("memory_close",c)}let x={...w,...l,...B};g=!0;let v;try{v=openGlobalDevFlowDatabase();let m=y;if(m)try{v.reconcileSkillExecution(m,"completed",b,x);let d=v.getSkillExecution(m);await O("/api/telemetry/skill-execution/complete",{executionId:m,finishedAt:b,status:"completed",summary:{totalToolCalls:d?.totalToolCalls??0,mcpToolCalls:d?.mcpToolCalls??0,directToolCalls:d?.directToolCalls??0,subagentCount:d?.subagentCount??0,totalDuration:d?.totalDuration??0,mcpComplianceRate:d?.mcpComplianceRate??0,missedTools:d?.missedMcpTools??[],actualFailureCount:d?.failedToolCalls??0,fallbackCount:d?.fallbackCount??0,fallbackReasons:d?.fallbackReasons??[]},metadata:x},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let c=v.reconcileRunningSkillExecutionsForSession(i,b,{closureReason:"session_finalize",...x});for(let d of c)await O("/api/telemetry/skill-execution/complete",{executionId:d.executionId,finishedAt:d.finishedAt,status:d.status,summary:{totalToolCalls:d.totalToolCalls??0,mcpToolCalls:d.mcpToolCalls??0,directToolCalls:d.directToolCalls??0,subagentCount:d.subagentCount??0,totalDuration:d.totalDuration??0,mcpComplianceRate:d.mcpComplianceRate??0,missedTools:d.missedMcpTools??[],actualFailureCount:d.failedToolCalls??0,fallbackCount:d.fallbackCount??0,fallbackReasons:d.fallbackReasons??[]},metadata:x},{fallbackReason:"skill_execution_already_reconciled_locally"});let h=v.getLatestSkillExecutionForSession(i);if(h&&!c.some(d=>d.executionId===h.executionId)&&v.mergeSkillExecutionMetadata(h.executionId,x),e){v.deleteHookReceipt(t);let d=_(t),_e=createHash("sha256").update(t).digest("hex").slice(0,12);for(let Ie of [`session-id-${_e}`,"current-execution-id","current-skill.json","event-map.json"])rmSync(join(d,Ie),{force:!0});}v.deleteContextReceipt(t,i);}catch{}finally{v?.close();}try{await u.endSession(i),await u.flushAndAggregate();}catch{}}finally{if(f)try{f.close();}catch{}p&&u.close(),g&&s.removeSession(i);}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let o=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{t+=e;}),process.stdin.on("end",async()=>{let e=ft(t.trim()||process.argv[2]||"");e&&o(JSON.stringify(e)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}export{mt as buildMemoryTurnOutcomeMetadata,ft as enqueueSessionEndFinalization,On as handleSessionEnd};
1
+ import {getLocalApiKey,getProjectStateDir,resolveRuntimeEndpoint,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure}from'@devflow-tools/sdk';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {MemoryGate}from'@devflow-tools/memory-engine';import {existsSync as existsSync$1,readFileSync,rmSync as rmSync$1,mkdirSync as mkdirSync$1,writeFileSync as writeFileSync$1,linkSync,readdirSync,renameSync as renameSync$1,unlinkSync as unlinkSync$1}from'fs';import {join as join$1}from'path';import {homedir as homedir$1}from'os';import {request}from'node:http';import {mkdirSync,existsSync,writeFileSync,renameSync,unlinkSync,rmSync,lstatSync,openSync,constants,fstatSync,readSync,closeSync,appendFileSync}from'node:fs';import {join}from'node:path';import {homedir}from'node:os';import {createHash}from'node:crypto';import {randomUUID,createHash as createHash$1}from'crypto';function M(r){return r??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function E(r){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(M(r))}function N(r,t,e){try{let n=openGlobalDevFlowDatabase();try{n.insertEvent({kind:r,timestamp:Date.now(),duration:e,success:t.success!==!1,metadata:t});}finally{n.close();}}catch{}}var $e=getLocalApiKey(),q=join(homedir(),".devflow","errors");async function A(r,t,e={}){let n=e.endpoint??resolveRuntimeEndpoint().url,i=e.timeout??1500,o=e.durableMirror??true,s=e.maxRetries??(o?0:2),a=e.circuitBreaker??true,l=acquireRuntimeHttpCircuit(n,r);if(a&&!l.allowed)return {delivered:false,suppressed:true,fallbackReason:l.state.fallbackReason};let u;for(let g=0;g<=s;g+=1)try{return await Pe(n,r,t,i),a&&registerRuntimeHttpSuccess(n,r).transitioned&&N("http_circuit_transition",{endpoint:n,path:new URL(r,n).pathname,previous:l.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(f){u=f instanceof Error?f:new Error(String(f)),g<s&&await Me(Math.min(100*2**g,1e3));}if(!u)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return X(r,u),{delivered:false,suppressed:false,fallbackReason:u.message};let p=registerRuntimeHttpFailure(n,r,e.fallbackReason??(o?"local_durable_mirror":"http_delivery_failed"));return p.transitioned&&(X(r,u),N("http_circuit_transition",{endpoint:n,path:new URL(r,n).pathname,previous:l.state.status,status:"open",failures:p.state.failures,openUntil:p.state.openUntil,fallbackReason:p.state.fallbackReason})),{delivered:false,suppressed:false,fallbackReason:p.state.fallbackReason}}function Pe(r,t,e,n){return new Promise((i,o)=>{let s=JSON.stringify(e),a=new URL(t,r),l=false,u=g=>{l||(l=true,g?o(g):i());},p=request({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":$e,"Content-Length":Buffer.byteLength(s)},timeout:n},g=>{g.on("error",u),g.on("end",()=>{let f=g.statusCode??0;u(f>=200&&f<300?void 0:new Error(`HTTP ${f}`));}),g.resume();});p.on("error",u),p.on("timeout",()=>p.destroy(new Error(`HTTP mirror timed out after ${n}ms`))),p.write(s),p.end();})}function X(r,t){try{existsSync(q)||mkdirSync(q,{recursive:!0}),appendFileSync(join(q,"http-errors.log"),`${new Date().toISOString()} | ${r} | ${t.message}
2
+ `);}catch{}}function Me(r){return new Promise(t=>setTimeout(t,r))}var ne=1e4,Ne=3e4,F=500,z=class{constructor(t){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=t?.apiUrl,this.cacheDir=t?.cacheDir??join$1(process.env.DEVFLOW_STATE_DIR??join$1(homedir$1(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=t?.legacyCacheDir??(t?.cacheDir?null:join$1(homedir$1(),".devflow","telemetry-cache")),this.database=t?.database??null,this.ownsDatabase=!t?.database;let e=t?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(e)&&e>=0?e:100;}async sendEvent(t){let e={...t,input:this.truncateInput(t.input)};return this.commitOrCache("tool_call",e)?(this.postHttp("/api/telemetry/tool-call",e),t.eventId):null}async sendExecutionStart(t,e,n,i,o=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:t,sessionId:e,skillName:n,startedAt:i,projectRoot:o,requiredMcpTools:s};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(t,e="completed",n=Date.now(),i){let o={executionId:t,status:e,finishedAt:n,metadata:i},s=this.commitOrCache("execution_complete",o);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",o),s}async sendSessionStart(t,e,n){let i={id:t,projectRoot:e,startedAt:n,label:e.split("/").pop()??"unknown"},o=this.commitOrCache("session_start",i);return o&&this.postHttp("/api/telemetry/sessions",i),o}async completeEvent(t){let e=this.commitOrCache("complete_event",t);return e&&(this.postHttp("/api/telemetry/tool-call/output",t),this.scheduleMetricAggregation()),e}async endSession(t,e=Date.now()){let n={sessionId:t,finishedAt:e},i=this.commitOrCache("session_end",n);return i&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:e})),i}async flushCache(){try{let n=this.getDatabase(),i=n.listTelemetryFailures({unresolvedOnly:!0,limit:F}).reverse();for(let o of i)try{this.applyOperation(o.operation,o.payload),n.resolveTelemetryFailure(o.id);}catch{}n.trimTelemetryFailures(F);}catch{}let e=[...new Set([this.cacheDir,this.legacyCacheDir].filter(n=>!!n))].filter(n=>existsSync$1(n)).flatMap(n=>readdirSync(n).filter(i=>i.endsWith(".json")).map(i=>{let o=join$1(n,i);try{return {cacheFile:o,envelope:qe(JSON.parse(readFileSync(o,"utf8")),i)}}catch{return null}})).filter(n=>n!==null).sort((n,i)=>n.envelope.timestamp-i.envelope.timestamp||ie(n.envelope.operation)-ie(i.envelope.operation));for(let{cacheFile:n,envelope:i}of e)try{let o=this.getDatabase();o.insertTelemetryFailure({id:i.id,operation:i.operation,payload:i.payload,error:i.failure,createdAt:i.timestamp}),this.applyOperation(i.operation,i.payload),o.resolveTelemetryFailure(i.id),unlinkSync$1(n);}catch{}this.database?.aggregatePendingToolMetrics();}aggregateMetrics(){return this.getDatabase().aggregatePendingToolMetrics()}async flushAndAggregate(){await this.flushCache(),this.aggregateMetrics();}close(){this.ownsDatabase&&this.database?.close(),this.database=null;}getDatabase(){return this.database??=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:this.busyTimeoutMs}),this.database}commitOrCache(t,e){try{return this.applyOperation(t,e),!0}catch(n){return this.cacheOperation(t,e,n),false}}applyOperation(t,e){let n=this.getDatabase();switch(t){case "tool_call":this.ensureParentSession(n,e),n.insertToolCallEvent(e);return;case "execution_start":this.ensureParentSession(n,e),n.insertSkillExecution({executionId:e.executionId,sessionId:e.sessionId,skillName:e.skillName,startedAt:e.startedAt,status:"running",requiredMcpTools:e.requiredMcpTools});return;case "execution_complete":n.reconcileSkillExecution(e.executionId,e.status,e.finishedAt,e.metadata);return;case "session_start":n.ensureSession(e),n.insertRun({id:re(e.id),source:"hook",tool:"session",input:{projectRoot:e.projectRoot},status:"active",startedAt:e.startedAt,tokenUsed:0,metadata:{sessionId:e.id,projectRoot:e.projectRoot}});return;case "complete_event":if(!n.updateToolCallEvent(e.eventId,{output:e.output===void 0?void 0:JSON.stringify(e.output),error:e.error,failureCategory:e.failureCategory,duration:e.duration}))throw new Error(`Tool call event ${e.eventId} is not available for completion`);return;case "session_end":n.closeSession(e.sessionId,e.finishedAt),n.updateRun(re(e.sessionId),{status:"completed",finishedAt:e.finishedAt});return}}ensureParentSession(t,e){let n=typeof e.sessionId=="string"?e.sessionId.trim():"";if(!n)throw new Error("Canonical session ID is required for telemetry");let i=typeof e.projectRoot=="string"&&e.projectRoot.trim()?e.projectRoot:typeof e.input?.projectRoot=="string"&&e.input.projectRoot.trim()?e.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";t.ensureSession({id:n,projectRoot:i,label:i==="unknown"?void 0:i.split("/").pop(),startedAt:Number(e.startedAt??e.timestamp??Date.now())});}cacheOperation(t,e,n){let i=Date.now(),o={id:`failure:${i}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:e,failure:n instanceof Error?n.message:String(n),timestamp:i};try{let s=this.getDatabase();s.insertTelemetryFailure({id:o.id,operation:t,payload:e,error:o.failure,createdAt:i}),s.trimTelemetryFailures(F),this.scheduleRetry();return}catch{}try{existsSync$1(this.cacheDir)||mkdirSync$1(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${i}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync$1(s,JSON.stringify(o,null,2),{mode:384}),this.trimCompatibilityCache(),this.scheduleRetry();}catch{}}trimCompatibilityCache(){try{let t=readdirSync(this.cacheDir).filter(e=>e.endsWith(".json")).sort();for(let e of t.slice(0,Math.max(0,t.length-F)))unlinkSync$1(join$1(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},Ne).unref());}scheduleMetricAggregation(){if(this.metricAggregationScheduled||process.env.DEVFLOW_HOOK_DEGRADED==="1")return;this.metricAggregationScheduled=true,setTimeout(()=>{this.metricAggregationScheduled=false;try{this.getDatabase().aggregatePendingToolMetrics(50)===50&&this.scheduleMetricAggregation();}catch{}},25).unref();}postHttp(t,e){A(t,e,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=ne?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,ne)}...`}}};function ie(r){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(r)}function re(r){return `hook-run:${r}`}function qe(r,t){if(!r||typeof r!="object")throw new Error("Invalid telemetry cache envelope");let e=r;if(typeof e.operation=="string"&&e.payload!==void 0)return e;let n=e.type==="tool_call"?"tool_call":e.type==="execution_start"?"execution_start":null;if(!n)throw new Error("Unknown legacy telemetry cache operation");let i=e.payload??{},o=Number(i.timestamp??i.startedAt??Date.now());return {id:`legacy-cache:${t}`,operation:n,payload:i,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:o}}async function oe(r){let t=!r.memory,e=r.memory??new MemoryGate(r.projectRoot),n=0,i=0;try{await e.forceWarmUp(),r.trigger==="session_end"&&(n=await e.releasePendingDistillLeases(r.sessionId)),i=e.getPendingEventCount(r.sessionId,r.trigger!=="session_end");}finally{t&&e.close();}let o={pendingEvents:i,releasedLeases:n,trigger:r.trigger,sessionId:r.sessionId,details:r.details};try{let s=openGlobalDevFlowDatabase();try{let a=Date.now(),l=r.trigger==="session_end"&&r.sessionId?`distill:session_end:${createHash("sha256").update(`${r.projectRoot}\0${r.sessionId}`).digest("hex").slice(0,24)}`:`distill:${a}:${Math.random().toString(36).slice(2,10)}`;s.recordMemoryDistillCheckpoint({id:l,projectRoot:r.projectRoot,sessionId:r.sessionId,trigger:r.trigger,pendingEvents:i,releasedLeases:n,details:r.details,createdAt:a}),s.insertEvent({kind:"memory_distill_requested",timestamp:a,success:!0,metadata:{...o,projectRoot:r.projectRoot}});}finally{s.close();}}catch(s){throw s}return o}function le(r){return Buffer.from(r,"utf8").toString("base64url")}function Ve(r,t,e){let n=t?.trim();if(n){let i=/^[a-zA-Z0-9:._-]{1,192}$/.test(n)?n:`tool-${createHash$1("sha256").update(n.slice(0,1024)).digest("hex").slice(0,32)}`;return `${r}:${i}`}return `${r}:legacy-${e}-${randomUUID().slice(0,8)}`}function fe(r){return `${r}:legacy-journal`}var x=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(E(t),"hook-sessions");}registerSession(t){let e=t.trim();if(!e)throw new Error("session_id_required");let n=this.get(e);if(n)return n.lastActivityAt=Date.now(),this.persist(n),n;let i=Date.now(),o={sessionId:e,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:i,lastActivityAt:i};return this.sessions.set(e,o),this.persist(o),o}startExecution(t,e,n){let i=this.registerSession(t);return (!i.executionId||i.skillName!==e)&&(i.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),i.skillName=e,i.requiredMcpTools=[...new Set(n)],i.lastActivityAt=Date.now(),this.persist(i),i}get(t){let e=t.trim();if(!e)return null;let n=this.sessions.get(e);if(n)return this.replayEvidenceJournal(n),n;let i=this.snapshotPath(e);if(!existsSync$1(i))return null;try{let o=JSON.parse(readFileSync(i,"utf8"));return o.sessionId!==e||o.projectRoot!==this.projectRoot?null:(o.requiredMcpTools=Array.isArray(o.requiredMcpTools)?o.requiredMcpTools:[],o.evidenceObligations=de(o.evidenceObligations),o.evidenceDegradations=ue(o.evidenceDegradations),o.evidenceOutcomes=pe(o.evidenceOutcomes),this.replayEvidenceJournal(o),this.sessions.set(e,o),o)}catch{return null}}completeExecution(t){let e=this.get(t);if(!e)return null;let n=structuredClone(e);return delete e.executionId,delete e.skillName,e.requiredMcpTools=[],e.lastActivityAt=Date.now(),this.persist(e),n}addEvidenceObligation(t,e,n=Date.now(),i){let o=this.registerSession(t),a=(i?void 0:o.evidenceObligations.find(u=>u.contractId===e.id))?.obligationId??Ve(e.id,i,n);this.appendEvidenceEvent(t,{kind:"add",obligationId:a,contractId:e.id,at:n,contract:e},`add\0${a}`),this.replayEvidenceJournal(o);let l=o.evidenceObligations.find(u=>u.obligationId===a);return l?(o.lastActivityAt=Date.now(),this.persist(o),structuredClone(l)):null}listEvidenceObligations(t){return (this.get(t)?.evidenceObligations??[]).map(e=>structuredClone(e))}markEvidenceCorrection(t,e,n,i,o=Date.now()){let s=this.get(t),a=s?.evidenceObligations.find(p=>p.obligationId===e);if(!s||!a)return null;let l=/^[a-f0-9]{64}$/.test(i)?i:"";if(!l)return null;this.appendEvidenceEvent(t,{kind:"correction",obligationId:e,contractId:a.contractId,at:o,fingerprint:l,violations:n.slice(0,16).map(p=>p.slice(0,240))},`correction\0${e}\0${l}`),this.replayEvidenceJournal(s),s.lastActivityAt=o,this.persist(s);let u=s.evidenceObligations.find(p=>p.obligationId===e);return u?structuredClone(u):null}resolveEvidenceObligation(t,e){let n=this.get(t);if(!n)return false;let i=n.evidenceObligations.find(s=>s.obligationId===e);if(!i)return false;let o=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:i.contractId,at:o},`resolve\0${e}`),this.replayEvidenceJournal(n),n.lastActivityAt=o,this.persist(n),true}degradeEvidenceObligation(t,e,n,i=Date.now()){let o=this.get(t),s=o?.evidenceObligations.find(l=>l.obligationId===e);if(!o||!s)return false;let a=n.slice(0,240);return this.appendEvidenceEvent(t,{kind:"degrade",obligationId:e,contractId:s.contractId,at:i,reason:a},`degrade\0${e}\0${a}`),this.replayEvidenceJournal(o),o.lastActivityAt=i,this.persist(o),true}removeSession(t){let e=t.trim();e&&(this.sessions.delete(e),rmSync$1(this.snapshotPath(e),{force:true}),rmSync$1(this.evidenceJournalDir(e),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(t){return join$1(this.sessionsDir,`${le(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",le(t))}appendEvidenceEvent(t,e,n){let i=this.evidenceJournalDir(t);mkdirSync$1(i,{recursive:true,mode:448});let o=createHash$1("sha256").update(n).digest("hex"),s=join$1(i,`${e.kind}-${o}.json`);if(existsSync$1(s))return;let a=join$1(i,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync$1(a,JSON.stringify(e),{mode:384});try{linkSync(a,s);}catch(l){if(l.code!=="EEXIST")throw l}finally{rmSync$1(a,{force:true});}}replayEvidenceJournal(t){t.evidenceObligations=de(t.evidenceObligations),t.evidenceDegradations=ue(t.evidenceDegradations),t.evidenceOutcomes=pe(t.evidenceOutcomes);let e=this.evidenceJournalDir(t.sessionId);if(!existsSync$1(e))return;let n;try{n=readdirSync(e).filter(o=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(o)).slice(0,4096);}catch{return}let i=n.flatMap(o=>{try{let s=readFileSync(join$1(e,o),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=Ze(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((o,s)=>o.at-s.at||ge(o.kind)-ge(s.kind));for(let o of i)this.applyEvidenceEvent(t,o);t.evidenceObligations=t.evidenceObligations.slice(-8),t.evidenceDegradations=t.evidenceDegradations.slice(-20),t.evidenceOutcomes=t.evidenceOutcomes.slice(-20);}applyEvidenceEvent(t,e){let n=t.evidenceOutcomes.find(s=>s.obligationId===e.obligationId);if(e.kind==="add"){if(n)return;let s=t.evidenceObligations.find(a=>a.obligationId===e.obligationId);s?(s.contract=e.contract,s.promptedAt=Math.min(s.promptedAt,e.at)):t.evidenceObligations.push({obligationId:e.obligationId,contractId:e.contractId,contract:e.contract,promptedAt:e.at,attempt:0,correctionRequested:false,violations:[]});return}let i=t.evidenceObligations.find(s=>s.obligationId===e.obligationId);if(e.kind==="correction"){if(!i||n||i.correctionFingerprint===e.fingerprint)return;i.attempt+=1,i.correctionRequested=true,i.correctionRequestedAt=e.at,i.correctionFingerprint=e.fingerprint,i.violations=e.violations;return}let o=i?.attempt??0;t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==e.obligationId),!n&&(e.kind==="degrade"&&t.evidenceDegradations.push({obligationId:e.obligationId,contractId:e.contractId,reason:e.reason,degradedAt:e.at,attempt:o}),t.evidenceOutcomes.push({obligationId:e.obligationId,contractId:e.contractId,status:e.kind==="resolve"?"resolved":"degraded",completedAt:e.at,attempt:o,...e.kind==="degrade"?{reason:e.reason}:{}}));}persist(t){mkdirSync$1(this.sessionsDir,{recursive:true,mode:448});let e=this.snapshotPath(t.sessionId),n=`${e}.${process.pid}.${randomUUID()}.tmp`;writeFileSync$1(n,JSON.stringify(t),{mode:384}),renameSync$1(n,e);}};function de(r){return Array.isArray(r)?r.flatMap(t=>{if(!t||typeof t!="object")return [];let e=t;if(typeof e.contractId!="string"||e.contractId.length===0||e.contractId.length>128||typeof e.promptedAt!="number"||typeof e.attempt!="number"||typeof e.correctionRequested!="boolean"||!Array.isArray(e.violations)||!he(e.contract))return [];let n=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:fe(e.contractId),i=typeof e.correctionTranscriptHash=="string"?e.correctionTranscriptHash:void 0,o=e.correctionFingerprint??i;return o!==void 0&&!/^[a-f0-9]{64}$/.test(o)?[]:[{...e,obligationId:n,correctionFingerprint:o}]}).slice(-8):[]}function ue(r){return Array.isArray(r)?r.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&typeof e.reason=="string"&&typeof e.degradedAt=="number"&&typeof e.attempt=="number"}).slice(-20):[]}function pe(r){return Array.isArray(r)?r.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&(e.status==="resolved"||e.status==="degraded")&&typeof e.completedAt=="number"&&typeof e.attempt=="number"&&(e.reason===void 0||typeof e.reason=="string")}).slice(-20):[]}function Ze(r){if(!r||typeof r!="object")return null;let t=r;if(!["add","correction","resolve","degrade"].includes(t.kind??"")||typeof t.contractId!="string"||t.contractId.length>128||typeof t.at!="number")return null;let e=typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:fe(t.contractId);if(t.kind==="add")return he(t.contract)?{...t,obligationId:e}:null;if(t.kind==="correction"){let n=typeof t.fingerprint=="string"?t.fingerprint:t.transcriptHash;return typeof n=="string"&&/^[a-f0-9]{64}$/.test(n)&&Array.isArray(t.violations)&&t.violations.every(i=>typeof i=="string"&&i.length<=240)?{...t,obligationId:e,fingerprint:n}:null}return t.kind==="resolve"?{...t,obligationId:e}:typeof t.reason=="string"&&t.reason.length<=240?{...t,obligationId:e}:null}function ge(r){return r==="add"?0:r==="correction"?1:2}function he(r){if(!r||typeof r!="object")return false;let t=r,e=t.requiredSections,n=t.prohibitedClaims;return t.version==="1.0"&&typeof t.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(t.id)&&typeof t.runtimeProfilingOccurred=="boolean"&&typeof t.samplingEvidenceOccurred=="boolean"&&Array.isArray(e)&&e.length===3&&e[0]==="\u5DE5\u5177\u53D1\u73B0"&&e[1]==="\u6A21\u578B\u5047\u8BBE"&&e[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(n)&&n.length<=16&&n.every(i=>typeof i=="string"&&i.length<=128)&&typeof t.canonicalReport=="string"&&Buffer.byteLength(t.canonicalReport,"utf8")<=48*1024&&!!t.correctionPolicy&&t.correctionPolicy.maxAttempts===1&&t.correctionPolicy.repeatedViolation==="fail_open"}function ve(r,t){let e=et(r);mkdirSync(e,{recursive:true,mode:448});let n=join(e,`${t.receiptId}.json`);if(existsSync(n))return t.receiptId;let i=`${n}.${process.pid}.tmp`;writeFileSync(i,JSON.stringify(t),{mode:384});try{renameSync(i,n);}catch(o){try{unlinkSync(i);}catch{}if(!existsSync(n))throw o}return t.receiptId}function et(r){return join(E(r),"session-finalize-pending")}var st=512*1024,at=500;var ct=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function lt(r){let t=false,e=[],n=[];for(let i of r){if(/^\s*```/.test(i)){t=!t,e.push(""),n.push(i.replace(/^\s*```+[^\s`]*/,"").replace(/```+\s*$/,"").trim());continue}e.push(t?"":i.replace(/`[^`]*`/g,"").trim()),n.push(i.replace(/`([^`]*)`/g,(o,s)=>dt(s)?"":s).trim());}return {headingLines:e,claimLines:n}}function dt(r){let t=r.trim().slice(0,256);return !t||/\s/.test(t)||r.trim().length>256?false:/^[A-Za-z_$][\w$.-]*$/.test(t)||/^(['"])[^'"`]*\1$/.test(t)}function ut(r,t){if(!r||r.length>4096)return {degradationReason:"transcript_path_missing"};let e;try{let n=lstatSync(r);if(!n.isFile()||n.isSymbolicLink())return {degradationReason:"transcript_path_unsafe"};e=openSync(r,constants.O_RDONLY|(constants.O_NOFOLLOW??0));let i=fstatSync(e);if(!i.isFile()||i.dev!==n.dev||i.ino!==n.ino)return {degradationReason:"transcript_path_changed"};let o=Math.min(i.size,st),s=Buffer.alloc(o),a=0;for(;a<o;){let y=readSync(e,s,a,o-a,i.size-o+a);if(y===0)break;a+=y;}let l=s.subarray(0,a).toString("utf8");i.size>o&&(l=l.slice(Math.max(0,l.indexOf(`
3
+ `)+1)));let u=l.split(/\r?\n/).slice(-at),p=t.length>0?Math.min(...t.map(y=>y.promptedAt)):0,g=gt(u,p),b=[...g].reverse().find(y=>pt(y.text,t))??g.at(-1);return b?.text?{answer:b.text,fingerprint:b.fingerprint}:{degradationReason:"transcript_answer_unavailable"}}catch{return {degradationReason:"transcript_unreadable"}}finally{e!==void 0&&closeSync(e);}}function pt(r,t){let e=new Set(t.flatMap(i=>i.contract.requiredSections)),n=ft(lt(r.split(/\r?\n/u)).headingLines);return [...e].every(i=>n.found.has(i))}function Ee(r){return ut(r,[]).answer}function gt(r,t){let e=[];for(let n=0;n<r.length;n++){let i=r[n];if(i.trim())try{let o=JSON.parse(i),s=o.message;if(!s||typeof s!="object"||s.role!=="assistant")continue;let a=s,l=mt(o.timestamp);if(l>0&&l+5e3<t)continue;let u=s.content,p=typeof u=="string"?u:Array.isArray(u)?u.filter(g=>g&&typeof g=="object"&&g.type==="text").map(g=>g.text).filter(g=>typeof g=="string").join(`
4
+ `):"";if(p.trim()){let g=p.trim(),f=typeof a.id=="string"&&a.id?`message:${a.id}`:typeof o.uuid=="string"&&o.uuid?`uuid:${o.uuid}`:`record:${String(o.timestamp??"")}:${n}:${createHash("sha256").update(i).digest("hex")}`,b=createHash("sha256").update(g).digest("hex"),y=createHash("sha256").update(`${f}\0${b}`).digest("hex");e.push({text:g,timestamp:l,fingerprint:y});}}catch{continue}}return e}function mt(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r!="string")return 0;let t=Date.parse(r);return Number.isFinite(t)?t:0}function ft(r){let t=new Set,e=new Map,n;for(let i=0;i<r.length;i++){let o=r[i].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=ct.find(a=>o===a);s&&(n=s,t.add(s)),e.set(i,n);}return {found:t,byLine:e}}function vt(r){let t={committed:0,skipped:0,pending:0},e=[];for(let n of r)t[n.status]+=1,n.receiptId&&e.push(n.receiptId);return {memoryReceiptIds:[...new Set(e)],missingMemoryDecisionCount:t.pending,memoryTurnOutcomes:t}}function O(r){return (r instanceof Error?r.message:String(r)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var I=class extends Error{constructor(t,e){super(`session_finalize_${t}:${e}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${t}`;}};function L(r){let t;try{t=openGlobalDevFlowDatabase();let e=(r.executionId?t.getSkillExecution(r.executionId):null)??t.getLatestSkillExecutionForSession(r.sessionId),n={stage:r.stage,reason:r.reason,degradedAt:Date.now()};e&&t.mergeSkillExecutionMetadata(e.executionId,{...r.metadata,sessionFinalizationDegradations:[n]}),t.insertEvent({kind:"session_finalize_degraded",timestamp:n.degradedAt,success:!1,metadata:{projectRoot:r.projectRoot,sessionId:r.sessionId,executionId:e?.executionId,...n}});}catch{}finally{t?.close();}}function St(r,t=M(),e=true,n,i=true){let o;try{o=JSON.parse(r);}catch{return null}let s=o.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${t}\0${s}`).digest("hex").slice(0,24)}`,l={inputJson:r,sessionId:s,cleanupSharedState:e,executionId:n},u;try{u=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let p=u.requestSessionClosure({receiptId:a,projectRoot:t,sessionId:s,payload:l}),g=u.getWorkByIdempotencyKey(a);return {status:p.state==="closed"||p.state==="closed_with_pending_work"?"completed":"accepted",receiptId:a,workState:g?.state??"pending",closureState:p.state,pendingWorkCount:p.pendingWorkCount}}catch(p){if(!i)throw p;return ve(t,{receiptId:a,...l}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{u?.close();}}async function Pn(r,t=M(),e=true,n){let i;try{i=JSON.parse(r);}catch{return}let o=i.session_id?.trim();if(!o)return;let s=new x(t),a=s.get(o),l={evidenceDegradations:a?.evidenceDegradations??[],evidenceContractOutcomes:a?.evidenceOutcomes??[],pendingEvidenceContractIds:a?.evidenceObligations.map(b=>b.contractId)??[]},u=n?.telemetry??new z,p=!n?.telemetry,g=false,f;try{try{await u.flushAndAggregate();}catch{}let b=Date.now(),y=n?.executionId??a?.executionId,C;try{let m=openGlobalDevFlowDatabase();try{C=m.listSessionMemoryTurnsForReconciliation(t,o);for(let c of C){let h=`memory:${c.turnId}`,d=m.getSessionObligation(t,o,h);d?d.state==="open"&&c.status!=="pending"&&m.resolveSessionObligation({projectRoot:t,sessionId:o,obligationId:h,state:"satisfied",receiptId:c.receiptId,reason:c.reason,resolvedAt:c.decidedAt}):m.upsertSessionObligation({obligationId:h,projectRoot:t,sessionId:o,turnId:c.turnId,kind:"memory_decision",state:c.status==="pending"?"open":"satisfied",payload:{eventId:c.eventId,promptHash:c.promptHash},receiptId:c.receiptId,reason:c.reason,createdAt:c.createdAt,updatedAt:c.decidedAt??c.createdAt,resolvedAt:c.decidedAt});}}finally{m.close();}}catch(m){let c=O(m),h={...l,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:c,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw L({projectRoot:t,sessionId:o,executionId:y,stage:"turn_load",reason:c,metadata:h}),new I("turn_load",c)}let T=vt(C),$=n?.memory??(f=new MemoryGate(t)),P={status:"unknown",selected:0,adopted:0,unknown:0};try{let m=Ee(i.transcript_path),c=await $.attributeRetrievalBenefits({sessionId:o,executionId:y,finalAnswer:m});P={status:m?"evaluated":"unknown",...c};}catch(m){P={...P,status:"degraded",reason:O(m)};}let S;try{S=await $.reconcileDecidedTurnEventWindows(o,C,b);}catch(m){let c=O(m),h={...T,...l,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:c,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw L({projectRoot:t,sessionId:o,executionId:y,stage:"event_reconciliation",reason:c,metadata:h}),new I("event_reconciliation",c)}let R;try{R=await oe({projectRoot:t,sessionId:o,trigger:"session_end",memory:$,details:{eventReconciliation:S},strictPersistence:!0});}catch(m){let c=O(m),h={...T,...l,memoryEventReconciliation:{status:"completed",...S,checkpointPending:null},memoryCheckpointDegradation:c};throw L({projectRoot:t,sessionId:o,executionId:y,stage:"checkpoint",reason:c,metadata:h}),new I("checkpoint",c)}let B={memoryBenefitAttribution:P,memoryEventReconciliation:{status:"completed",...S,checkpointPending:R.pendingEvents},memoryDistillCheckpoint:R};try{let m=openGlobalDevFlowDatabase();try{let c=`session-finalize:${o}:events`,h=Math.max(Number(R.pendingEvents??0),Number(S.remainingUndecided??0)),d=m.getSessionObligation(t,o,c);h>0?m.upsertSessionObligation({obligationId:c,projectRoot:t,sessionId:o,executionId:y,kind:"session_finalize",state:"open",payload:{pendingEvents:h,reconciliation:S,checkpointId:R.id},reason:"active_unprocessed_session_events",createdAt:d?.createdAt??b,updatedAt:b}):d?.state==="open"&&m.resolveSessionObligation({projectRoot:t,sessionId:o,obligationId:c,state:"satisfied",reason:"session_events_reconciled",resolvedAt:b});}finally{m.close();}}catch(m){console.error("[devflow] Session finalization obligation persistence failed:",m.message);}try{await $.closeSession(o),f&&(f.close(),f=void 0);}catch(m){let c=O(m),h={...T,...l,...B,memorySessionCloseDegradation:c};throw L({projectRoot:t,sessionId:o,executionId:y,stage:"memory_close",reason:c,metadata:h}),new I("memory_close",c)}let k={...T,...l,...B};g=!0;let v;try{v=openGlobalDevFlowDatabase();let m=y;if(m)try{v.reconcileSkillExecution(m,"completed",b,k);let d=v.getSkillExecution(m);await A("/api/telemetry/skill-execution/complete",{executionId:m,finishedAt:b,status:"completed",summary:{totalToolCalls:d?.totalToolCalls??0,mcpToolCalls:d?.mcpToolCalls??0,directToolCalls:d?.directToolCalls??0,subagentCount:d?.subagentCount??0,totalDuration:d?.totalDuration??0,mcpComplianceRate:d?.mcpComplianceRate??0,missedTools:d?.missedMcpTools??[],actualFailureCount:d?.failedToolCalls??0,fallbackCount:d?.fallbackCount??0,fallbackReasons:d?.fallbackReasons??[]},metadata:k},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let c=v.reconcileRunningSkillExecutionsForSession(o,b,{closureReason:"session_finalize",...k});for(let d of c)await A("/api/telemetry/skill-execution/complete",{executionId:d.executionId,finishedAt:d.finishedAt,status:d.status,summary:{totalToolCalls:d.totalToolCalls??0,mcpToolCalls:d.mcpToolCalls??0,directToolCalls:d.directToolCalls??0,subagentCount:d.subagentCount??0,totalDuration:d.totalDuration??0,mcpComplianceRate:d.mcpComplianceRate??0,missedTools:d.missedMcpTools??[],actualFailureCount:d.failedToolCalls??0,fallbackCount:d.fallbackCount??0,fallbackReasons:d.fallbackReasons??[]},metadata:k},{fallbackReason:"skill_execution_already_reconciled_locally"});let h=v.getLatestSkillExecutionForSession(o);if(h&&!c.some(d=>d.executionId===h.executionId)&&v.mergeSkillExecutionMetadata(h.executionId,k),e){v.deleteHookReceipt(t);let d=E(t),_e=createHash("sha256").update(t).digest("hex").slice(0,12);for(let Ie of [`session-id-${_e}`,"current-execution-id","current-skill.json","event-map.json"])rmSync(join(d,Ie),{force:!0});}v.deleteContextReceipt(t,o);}catch{}finally{v?.close();}try{await u.endSession(o),await u.flushAndAggregate();}catch{}}finally{if(f)try{f.close();}catch{}p&&u.close(),g&&s.removeSession(o);}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let r=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{t+=e;}),process.stdin.on("end",async()=>{let e=St(t.trim()||process.argv[2]||"");e&&r(JSON.stringify(e)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}export{vt as buildMemoryTurnOutcomeMetadata,St as enqueueSessionEndFinalization,Pn as handleSessionEnd};
@@ -1,17 +1,17 @@
1
- import {getLocalApiKey,resolveRuntimeEndpoint,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,getProjectStateDir}from'@devflow-tools/sdk';import {existsSync as existsSync$1,readFileSync as readFileSync$1,rmSync,mkdirSync as mkdirSync$1,writeFileSync as writeFileSync$1,linkSync,readdirSync,renameSync as renameSync$1}from'fs';import {join as join$1}from'path';import {randomUUID,createHash as createHash$1}from'crypto';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import'@devflow-tools/memory-engine';import'os';import {request}from'node:http';import {mkdirSync,existsSync,writeFileSync,renameSync,unlinkSync,readFileSync,openSync,constants,fstatSync,closeSync,appendFileSync,lstatSync,readSync}from'node:fs';import {join,resolve}from'node:path';import {homedir}from'node:os';import {createHash}from'node:crypto';function v(n){return n??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function S(n){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(v(n))}function P(n){return Buffer.from(n,"utf8").toString("base64url")}function fe(n,e,t){let r=e?.trim();if(r){let o=/^[a-zA-Z0-9:._-]{1,192}$/.test(r)?r:`tool-${createHash$1("sha256").update(r.slice(0,1024)).digest("hex").slice(0,32)}`;return `${n}:${o}`}return `${n}:legacy-${t}-${randomUUID().slice(0,8)}`}function H(n){return `${n}:legacy-journal`}var y=class{constructor(e){this.projectRoot=e;this.sessions=new Map;this.sessionsDir=join$1(S(e),"hook-sessions");}registerSession(e){let t=e.trim();if(!t)throw new Error("session_id_required");let r=this.get(t);if(r)return r.lastActivityAt=Date.now(),this.persist(r),r;let o=Date.now(),i={sessionId:t,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:o,lastActivityAt:o};return this.sessions.set(t,i),this.persist(i),i}startExecution(e,t,r){let o=this.registerSession(e);return (!o.executionId||o.skillName!==t)&&(o.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),o.skillName=t,o.requiredMcpTools=[...new Set(r)],o.lastActivityAt=Date.now(),this.persist(o),o}get(e){let t=e.trim();if(!t)return null;let r=this.sessions.get(t);if(r)return this.replayEvidenceJournal(r),r;let o=this.snapshotPath(t);if(!existsSync$1(o))return null;try{let i=JSON.parse(readFileSync$1(o,"utf8"));return i.sessionId!==t||i.projectRoot!==this.projectRoot?null:(i.requiredMcpTools=Array.isArray(i.requiredMcpTools)?i.requiredMcpTools:[],i.evidenceObligations=j(i.evidenceObligations),i.evidenceDegradations=F(i.evidenceDegradations),i.evidenceOutcomes=N(i.evidenceOutcomes),this.replayEvidenceJournal(i),this.sessions.set(t,i),i)}catch{return null}}completeExecution(e){let t=this.get(e);if(!t)return null;let r=structuredClone(t);return delete t.executionId,delete t.skillName,t.requiredMcpTools=[],t.lastActivityAt=Date.now(),this.persist(t),r}addEvidenceObligation(e,t,r=Date.now(),o){let i=this.registerSession(e),a=(o?void 0:i.evidenceObligations.find(d=>d.contractId===t.id))?.obligationId??fe(t.id,o,r);this.appendEvidenceEvent(e,{kind:"add",obligationId:a,contractId:t.id,at:r,contract:t},`add\0${a}`),this.replayEvidenceJournal(i);let c=i.evidenceObligations.find(d=>d.obligationId===a);return c?(i.lastActivityAt=Date.now(),this.persist(i),structuredClone(c)):null}listEvidenceObligations(e){return (this.get(e)?.evidenceObligations??[]).map(t=>structuredClone(t))}markEvidenceCorrection(e,t,r,o,i=Date.now()){let s=this.get(e),a=s?.evidenceObligations.find(l=>l.obligationId===t);if(!s||!a)return null;let c=/^[a-f0-9]{64}$/.test(o)?o:"";if(!c)return null;this.appendEvidenceEvent(e,{kind:"correction",obligationId:t,contractId:a.contractId,at:i,fingerprint:c,violations:r.slice(0,16).map(l=>l.slice(0,240))},`correction\0${t}\0${c}`),this.replayEvidenceJournal(s),s.lastActivityAt=i,this.persist(s);let d=s.evidenceObligations.find(l=>l.obligationId===t);return d?structuredClone(d):null}resolveEvidenceObligation(e,t){let r=this.get(e);if(!r)return false;let o=r.evidenceObligations.find(s=>s.obligationId===t);if(!o)return false;let i=Date.now();return this.appendEvidenceEvent(e,{kind:"resolve",obligationId:t,contractId:o.contractId,at:i},`resolve\0${t}`),this.replayEvidenceJournal(r),r.lastActivityAt=i,this.persist(r),true}degradeEvidenceObligation(e,t,r,o=Date.now()){let i=this.get(e),s=i?.evidenceObligations.find(c=>c.obligationId===t);if(!i||!s)return false;let a=r.slice(0,240);return this.appendEvidenceEvent(e,{kind:"degrade",obligationId:t,contractId:s.contractId,at:o,reason:a},`degrade\0${t}\0${a}`),this.replayEvidenceJournal(i),i.lastActivityAt=o,this.persist(i),true}removeSession(e){let t=e.trim();t&&(this.sessions.delete(t),rmSync(this.snapshotPath(t),{force:true}),rmSync(this.evidenceJournalDir(t),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(e){return join$1(this.sessionsDir,`${P(e)}.json`)}evidenceJournalDir(e){return join$1(this.sessionsDir,"evidence-journal",P(e))}appendEvidenceEvent(e,t,r){let o=this.evidenceJournalDir(e);mkdirSync$1(o,{recursive:true,mode:448});let i=createHash$1("sha256").update(r).digest("hex"),s=join$1(o,`${t.kind}-${i}.json`);if(existsSync$1(s))return;let a=join$1(o,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync$1(a,JSON.stringify(t),{mode:384});try{linkSync(a,s);}catch(c){if(c.code!=="EEXIST")throw c}finally{rmSync(a,{force:true});}}replayEvidenceJournal(e){e.evidenceObligations=j(e.evidenceObligations),e.evidenceDegradations=F(e.evidenceDegradations),e.evidenceOutcomes=N(e.evidenceOutcomes);let t=this.evidenceJournalDir(e.sessionId);if(!existsSync$1(t))return;let r;try{r=readdirSync(t).filter(i=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(i)).slice(0,4096);}catch{return}let o=r.flatMap(i=>{try{let s=readFileSync$1(join$1(t,i),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=ye(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||L(i.kind)-L(s.kind));for(let i of o)this.applyEvidenceEvent(e,i);e.evidenceObligations=e.evidenceObligations.slice(-8),e.evidenceDegradations=e.evidenceDegradations.slice(-20),e.evidenceOutcomes=e.evidenceOutcomes.slice(-20);}applyEvidenceEvent(e,t){let r=e.evidenceOutcomes.find(s=>s.obligationId===t.obligationId);if(t.kind==="add"){if(r)return;let s=e.evidenceObligations.find(a=>a.obligationId===t.obligationId);s?(s.contract=t.contract,s.promptedAt=Math.min(s.promptedAt,t.at)):e.evidenceObligations.push({obligationId:t.obligationId,contractId:t.contractId,contract:t.contract,promptedAt:t.at,attempt:0,correctionRequested:false,violations:[]});return}let o=e.evidenceObligations.find(s=>s.obligationId===t.obligationId);if(t.kind==="correction"){if(!o||r||o.correctionFingerprint===t.fingerprint)return;o.attempt+=1,o.correctionRequested=true,o.correctionRequestedAt=t.at,o.correctionFingerprint=t.fingerprint,o.violations=t.violations;return}let i=o?.attempt??0;e.evidenceObligations=e.evidenceObligations.filter(s=>s.obligationId!==t.obligationId),!r&&(t.kind==="degrade"&&e.evidenceDegradations.push({obligationId:t.obligationId,contractId:t.contractId,reason:t.reason,degradedAt:t.at,attempt:i}),e.evidenceOutcomes.push({obligationId:t.obligationId,contractId:t.contractId,status:t.kind==="resolve"?"resolved":"degraded",completedAt:t.at,attempt:i,...t.kind==="degrade"?{reason:t.reason}:{}}));}persist(e){mkdirSync$1(this.sessionsDir,{recursive:true,mode:448});let t=this.snapshotPath(e.sessionId),r=`${t}.${process.pid}.${randomUUID()}.tmp`;writeFileSync$1(r,JSON.stringify(e),{mode:384}),renameSync$1(r,t);}};function j(n){return Array.isArray(n)?n.flatMap(e=>{if(!e||typeof e!="object")return [];let t=e;if(typeof t.contractId!="string"||t.contractId.length===0||t.contractId.length>128||typeof t.promptedAt!="number"||typeof t.attempt!="number"||typeof t.correctionRequested!="boolean"||!Array.isArray(t.violations)||!U(t.contract))return [];let r=typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:H(t.contractId),o=typeof t.correctionTranscriptHash=="string"?t.correctionTranscriptHash:void 0,i=t.correctionFingerprint??o;return i!==void 0&&!/^[a-f0-9]{64}$/.test(i)?[]:[{...t,obligationId:r,correctionFingerprint:i}]}).slice(-8):[]}function F(n){return Array.isArray(n)?n.filter(e=>{if(!e||typeof e!="object")return false;let t=e;return typeof t.obligationId=="string"&&typeof t.contractId=="string"&&typeof t.reason=="string"&&typeof t.degradedAt=="number"&&typeof t.attempt=="number"}).slice(-20):[]}function N(n){return Array.isArray(n)?n.filter(e=>{if(!e||typeof e!="object")return false;let t=e;return typeof t.obligationId=="string"&&typeof t.contractId=="string"&&(t.status==="resolved"||t.status==="degraded")&&typeof t.completedAt=="number"&&typeof t.attempt=="number"&&(t.reason===void 0||typeof t.reason=="string")}).slice(-20):[]}function ye(n){if(!n||typeof n!="object")return null;let e=n;if(!["add","correction","resolve","degrade"].includes(e.kind??"")||typeof e.contractId!="string"||e.contractId.length>128||typeof e.at!="number")return null;let t=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:H(e.contractId);if(e.kind==="add")return U(e.contract)?{...e,obligationId:t}:null;if(e.kind==="correction"){let r=typeof e.fingerprint=="string"?e.fingerprint:e.transcriptHash;return typeof r=="string"&&/^[a-f0-9]{64}$/.test(r)&&Array.isArray(e.violations)&&e.violations.every(o=>typeof o=="string"&&o.length<=240)?{...e,obligationId:t,fingerprint:r}:null}return e.kind==="resolve"?{...e,obligationId:t}:typeof e.reason=="string"&&e.reason.length<=240?{...e,obligationId:t}:null}function L(n){return n==="add"?0:n==="correction"?1:2}function U(n){if(!n||typeof n!="object")return false;let e=n,t=e.requiredSections,r=e.prohibitedClaims;return e.version==="1.0"&&typeof e.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(e.id)&&typeof e.runtimeProfilingOccurred=="boolean"&&typeof e.samplingEvidenceOccurred=="boolean"&&Array.isArray(t)&&t.length===3&&t[0]==="\u5DE5\u5177\u53D1\u73B0"&&t[1]==="\u6A21\u578B\u5047\u8BBE"&&t[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(r)&&r.length<=16&&r.every(o=>typeof o=="string"&&o.length<=128)&&typeof e.canonicalReport=="string"&&Buffer.byteLength(e.canonicalReport,"utf8")<=48*1024&&!!e.correctionPolicy&&e.correctionPolicy.maxAttempts===1&&e.correctionPolicy.repeatedViolation==="fail_open"}function x(n,e,t){try{let r=openGlobalDevFlowDatabase();try{r.insertEvent({kind:n,timestamp:Date.now(),duration:t,success:e.success!==!1,metadata:e});}finally{r.close();}}catch{}}var ke=getLocalApiKey(),C=join(homedir(),".devflow","errors");async function _(n,e,t={}){let r=t.endpoint??resolveRuntimeEndpoint().url,o=t.timeout??1500,i=t.durableMirror??true,s=t.maxRetries??(i?0:2),a=t.circuitBreaker??true,c=acquireRuntimeHttpCircuit(r,n);if(a&&!c.allowed)return {delivered:false,suppressed:true,fallbackReason:c.state.fallbackReason};let d;for(let u=0;u<=s;u+=1)try{return await Re(r,n,e,o),a&&registerRuntimeHttpSuccess(r,n).transitioned&&x("http_circuit_transition",{endpoint:r,path:new URL(n,r).pathname,previous:c.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(m){d=m instanceof Error?m:new Error(String(m)),u<s&&await Ee(Math.min(100*2**u,1e3));}if(!d)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return G(n,d),{delivered:false,suppressed:false,fallbackReason:d.message};let l=registerRuntimeHttpFailure(r,n,t.fallbackReason??(i?"local_durable_mirror":"http_delivery_failed"));return l.transitioned&&(G(n,d),x("http_circuit_transition",{endpoint:r,path:new URL(n,r).pathname,previous:c.state.status,status:"open",failures:l.state.failures,openUntil:l.state.openUntil,fallbackReason:l.state.fallbackReason})),{delivered:false,suppressed:false,fallbackReason:l.state.fallbackReason}}function Re(n,e,t,r){return new Promise((o,i)=>{let s=JSON.stringify(t),a=new URL(e,n),c=false,d=u=>{c||(c=true,u?i(u):o());},l=request({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":ke,"Content-Length":Buffer.byteLength(s)},timeout:r},u=>{u.on("error",d),u.on("end",()=>{let m=u.statusCode??0;d(m>=200&&m<300?void 0:new Error(`HTTP ${m}`));}),u.resume();});l.on("error",d),l.on("timeout",()=>l.destroy(new Error(`HTTP mirror timed out after ${r}ms`))),l.write(s),l.end();})}function G(n,e){try{existsSync(C)||mkdirSync(C,{recursive:!0}),appendFileSync(join(C,"http-errors.log"),`${new Date().toISOString()} | ${n} | ${e.message}
2
- `);}catch{}}function Ee(n){return new Promise(e=>setTimeout(e,n))}function Y(n,e){let t=Oe(n);mkdirSync(t,{recursive:true,mode:448});let r=join(t,`${e.receiptId}.json`);if(existsSync(r))return e.receiptId;let o=`${r}.${process.pid}.tmp`;writeFileSync(o,JSON.stringify(e),{mode:384});try{renameSync(o,r);}catch(i){try{unlinkSync(o);}catch{}if(!existsSync(r))throw i}return e.receiptId}function Oe(n){return join(S(n),"session-finalize-pending")}var Fe=512*1024,Ne=500;var Le=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function ee(n){let e=n.runtimeStore??new y(n.projectRoot),t=e.listEvidenceObligations(n.sessionId);if(t.length===0)return null;let r=Ke(n.transcriptPath,t);if(!r.answer){let s=r.degradationReason??"transcript_answer_unavailable";for(let a of t)e.degradeEvidenceObligation(n.sessionId,a.obligationId,s);return null}let o=r.fingerprint;if(!o){for(let s of t)e.degradeEvidenceObligation(n.sessionId,s.obligationId,"transcript_identity_unavailable");return null}let i=[];for(let s of t){let a=He(r.answer,[s]);if(a.length===0){e.resolveEvidenceObligation(n.sessionId,s.obligationId);continue}if(!s.correctionFingerprint){e.markEvidenceCorrection(n.sessionId,s.obligationId,a,o),i.push({obligation:s,violations:a});continue}if(s.correctionFingerprint===o){i.push({obligation:s,violations:a});continue}e.degradeEvidenceObligation(n.sessionId,s.obligationId,"evidence_contract_unresolved");}return i.length===0?null:ze(i)}function ze(n){let e=[...new Set(n.flatMap(r=>r.violations))],t=[...new Map(n.map(r=>[r.obligation.contractId,r.obligation.contract.canonicalReport])).values()];return {decision:"block",reason:["DevFlow evidence contract violation. Correct the final performance answer once before stopping.",`Violations: ${e.join("; ")}`,"Use this canonical report (you may add clearly labeled hypotheses or runtime verification steps, but no unsupported measured claims):",t.join(`
1
+ import {getLocalApiKey,resolveRuntimeEndpoint,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,getProjectStateDir}from'@devflow-tools/sdk';import {existsSync as existsSync$1,readFileSync as readFileSync$1,rmSync,mkdirSync as mkdirSync$1,writeFileSync as writeFileSync$1,linkSync,readdirSync,renameSync as renameSync$1}from'fs';import {join as join$1}from'path';import {randomUUID,createHash as createHash$1}from'crypto';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import'@devflow-tools/memory-engine';import'os';import {request}from'node:http';import {mkdirSync,existsSync,writeFileSync,renameSync,unlinkSync,readFileSync,openSync,constants,fstatSync,closeSync,appendFileSync,lstatSync,readSync}from'node:fs';import {join,resolve}from'node:path';import {homedir}from'node:os';import {createHash}from'node:crypto';function v(n){return n??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function S(n){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(v(n))}function j(n){return Buffer.from(n,"utf8").toString("base64url")}function be(n,e,t){let r=e?.trim();if(r){let o=/^[a-zA-Z0-9:._-]{1,192}$/.test(r)?r:`tool-${createHash$1("sha256").update(r.slice(0,1024)).digest("hex").slice(0,32)}`;return `${n}:${o}`}return `${n}:legacy-${t}-${randomUUID().slice(0,8)}`}function U(n){return `${n}:legacy-journal`}var y=class{constructor(e){this.projectRoot=e;this.sessions=new Map;this.sessionsDir=join$1(S(e),"hook-sessions");}registerSession(e){let t=e.trim();if(!t)throw new Error("session_id_required");let r=this.get(t);if(r)return r.lastActivityAt=Date.now(),this.persist(r),r;let o=Date.now(),i={sessionId:t,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:o,lastActivityAt:o};return this.sessions.set(t,i),this.persist(i),i}startExecution(e,t,r){let o=this.registerSession(e);return (!o.executionId||o.skillName!==t)&&(o.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),o.skillName=t,o.requiredMcpTools=[...new Set(r)],o.lastActivityAt=Date.now(),this.persist(o),o}get(e){let t=e.trim();if(!t)return null;let r=this.sessions.get(t);if(r)return this.replayEvidenceJournal(r),r;let o=this.snapshotPath(t);if(!existsSync$1(o))return null;try{let i=JSON.parse(readFileSync$1(o,"utf8"));return i.sessionId!==t||i.projectRoot!==this.projectRoot?null:(i.requiredMcpTools=Array.isArray(i.requiredMcpTools)?i.requiredMcpTools:[],i.evidenceObligations=F(i.evidenceObligations),i.evidenceDegradations=N(i.evidenceDegradations),i.evidenceOutcomes=L(i.evidenceOutcomes),this.replayEvidenceJournal(i),this.sessions.set(t,i),i)}catch{return null}}completeExecution(e){let t=this.get(e);if(!t)return null;let r=structuredClone(t);return delete t.executionId,delete t.skillName,t.requiredMcpTools=[],t.lastActivityAt=Date.now(),this.persist(t),r}addEvidenceObligation(e,t,r=Date.now(),o){let i=this.registerSession(e),a=(o?void 0:i.evidenceObligations.find(d=>d.contractId===t.id))?.obligationId??be(t.id,o,r);this.appendEvidenceEvent(e,{kind:"add",obligationId:a,contractId:t.id,at:r,contract:t},`add\0${a}`),this.replayEvidenceJournal(i);let c=i.evidenceObligations.find(d=>d.obligationId===a);return c?(i.lastActivityAt=Date.now(),this.persist(i),structuredClone(c)):null}listEvidenceObligations(e){return (this.get(e)?.evidenceObligations??[]).map(t=>structuredClone(t))}markEvidenceCorrection(e,t,r,o,i=Date.now()){let s=this.get(e),a=s?.evidenceObligations.find(l=>l.obligationId===t);if(!s||!a)return null;let c=/^[a-f0-9]{64}$/.test(o)?o:"";if(!c)return null;this.appendEvidenceEvent(e,{kind:"correction",obligationId:t,contractId:a.contractId,at:i,fingerprint:c,violations:r.slice(0,16).map(l=>l.slice(0,240))},`correction\0${t}\0${c}`),this.replayEvidenceJournal(s),s.lastActivityAt=i,this.persist(s);let d=s.evidenceObligations.find(l=>l.obligationId===t);return d?structuredClone(d):null}resolveEvidenceObligation(e,t){let r=this.get(e);if(!r)return false;let o=r.evidenceObligations.find(s=>s.obligationId===t);if(!o)return false;let i=Date.now();return this.appendEvidenceEvent(e,{kind:"resolve",obligationId:t,contractId:o.contractId,at:i},`resolve\0${t}`),this.replayEvidenceJournal(r),r.lastActivityAt=i,this.persist(r),true}degradeEvidenceObligation(e,t,r,o=Date.now()){let i=this.get(e),s=i?.evidenceObligations.find(c=>c.obligationId===t);if(!i||!s)return false;let a=r.slice(0,240);return this.appendEvidenceEvent(e,{kind:"degrade",obligationId:t,contractId:s.contractId,at:o,reason:a},`degrade\0${t}\0${a}`),this.replayEvidenceJournal(i),i.lastActivityAt=o,this.persist(i),true}removeSession(e){let t=e.trim();t&&(this.sessions.delete(t),rmSync(this.snapshotPath(t),{force:true}),rmSync(this.evidenceJournalDir(t),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(e){return join$1(this.sessionsDir,`${j(e)}.json`)}evidenceJournalDir(e){return join$1(this.sessionsDir,"evidence-journal",j(e))}appendEvidenceEvent(e,t,r){let o=this.evidenceJournalDir(e);mkdirSync$1(o,{recursive:true,mode:448});let i=createHash$1("sha256").update(r).digest("hex"),s=join$1(o,`${t.kind}-${i}.json`);if(existsSync$1(s))return;let a=join$1(o,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync$1(a,JSON.stringify(t),{mode:384});try{linkSync(a,s);}catch(c){if(c.code!=="EEXIST")throw c}finally{rmSync(a,{force:true});}}replayEvidenceJournal(e){e.evidenceObligations=F(e.evidenceObligations),e.evidenceDegradations=N(e.evidenceDegradations),e.evidenceOutcomes=L(e.evidenceOutcomes);let t=this.evidenceJournalDir(e.sessionId);if(!existsSync$1(t))return;let r;try{r=readdirSync(t).filter(i=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(i)).slice(0,4096);}catch{return}let o=r.flatMap(i=>{try{let s=readFileSync$1(join$1(t,i),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=ve(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||z(i.kind)-z(s.kind));for(let i of o)this.applyEvidenceEvent(e,i);e.evidenceObligations=e.evidenceObligations.slice(-8),e.evidenceDegradations=e.evidenceDegradations.slice(-20),e.evidenceOutcomes=e.evidenceOutcomes.slice(-20);}applyEvidenceEvent(e,t){let r=e.evidenceOutcomes.find(s=>s.obligationId===t.obligationId);if(t.kind==="add"){if(r)return;let s=e.evidenceObligations.find(a=>a.obligationId===t.obligationId);s?(s.contract=t.contract,s.promptedAt=Math.min(s.promptedAt,t.at)):e.evidenceObligations.push({obligationId:t.obligationId,contractId:t.contractId,contract:t.contract,promptedAt:t.at,attempt:0,correctionRequested:false,violations:[]});return}let o=e.evidenceObligations.find(s=>s.obligationId===t.obligationId);if(t.kind==="correction"){if(!o||r||o.correctionFingerprint===t.fingerprint)return;o.attempt+=1,o.correctionRequested=true,o.correctionRequestedAt=t.at,o.correctionFingerprint=t.fingerprint,o.violations=t.violations;return}let i=o?.attempt??0;e.evidenceObligations=e.evidenceObligations.filter(s=>s.obligationId!==t.obligationId),!r&&(t.kind==="degrade"&&e.evidenceDegradations.push({obligationId:t.obligationId,contractId:t.contractId,reason:t.reason,degradedAt:t.at,attempt:i}),e.evidenceOutcomes.push({obligationId:t.obligationId,contractId:t.contractId,status:t.kind==="resolve"?"resolved":"degraded",completedAt:t.at,attempt:i,...t.kind==="degrade"?{reason:t.reason}:{}}));}persist(e){mkdirSync$1(this.sessionsDir,{recursive:true,mode:448});let t=this.snapshotPath(e.sessionId),r=`${t}.${process.pid}.${randomUUID()}.tmp`;writeFileSync$1(r,JSON.stringify(e),{mode:384}),renameSync$1(r,t);}};function F(n){return Array.isArray(n)?n.flatMap(e=>{if(!e||typeof e!="object")return [];let t=e;if(typeof t.contractId!="string"||t.contractId.length===0||t.contractId.length>128||typeof t.promptedAt!="number"||typeof t.attempt!="number"||typeof t.correctionRequested!="boolean"||!Array.isArray(t.violations)||!q(t.contract))return [];let r=typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:U(t.contractId),o=typeof t.correctionTranscriptHash=="string"?t.correctionTranscriptHash:void 0,i=t.correctionFingerprint??o;return i!==void 0&&!/^[a-f0-9]{64}$/.test(i)?[]:[{...t,obligationId:r,correctionFingerprint:i}]}).slice(-8):[]}function N(n){return Array.isArray(n)?n.filter(e=>{if(!e||typeof e!="object")return false;let t=e;return typeof t.obligationId=="string"&&typeof t.contractId=="string"&&typeof t.reason=="string"&&typeof t.degradedAt=="number"&&typeof t.attempt=="number"}).slice(-20):[]}function L(n){return Array.isArray(n)?n.filter(e=>{if(!e||typeof e!="object")return false;let t=e;return typeof t.obligationId=="string"&&typeof t.contractId=="string"&&(t.status==="resolved"||t.status==="degraded")&&typeof t.completedAt=="number"&&typeof t.attempt=="number"&&(t.reason===void 0||typeof t.reason=="string")}).slice(-20):[]}function ve(n){if(!n||typeof n!="object")return null;let e=n;if(!["add","correction","resolve","degrade"].includes(e.kind??"")||typeof e.contractId!="string"||e.contractId.length>128||typeof e.at!="number")return null;let t=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:U(e.contractId);if(e.kind==="add")return q(e.contract)?{...e,obligationId:t}:null;if(e.kind==="correction"){let r=typeof e.fingerprint=="string"?e.fingerprint:e.transcriptHash;return typeof r=="string"&&/^[a-f0-9]{64}$/.test(r)&&Array.isArray(e.violations)&&e.violations.every(o=>typeof o=="string"&&o.length<=240)?{...e,obligationId:t,fingerprint:r}:null}return e.kind==="resolve"?{...e,obligationId:t}:typeof e.reason=="string"&&e.reason.length<=240?{...e,obligationId:t}:null}function z(n){return n==="add"?0:n==="correction"?1:2}function q(n){if(!n||typeof n!="object")return false;let e=n,t=e.requiredSections,r=e.prohibitedClaims;return e.version==="1.0"&&typeof e.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(e.id)&&typeof e.runtimeProfilingOccurred=="boolean"&&typeof e.samplingEvidenceOccurred=="boolean"&&Array.isArray(t)&&t.length===3&&t[0]==="\u5DE5\u5177\u53D1\u73B0"&&t[1]==="\u6A21\u578B\u5047\u8BBE"&&t[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(r)&&r.length<=16&&r.every(o=>typeof o=="string"&&o.length<=128)&&typeof e.canonicalReport=="string"&&Buffer.byteLength(e.canonicalReport,"utf8")<=48*1024&&!!e.correctionPolicy&&e.correctionPolicy.maxAttempts===1&&e.correctionPolicy.repeatedViolation==="fail_open"}function x(n,e,t){try{let r=openGlobalDevFlowDatabase();try{r.insertEvent({kind:n,timestamp:Date.now(),duration:t,success:e.success!==!1,metadata:e});}finally{r.close();}}catch{}}var xe=getLocalApiKey(),C=join(homedir(),".devflow","errors");async function _(n,e,t={}){let r=t.endpoint??resolveRuntimeEndpoint().url,o=t.timeout??1500,i=t.durableMirror??true,s=t.maxRetries??(i?0:2),a=t.circuitBreaker??true,c=acquireRuntimeHttpCircuit(r,n);if(a&&!c.allowed)return {delivered:false,suppressed:true,fallbackReason:c.state.fallbackReason};let d;for(let u=0;u<=s;u+=1)try{return await Ce(r,n,e,o),a&&registerRuntimeHttpSuccess(r,n).transitioned&&x("http_circuit_transition",{endpoint:r,path:new URL(n,r).pathname,previous:c.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(m){d=m instanceof Error?m:new Error(String(m)),u<s&&await Me(Math.min(100*2**u,1e3));}if(!d)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return V(n,d),{delivered:false,suppressed:false,fallbackReason:d.message};let l=registerRuntimeHttpFailure(r,n,t.fallbackReason??(i?"local_durable_mirror":"http_delivery_failed"));return l.transitioned&&(V(n,d),x("http_circuit_transition",{endpoint:r,path:new URL(n,r).pathname,previous:c.state.status,status:"open",failures:l.state.failures,openUntil:l.state.openUntil,fallbackReason:l.state.fallbackReason})),{delivered:false,suppressed:false,fallbackReason:l.state.fallbackReason}}function Ce(n,e,t,r){return new Promise((o,i)=>{let s=JSON.stringify(t),a=new URL(e,n),c=false,d=u=>{c||(c=true,u?i(u):o());},l=request({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":xe,"Content-Length":Buffer.byteLength(s)},timeout:r},u=>{u.on("error",d),u.on("end",()=>{let m=u.statusCode??0;d(m>=200&&m<300?void 0:new Error(`HTTP ${m}`));}),u.resume();});l.on("error",d),l.on("timeout",()=>l.destroy(new Error(`HTTP mirror timed out after ${r}ms`))),l.write(s),l.end();})}function V(n,e){try{existsSync(C)||mkdirSync(C,{recursive:!0}),appendFileSync(join(C,"http-errors.log"),`${new Date().toISOString()} | ${n} | ${e.message}
2
+ `);}catch{}}function Me(n){return new Promise(e=>setTimeout(e,n))}function Z(n,e){let t=$e(n);mkdirSync(t,{recursive:true,mode:448});let r=join(t,`${e.receiptId}.json`);if(existsSync(r))return e.receiptId;let o=`${r}.${process.pid}.tmp`;writeFileSync(o,JSON.stringify(e),{mode:384});try{renameSync(o,r);}catch(i){try{unlinkSync(o);}catch{}if(!existsSync(r))throw i}return e.receiptId}function $e(n){return join(S(n),"session-finalize-pending")}var ze=512*1024,He=500;var Ue=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function te(n){let e=n.runtimeStore??new y(n.projectRoot),t=e.listEvidenceObligations(n.sessionId);if(t.length===0)return null;let r=re(n.transcriptPath,t);if(!r.answer){let s=r.degradationReason??"transcript_answer_unavailable";for(let a of t)e.degradeEvidenceObligation(n.sessionId,a.obligationId,s);return null}let o=r.fingerprint;if(!o){for(let s of t)e.degradeEvidenceObligation(n.sessionId,s.obligationId,"transcript_identity_unavailable");return null}let i=[];for(let s of t){let a=Je(r.answer,[s]);if(a.length===0){e.resolveEvidenceObligation(n.sessionId,s.obligationId);continue}if(!s.correctionFingerprint){e.markEvidenceCorrection(n.sessionId,s.obligationId,a,o),i.push({obligation:s,violations:a});continue}if(s.correctionFingerprint===o){i.push({obligation:s,violations:a});continue}e.degradeEvidenceObligation(n.sessionId,s.obligationId,"evidence_contract_unresolved");}return i.length===0?null:qe(i)}function qe(n){let e=[...new Set(n.flatMap(r=>r.violations))],t=[...new Map(n.map(r=>[r.obligation.contractId,r.obligation.contract.canonicalReport])).values()];return {decision:"block",reason:["DevFlow evidence contract violation. Correct the final performance answer once before stopping.",`Violations: ${e.join("; ")}`,"Use this canonical report (you may add clearly labeled hypotheses or runtime verification steps, but no unsupported measured claims):",t.join(`
3
3
 
4
4
  ---
5
5
 
6
6
  `)].join(`
7
7
 
8
- `)}}function He(n,e){let t=new Set,r=new Set(e.flatMap(c=>c.contract.requiredSections)),o=Ue(n.split(/\r?\n/)),i=Qe(o.headingLines);for(let c of r)i.found.has(c)||t.add(`missing_section:${c}`);if(e.every(c=>c.contract.runtimeProfilingOccurred))return [...t];let a=e.every(c=>c.contract.samplingEvidenceOccurred);for(let c=0;c<o.claimLines.length;c++){let d=o.claimLines[c].trim();if(!d||Je(d))continue;let l=i.byLine.get(c);for(let u of Xe(d))Be(u,l,a,t);}return [...t]}function Ue(n){let e=false,t=[],r=[];for(let o of n){if(/^\s*```/.test(o)){e=!e,t.push(""),r.push(o.replace(/^\s*```+[^\s`]*/,"").replace(/```+\s*$/,"").trim());continue}t.push(e?"":o.replace(/`[^`]*`/g,"").trim()),r.push(o.replace(/`([^`]*)`/g,(i,s)=>qe(s)?"":s).trim());}return {headingLines:t,claimLines:r}}function qe(n){let e=n.trim().slice(0,256);return !e||/\s/.test(e)||n.trim().length>256?false:/^[A-Za-z_$][\w$.-]*$/.test(e)||/^(['"])[^'"`]*\1$/.test(e)}function Je(n){if(n.length>2048)return false;let e=n.replace(/^\s*(?:[-*+]|\d+[.)])\s+/,"").trim();return e?We(e)||/^(?:\/\/|\/\*|\*\/|\*\s|#!)/.test(e)||/^(?:import|export|const|let|var|function|class|type|interface|enum|namespace|declare)\b/.test(e)||/^(?:async\s+)?(?:function\s+)?[A-Za-z_$][\w$]*\s*=\s*/.test(e)||/^[A-Za-z_$][\w$.[\]'"-]*\s*(?:=|\+=|-=|\*=|\/=|\?\?=|&&=|\|\|=)\s*/.test(e)||/^[A-Za-z_$'"-][\w$.'"-]*\s*:\s*[^:]+[,}]?$/.test(e)||/=>/.test(e)||/^(?:await\s+|return\s+|throw\s+|new\s+)?[A-Za-z_$][\w$.]*\s*\([^)]*\)\s*;?$/.test(e)||/^(['"])[\s\S]*\1[;,]?$/.test(e)?true:/[{}()[\]=<>]\s*;?$/.test(e)&&/(?:;|=>|\b(?:return|new|await)\b)/.test(e):false}function We(n){if(n.length>1024)return false;let e="(?:--[A-Za-z0-9_-]+|(?:-webkit-|-moz-|-ms-)?(?:animation(?:-[a-z-]+)?|transition(?:-[a-z-]+)?|opacity|transform|will-change|contain|content-visibility|display|position|top|right|bottom|left|width|height|min-(?:width|height)|max-(?:width|height)|margin(?:-[a-z]+)?|padding(?:-[a-z]+)?|color|background(?:-[a-z-]+)?|border(?:-[a-z-]+)?|font(?:-[a-z-]+)?|line-height|z-index|overflow(?:-[xy])?))";return new RegExp(`^${e}\\s*:\\s*\\S[^;]{0,960};$`,"i").test(n)}function Be(n,e,t,r){let o=/\bP0\b/gi;for(let p of n.matchAll(o))Q(n,p.index??0,p[0],"p0")||r.add("unsupported_p0_severity");let i=/(?:中高|高)(?:风险|优先级)|严重(?:问题|风险)|\bhigh[- ](?:risk|severity|priority)\b/gi;for(let p of n.matchAll(i))Q(n,p.index??0,p[0],"high")||r.add("unsupported_high_severity");let s=/(?:性能)?瓶颈|卡顿|掉帧|CPU\s*(?:热点|尖峰)|\bbottleneck\b|\bjank\b|\bdropped frames?\b|\bCPU hotspot\b/gi;for(let p of n.matchAll(s))Ve(n,p.index??0,p[0])||(/(?:瓶颈|bottleneck)/i.test(p[0])?r.add("unsupported_confirmed_bottleneck"):r.add("unsupported_runtime_effect"));let a=/\b\d{1,3}(?:\.\d+)?\s*%/.test(n),c=/(?:预计|预期|估计|提升|降低|减少|节省|改善|收益|加速|improve|reduce|faster|gain|benefit|speedup|expected|estimated)/i.test(n),d=/\b\d+(?:\.\d+)?\s*[x×]\b/i.test(n);(a||d)&&c&&r.add(a?"unsupported_benefit_percentage":"unsupported_performance_number");let l=/\b\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:ms|fps|hz)\b/i.test(n)||/\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:毫秒|次\s*\/\s*秒|帧)/.test(n),u=e==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&/(?:采集|记录|测量|收集|collect|measure|record)/i.test(n)&&!/(?:预计|预期|估计|约|大约|通常|平均|每(?:隔)?|达到|提升|降低|减少|节省|改善|improve|reduce|faster|expected|estimated|average|typically|every)/i.test(n);a&&!c&&!u&&r.add("unsupported_benefit_percentage"),l&&!u&&r.add("unsupported_performance_number");let m=/(?:requestAnimationFrame|\bRAF\b)/i.test(n),f=/(?:建议|应该|应当|使用|添加|采用|切换|包裹|优化|节流|\buse\b|\badopt\b|\brecommend\b|\bswitch\b|\bwrap\b|\bthrottl(?:e|ing)\b)/i.test(n),g=/(?:不要|不得|不能|不应|避免|不建议|不推荐).{0,16}(?:使用|采用|添加|切换|包裹|节流)?.{0,8}(?:requestAnimationFrame|\bRAF\b)|\b(?:do\s+not|don't|never|avoid)\s+(?:use|adopt|recommend|switch|wrap|throttle)?.{0,8}(?:requestAnimationFrame|RAF)\b/i.test(n);m&&f&&!g&&!t&&r.add("raf_without_sampling_evidence");}function Q(n,e,t,r){let o=n.slice(Math.max(0,e-64),e),i=n.slice(e+t.length,e+t.length+28),s=Ge(o),a=/^(?:\s+)?(?:未发现|不存在|并不存在|未被发现)/.test(i)||/^(?:\s+)?(?:was\s+|is\s+)?not found\b/i.test(i);return s||a?true:r==="high"?/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?)\s*(?:任何|明确的)?\s*P0\s*(?:或|和|及|、)\s*$/i.test(o)||/\b(?:no evidence (?:of|for)|no)\s+P0\s+(?:or|and)\s+$/i.test(o):false}function Ge(n){if(/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?|不是|并非|未被)\s*(?:任何|明确的)?\s*(?:(?:问题|发现|证据|项|内容)\s*)?(?:(?:属于|(?:被)?(?:评|判定|认定|标记|列|视|定|归(?:类)?)为)\s*)?$/i.test(n)||/\b(?:no evidence (?:of|for)|no|not|isn't|is\s+not)\s+(?:an?\s+)?(?:(?:issues?|findings?|evidence|items?)\s+)?(?:(?:classified|rated|marked|labelled|labeled)(?:\s+as)?\s+)?$/i.test(n))return true;let t=/(?:不得|不能|不应|不宜|不要)\s*(?:被\s*)?(?:(?:直接|轻易|简单|明确|正式|合理|据此|当前|目前)\s*){0,2}(?:(?:评|判定|认定|标记|列|视|定|归(?:类)?)为|属于)\s*$/i,r=/\b(?:cannot|can't|must not|should not|shouldn't|do not|don't)\s+(?:(?:reasonably|directly|formally|currently)\s+){0,2}(?:be\s+)?(?:classified|labeled|labelled|rated|marked)(?:\s+as)?\s+$/i;return t.test(n)||r.test(n)}function Ve(n,e,t){let r=n.slice(Math.max(0,e-40),e),o=n.slice(e+t.length,e+t.length+32),i=/(?:是否|待验证|候选|可能|潜在|未观察到|没有观察到|未发现|不存在|无证据(?:表明)?|不能(?:据此)?确认|尚未(?:确认|证明)|验证(?:是否)?|测量(?:是否)?|采集|记录|收集).{0,16}$/i.test(r)||/\b(?:whether|measure|validate|candidate|potential|possible|may|might|no|no evidence(?: of| for)?|not observed|unobserved|collect|record).{0,18}$/i.test(r),s=/^(?:是否|有待验证|待验证|候选|可能|潜在|指标|需要(?:验证|测量)|需(?:验证|测量))/.test(o)||/^(?:\s+)?(?:candidate|potential|possible|metric|metrics|to (?:measure|validate)|needs? (?:measurement|validation)|is (?:a )?(?:candidate|potential))/i.test(o);return i||s}function Xe(n){return n.split(/(?:[。!?;;,,]|\b(?:but|however|yet|nevertheless|nonetheless)\b|但是|但|然而|却|不过|可是)/i).map(e=>e.trim()).filter(Boolean)}function Ke(n,e){if(!n||n.length>4096)return {degradationReason:"transcript_path_missing"};let t;try{let r=lstatSync(n);if(!r.isFile()||r.isSymbolicLink())return {degradationReason:"transcript_path_unsafe"};t=openSync(n,constants.O_RDONLY|(constants.O_NOFOLLOW??0));let o=fstatSync(t);if(!o.isFile()||o.dev!==r.dev||o.ino!==r.ino)return {degradationReason:"transcript_path_changed"};let i=Math.min(o.size,Fe),s=Buffer.alloc(i),a=0;for(;a<i;){let g=readSync(t,s,a,i-a,o.size-i+a);if(g===0)break;a+=g;}let c=s.subarray(0,a).toString("utf8");o.size>i&&(c=c.slice(Math.max(0,c.indexOf(`
9
- `)+1)));let d=c.split(/\r?\n/).slice(-Ne),l=e.length>0?Math.min(...e.map(g=>g.promptedAt)):0,u=Ye(d,l),f=[...u].reverse().find(g=>e.every(p=>p.contract.requiredSections.every(le=>g.text.includes(le))))??u.at(-1);return f?.text?{answer:f.text,fingerprint:f.fingerprint}:{degradationReason:"transcript_answer_unavailable"}}catch{return {degradationReason:"transcript_unreadable"}}finally{t!==void 0&&closeSync(t);}}function Ye(n,e){let t=[];for(let r=0;r<n.length;r++){let o=n[r];if(o.trim())try{let i=JSON.parse(o),s=i.message;if(!s||typeof s!="object"||s.role!=="assistant")continue;let a=s,c=Ze(i.timestamp);if(c>0&&c+5e3<e)continue;let d=s.content,l=typeof d=="string"?d:Array.isArray(d)?d.filter(u=>u&&typeof u=="object"&&u.type==="text").map(u=>u.text).filter(u=>typeof u=="string").join(`
10
- `):"";if(l.trim()){let u=l.trim(),m=typeof a.id=="string"&&a.id?`message:${a.id}`:typeof i.uuid=="string"&&i.uuid?`uuid:${i.uuid}`:`record:${String(i.timestamp??"")}:${r}:${createHash("sha256").update(o).digest("hex")}`,f=createHash("sha256").update(u).digest("hex"),g=createHash("sha256").update(`${m}\0${f}`).digest("hex");t.push({text:u,timestamp:c,fingerprint:g});}}catch{continue}}return t}function Ze(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?e:0}function Qe(n){let e=new Set,t=new Map,r;for(let o=0;o<n.length;o++){let i=n[o].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=Le.find(a=>i===a);s&&(r=s,e.add(s)),t.set(o,r);}return {found:e,byLine:t}}function te(n){let e={committed:0,skipped:0,pending:0},t=[];for(let r of n)e[r.status]+=1,r.receiptId&&t.push(r.receiptId);return {memoryReceiptIds:[...new Set(t)],missingMemoryDecisionCount:e.pending,memoryTurnOutcomes:e}}function nt(n,e=v(),t=true,r,o=true){let i;try{i=JSON.parse(n);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${e}\0${s}`).digest("hex").slice(0,24)}`,c={inputJson:n,sessionId:s,cleanupSharedState:t,executionId:r},d;try{d=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let l=d.requestSessionClosure({receiptId:a,projectRoot:e,sessionId:s,payload:c}),u=d.getWorkByIdempotencyKey(a);return {status:l.state==="closed"||l.state==="closed_with_pending_work"?"completed":"accepted",receiptId:a,workState:u?.state??"pending",closureState:l.state,pendingWorkCount:l.pendingWorkCount}}catch(l){if(!o)throw l;return Y(e,{receiptId:a,...c}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{d?.close();}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let n=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t;}),process.stdin.on("end",async()=>{let t=nt(e.trim()||process.argv[2]||"");t&&n(JSON.stringify(t)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var k=1,dt="memory-snapshot-v1.json",lt=512*1024,ie=256*1024,se=2e3,ut=500,mt=10,pt=240,gt=300*1e3,ft=720*60*60*1e3,yt=2147483647;function ht(n){return n.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:n.ownerUid===n.currentUid,modeSafe:(n.mode&18)===0}}function b(n){return resolve(n)}function w(n){return createHash("sha256").update(b(n)).digest("hex").slice(0,16)}function bt(n,e={}){let t=w(n),r=e.stateRoot?join(e.stateRoot,t):getProjectStateDir(b(n));return join(r,dt)}function vt(n,e){let r=(n instanceof Error?n.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return r?`${e}:${r}`:e}function O(n,e){return Array.isArray(n)&&n.length<=e&&n.every(t=>typeof t=="string"&&t.length>0&&t.length<=512)}function St(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let e=n;return typeof e.id=="string"&&e.id.length>0&&e.id.length<=512&&typeof e.kind=="string"&&e.kind.length>0&&e.kind.length<=128&&(e.family===void 0||typeof e.family=="string"&&e.family.length>0&&e.family.length<=256)&&(e.entity===void 0||typeof e.entity=="string"&&e.entity.length>0&&e.entity.length<=256)&&O(e.memoryIds,100)&&(e.status==="withheld"||e.status==="resolved")&&(e.summary===void 0||typeof e.summary=="string"&&e.summary.length<=2e3)}function wt(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let e=n;return typeof e.reason=="string"&&e.reason.length>0&&e.reason.length<=512&&(e.stale===void 0||typeof e.stale=="boolean")}function ae(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n,o=b(e),i=w(o),s=r.generation===void 0?0:r.generation;return r.version!==k||r.projectRoot!==o||r.projectHash!==i||typeof r.markdown!="string"||Buffer.byteLength(r.markdown,"utf8")>ie||!O(r.memoryIds,se)||!Array.isArray(r.conflicts)||r.conflicts.length>ut||!r.conflicts.every(St)||typeof r.generatedAt!="number"||!Number.isFinite(r.generatedAt)||r.generatedAt<0||r.generatedAt>t+gt||!Number.isInteger(s)||s<0||s>yt||!["ready","pending","degraded","disabled"].includes(String(r.status))||r.degradation!==void 0&&!wt(r.degradation)?null:{...r,generation:s}}function It(n,e,t,r,o=0){let i=b(n);return {version:k,projectRoot:i,projectHash:w(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:r,generation:o,status:e,degradation:{reason:t}}}function _t(n,e={}){let t=e.now??Date.now(),r=bt(n,e),o;try{o=openSync(r,constants.O_RDONLY|constants.O_NOFOLLOW);let i=fstatSync(o);if(!i.isFile()||i.size<=0||i.size>lt)throw new Error("cache_size_invalid");let s=ht({...typeof process.getuid=="function"?{currentUid:process.getuid()}:{},ownerUid:i.uid,mode:i.mode});if(!s.ownerSafe)throw new Error("cache_owner_invalid");if(!s.modeSafe)throw new Error("cache_permissions_unsafe");let a=JSON.parse(readFileSync(o,"utf8")),c=ae(a,n,t);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&t-c.generatedAt>ft?{snapshot:{...c,status:"degraded",degradation:{reason:"cache_stale",stale:!0}},source:"cache",valid:!0,stale:!0}:{snapshot:c,source:"cache",valid:!0,stale:!1}}catch(i){let a=i.code==="ENOENT";return {snapshot:It(n,a?"pending":"degraded",a?"cache_missing":vt(i,"cache_invalid"),t),source:"none",valid:false,stale:false}}finally{if(o!==void 0)try{closeSync(o);}catch{}}}function kt(n){if(!n)return true;try{return JSON.parse(readFileSync(n,"utf8")).sessionStart?.injectMemories??!0}catch{return true}}function Rt(n,e,t){if(!e.trim())return null;try{let r=JSON.parse(e);if(r.status!=="ok"&&r.status!=="degraded")return null;if(r.enabled===!1){let i=b(n);return {version:k,projectRoot:i,projectHash:w(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:t,generation:0,status:"disabled"}}let o=ae(r.snapshot,n,t);if(o)return o;if(r.status==="ok"&&typeof r.markdown=="string"&&r.markdown.length>0&&Buffer.byteLength(r.markdown,"utf8")<=ie){let i=b(n);return {version:k,projectRoot:i,projectHash:w(i),markdown:r.markdown,memoryIds:O(r.memoryIds,se)?r.memoryIds:[],conflicts:[],generatedAt:t,generation:0,status:"ready"}}}catch{}return null}function A(n,e){return [...(n??e).replace(/[\r\n\t|]+/gu," ").trim()||e].slice(0,pt).join("")}function Et(n){if(n.length===0)return "";let e=n.slice(0,mt),t=e.map(r=>{let o=A(r.family,"unknown"),i=A(r.entity,"unknown"),s=A(r.summary,"Explicit choice required.");return `- family=${o}; entity=${i}; status=${r.status}; summary=${s}`});return n.length>e.length&&t.push(`- ${n.length-e.length} additional conflict(s) omitted from SessionStart output.`),`## Withheld preference conflicts (${n.length})
8
+ `)}}function Je(n,e){let t=new Set,r=new Set(e.flatMap(c=>c.contract.requiredSections)),o=ne(n.split(/\r?\n/)),i=oe(o.headingLines);for(let c of r)i.found.has(c)||t.add(`missing_section:${c}`);if(e.every(c=>c.contract.runtimeProfilingOccurred))return [...t];let a=e.every(c=>c.contract.samplingEvidenceOccurred);for(let c=0;c<o.claimLines.length;c++){let d=o.claimLines[c].trim();if(!d||Be(d))continue;let l=i.byLine.get(c);for(let u of Ye(d))Ve(u,l,a,t);}return [...t]}function ne(n){let e=false,t=[],r=[];for(let o of n){if(/^\s*```/.test(o)){e=!e,t.push(""),r.push(o.replace(/^\s*```+[^\s`]*/,"").replace(/```+\s*$/,"").trim());continue}t.push(e?"":o.replace(/`[^`]*`/g,"").trim()),r.push(o.replace(/`([^`]*)`/g,(i,s)=>We(s)?"":s).trim());}return {headingLines:t,claimLines:r}}function We(n){let e=n.trim().slice(0,256);return !e||/\s/.test(e)||n.trim().length>256?false:/^[A-Za-z_$][\w$.-]*$/.test(e)||/^(['"])[^'"`]*\1$/.test(e)}function Be(n){if(n.length>2048)return false;let e=n.replace(/^\s*(?:[-*+]|\d+[.)])\s+/,"").trim();return e?Ge(e)||/^(?:\/\/|\/\*|\*\/|\*\s|#!)/.test(e)||/^(?:import|export|const|let|var|function|class|type|interface|enum|namespace|declare)\b/.test(e)||/^(?:async\s+)?(?:function\s+)?[A-Za-z_$][\w$]*\s*=\s*/.test(e)||/^[A-Za-z_$][\w$.[\]'"-]*\s*(?:=|\+=|-=|\*=|\/=|\?\?=|&&=|\|\|=)\s*/.test(e)||/^[A-Za-z_$'"-][\w$.'"-]*\s*:\s*[^:]+[,}]?$/.test(e)||/=>/.test(e)||/^(?:await\s+|return\s+|throw\s+|new\s+)?[A-Za-z_$][\w$.]*\s*\([^)]*\)\s*;?$/.test(e)||/^(['"])[\s\S]*\1[;,]?$/.test(e)?true:/[{}()[\]=<>]\s*;?$/.test(e)&&/(?:;|=>|\b(?:return|new|await)\b)/.test(e):false}function Ge(n){if(n.length>1024)return false;let e="(?:--[A-Za-z0-9_-]+|(?:-webkit-|-moz-|-ms-)?(?:animation(?:-[a-z-]+)?|transition(?:-[a-z-]+)?|opacity|transform|will-change|contain|content-visibility|display|position|top|right|bottom|left|width|height|min-(?:width|height)|max-(?:width|height)|margin(?:-[a-z]+)?|padding(?:-[a-z]+)?|color|background(?:-[a-z-]+)?|border(?:-[a-z-]+)?|font(?:-[a-z-]+)?|line-height|z-index|overflow(?:-[xy])?))";return new RegExp(`^${e}\\s*:\\s*\\S[^;]{0,960};$`,"i").test(n)}function Ve(n,e,t,r){let o=/\bP0\b/gi;for(let g of n.matchAll(o))ee(n,g.index??0,g[0],"p0")||r.add("unsupported_p0_severity");let i=/(?:中高|高)(?:风险|优先级)|严重(?:问题|风险)|\bhigh[- ](?:risk|severity|priority)\b/gi;for(let g of n.matchAll(i))ee(n,g.index??0,g[0],"high")||r.add("unsupported_high_severity");let s=/(?:性能)?瓶颈|卡顿|掉帧|CPU\s*(?:热点|尖峰)|\bbottleneck\b|\bjank\b|\bdropped frames?\b|\bCPU hotspot\b/gi;for(let g of n.matchAll(s))Xe(n,g.index??0,g[0])||(/(?:瓶颈|bottleneck)/i.test(g[0])?r.add("unsupported_confirmed_bottleneck"):r.add("unsupported_runtime_effect"));let a=/\b\d{1,3}(?:\.\d+)?\s*%/.test(n),c=/(?:预计|预期|估计|提升|降低|减少|节省|改善|收益|加速|improve|reduce|faster|gain|benefit|speedup|expected|estimated)/i.test(n),d=/\b\d+(?:\.\d+)?\s*[x×]\b/i.test(n);(a||d)&&c&&r.add(a?"unsupported_benefit_percentage":"unsupported_performance_number");let l=/\b\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:ms|fps|hz)\b/i.test(n)||/\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:毫秒|次\s*\/\s*秒|帧)/.test(n),u=e==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&/(?:采集|记录|测量|收集|collect|measure|record)/i.test(n)&&!/(?:预计|预期|估计|约|大约|通常|平均|每(?:隔)?|达到|提升|降低|减少|节省|改善|improve|reduce|faster|expected|estimated|average|typically|every)/i.test(n);a&&!c&&!u&&r.add("unsupported_benefit_percentage"),l&&!u&&r.add("unsupported_performance_number");let m=/(?:requestAnimationFrame|\bRAF\b)/i.test(n),f=/(?:建议|应该|应当|使用|添加|采用|切换|包裹|优化|节流|\buse\b|\badopt\b|\brecommend\b|\bswitch\b|\bwrap\b|\bthrottl(?:e|ing)\b)/i.test(n),p=/(?:不要|不得|不能|不应|避免|不建议|不推荐).{0,16}(?:使用|采用|添加|切换|包裹|节流)?.{0,8}(?:requestAnimationFrame|\bRAF\b)|\b(?:do\s+not|don't|never|avoid)\s+(?:use|adopt|recommend|switch|wrap|throttle)?.{0,8}(?:requestAnimationFrame|RAF)\b/i.test(n);m&&f&&!p&&!t&&r.add("raf_without_sampling_evidence");}function ee(n,e,t,r){let o=n.slice(Math.max(0,e-64),e),i=n.slice(e+t.length,e+t.length+28),s=Ke(o),a=/^(?:\s+)?(?:未发现|不存在|并不存在|未被发现)/.test(i)||/^(?:\s+)?(?:was\s+|is\s+)?not found\b/i.test(i);return s||a?true:r==="high"?/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?)\s*(?:任何|明确的)?\s*P0\s*(?:或|和|及|、)\s*$/i.test(o)||/\b(?:no evidence (?:of|for)|no)\s+P0\s+(?:or|and)\s+$/i.test(o):false}function Ke(n){if(/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?|不是|并非|未被)\s*(?:任何|明确的)?\s*(?:(?:问题|发现|证据|项|内容)\s*)?(?:(?:属于|(?:被)?(?:评|判定|认定|标记|列|视|定|归(?:类)?)为)\s*)?$/i.test(n)||/\b(?:no evidence (?:of|for)|no|not|isn't|is\s+not)\s+(?:an?\s+)?(?:(?:issues?|findings?|evidence|items?)\s+)?(?:(?:classified|rated|marked|labelled|labeled)(?:\s+as)?\s+)?$/i.test(n))return true;let t=/(?:不得|不能|不应|不宜|不要)\s*(?:被\s*)?(?:(?:直接|轻易|简单|明确|正式|合理|据此|当前|目前)\s*){0,2}(?:(?:评|判定|认定|标记|列|视|定|归(?:类)?)为|属于)\s*$/i,r=/\b(?:cannot|can't|must not|should not|shouldn't|do not|don't)\s+(?:(?:reasonably|directly|formally|currently)\s+){0,2}(?:be\s+)?(?:classified|labeled|labelled|rated|marked)(?:\s+as)?\s+$/i;return t.test(n)||r.test(n)}function Xe(n,e,t){let r=n.slice(Math.max(0,e-40),e),o=n.slice(e+t.length,e+t.length+32),i=/(?:是否|待验证|候选|可能|潜在|未观察到|没有观察到|未发现|不存在|无证据(?:表明)?|不能(?:据此)?确认|尚未(?:确认|证明)|验证(?:是否)?|测量(?:是否)?|采集|记录|收集).{0,16}$/i.test(r)||/\b(?:whether|measure|validate|candidate|potential|possible|may|might|no|no evidence(?: of| for)?|not observed|unobserved|collect|record).{0,18}$/i.test(r),s=/^(?:是否|有待验证|待验证|候选|可能|潜在|指标|需要(?:验证|测量)|需(?:验证|测量))/.test(o)||/^(?:\s+)?(?:candidate|potential|possible|metric|metrics|to (?:measure|validate)|needs? (?:measurement|validation)|is (?:a )?(?:candidate|potential))/i.test(o);return i||s}function Ye(n){return n.split(/(?:[。!?;;,,]|\b(?:but|however|yet|nevertheless|nonetheless)\b|但是|但|然而|却|不过|可是)/i).map(e=>e.trim()).filter(Boolean)}function re(n,e){if(!n||n.length>4096)return {degradationReason:"transcript_path_missing"};let t;try{let r=lstatSync(n);if(!r.isFile()||r.isSymbolicLink())return {degradationReason:"transcript_path_unsafe"};t=openSync(n,constants.O_RDONLY|(constants.O_NOFOLLOW??0));let o=fstatSync(t);if(!o.isFile()||o.dev!==r.dev||o.ino!==r.ino)return {degradationReason:"transcript_path_changed"};let i=Math.min(o.size,ze),s=Buffer.alloc(i),a=0;for(;a<i;){let p=readSync(t,s,a,i-a,o.size-i+a);if(p===0)break;a+=p;}let c=s.subarray(0,a).toString("utf8");o.size>i&&(c=c.slice(Math.max(0,c.indexOf(`
9
+ `)+1)));let d=c.split(/\r?\n/).slice(-He),l=e.length>0?Math.min(...e.map(p=>p.promptedAt)):0,u=Qe(d,l),f=[...u].reverse().find(p=>Ze(p.text,e))??u.at(-1);return f?.text?{answer:f.text,fingerprint:f.fingerprint}:{degradationReason:"transcript_answer_unavailable"}}catch{return {degradationReason:"transcript_unreadable"}}finally{t!==void 0&&closeSync(t);}}function Ze(n,e){let t=new Set(e.flatMap(o=>o.contract.requiredSections)),r=oe(ne(n.split(/\r?\n/u)).headingLines);return [...t].every(o=>r.found.has(o))}function A(n){return re(n,[]).answer}function Qe(n,e){let t=[];for(let r=0;r<n.length;r++){let o=n[r];if(o.trim())try{let i=JSON.parse(o),s=i.message;if(!s||typeof s!="object"||s.role!=="assistant")continue;let a=s,c=et(i.timestamp);if(c>0&&c+5e3<e)continue;let d=s.content,l=typeof d=="string"?d:Array.isArray(d)?d.filter(u=>u&&typeof u=="object"&&u.type==="text").map(u=>u.text).filter(u=>typeof u=="string").join(`
10
+ `):"";if(l.trim()){let u=l.trim(),m=typeof a.id=="string"&&a.id?`message:${a.id}`:typeof i.uuid=="string"&&i.uuid?`uuid:${i.uuid}`:`record:${String(i.timestamp??"")}:${r}:${createHash("sha256").update(o).digest("hex")}`,f=createHash("sha256").update(u).digest("hex"),p=createHash("sha256").update(`${m}\0${f}`).digest("hex");t.push({text:u,timestamp:c,fingerprint:p});}}catch{continue}}return t}function et(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?e:0}function oe(n){let e=new Set,t=new Map,r;for(let o=0;o<n.length;o++){let i=n[o].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=Ue.find(a=>i===a);s&&(r=s,e.add(s)),t.set(o,r);}return {found:e,byLine:t}}function ie(n){let e={committed:0,skipped:0,pending:0},t=[];for(let r of n)e[r.status]+=1,r.receiptId&&t.push(r.receiptId);return {memoryReceiptIds:[...new Set(t)],missingMemoryDecisionCount:e.pending,memoryTurnOutcomes:e}}function rt(n,e=v(),t=true,r,o=true){let i;try{i=JSON.parse(n);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${e}\0${s}`).digest("hex").slice(0,24)}`,c={inputJson:n,sessionId:s,cleanupSharedState:t,executionId:r},d;try{d=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let l=d.requestSessionClosure({receiptId:a,projectRoot:e,sessionId:s,payload:c}),u=d.getWorkByIdempotencyKey(a);return {status:l.state==="closed"||l.state==="closed_with_pending_work"?"completed":"accepted",receiptId:a,workState:u?.state??"pending",closureState:l.state,pendingWorkCount:l.pendingWorkCount}}catch(l){if(!o)throw l;return Z(e,{receiptId:a,...c}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{d?.close();}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let n=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t;}),process.stdin.on("end",async()=>{let t=rt(e.trim()||process.argv[2]||"");t&&n(JSON.stringify(t)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var k=1,lt="memory-snapshot-v1.json",ut=512*1024,de=256*1024,le=2e3,mt=500,pt=10,gt=240,ft=300*1e3,yt=720*60*60*1e3,ht=2147483647;function bt(n){return n.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:n.ownerUid===n.currentUid,modeSafe:(n.mode&18)===0}}function b(n){return resolve(n)}function w(n){return createHash("sha256").update(b(n)).digest("hex").slice(0,16)}function vt(n,e={}){let t=w(n),r=e.stateRoot?join(e.stateRoot,t):getProjectStateDir(b(n));return join(r,lt)}function St(n,e){let r=(n instanceof Error?n.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return r?`${e}:${r}`:e}function D(n,e){return Array.isArray(n)&&n.length<=e&&n.every(t=>typeof t=="string"&&t.length>0&&t.length<=512)}function wt(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let e=n;return typeof e.id=="string"&&e.id.length>0&&e.id.length<=512&&typeof e.kind=="string"&&e.kind.length>0&&e.kind.length<=128&&(e.family===void 0||typeof e.family=="string"&&e.family.length>0&&e.family.length<=256)&&(e.entity===void 0||typeof e.entity=="string"&&e.entity.length>0&&e.entity.length<=256)&&D(e.memoryIds,100)&&(e.status==="withheld"||e.status==="resolved")&&(e.summary===void 0||typeof e.summary=="string"&&e.summary.length<=2e3)}function It(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let e=n;return typeof e.reason=="string"&&e.reason.length>0&&e.reason.length<=512&&(e.stale===void 0||typeof e.stale=="boolean")}function ue(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n,o=b(e),i=w(o),s=r.generation===void 0?0:r.generation;return r.version!==k||r.projectRoot!==o||r.projectHash!==i||typeof r.markdown!="string"||Buffer.byteLength(r.markdown,"utf8")>de||!D(r.memoryIds,le)||!Array.isArray(r.conflicts)||r.conflicts.length>mt||!r.conflicts.every(wt)||typeof r.generatedAt!="number"||!Number.isFinite(r.generatedAt)||r.generatedAt<0||r.generatedAt>t+ft||!Number.isInteger(s)||s<0||s>ht||!["ready","pending","degraded","disabled"].includes(String(r.status))||r.degradation!==void 0&&!It(r.degradation)?null:{...r,generation:s}}function _t(n,e,t,r,o=0){let i=b(n);return {version:k,projectRoot:i,projectHash:w(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:r,generation:o,status:e,degradation:{reason:t}}}function kt(n,e={}){let t=e.now??Date.now(),r=vt(n,e),o;try{o=openSync(r,constants.O_RDONLY|constants.O_NOFOLLOW);let i=fstatSync(o);if(!i.isFile()||i.size<=0||i.size>ut)throw new Error("cache_size_invalid");let s=bt({...typeof process.getuid=="function"?{currentUid:process.getuid()}:{},ownerUid:i.uid,mode:i.mode});if(!s.ownerSafe)throw new Error("cache_owner_invalid");if(!s.modeSafe)throw new Error("cache_permissions_unsafe");let a=JSON.parse(readFileSync(o,"utf8")),c=ue(a,n,t);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&t-c.generatedAt>yt?{snapshot:{...c,status:"degraded",degradation:{reason:"cache_stale",stale:!0}},source:"cache",valid:!0,stale:!0}:{snapshot:c,source:"cache",valid:!0,stale:!1}}catch(i){let a=i.code==="ENOENT";return {snapshot:_t(n,a?"pending":"degraded",a?"cache_missing":St(i,"cache_invalid"),t),source:"none",valid:false,stale:false}}finally{if(o!==void 0)try{closeSync(o);}catch{}}}function Rt(n){if(!n)return true;try{return JSON.parse(readFileSync(n,"utf8")).sessionStart?.injectMemories??!0}catch{return true}}function Et(n,e,t){if(!e.trim())return null;try{let r=JSON.parse(e);if(r.status!=="ok"&&r.status!=="degraded")return null;if(r.enabled===!1){let i=b(n);return {version:k,projectRoot:i,projectHash:w(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:t,generation:0,status:"disabled"}}let o=ue(r.snapshot,n,t);if(o)return o;if(r.status==="ok"&&typeof r.markdown=="string"&&r.markdown.length>0&&Buffer.byteLength(r.markdown,"utf8")<=de){let i=b(n);return {version:k,projectRoot:i,projectHash:w(i),markdown:r.markdown,memoryIds:D(r.memoryIds,le)?r.memoryIds:[],conflicts:[],generatedAt:t,generation:0,status:"ready"}}}catch{}return null}function O(n,e){return [...(n??e).replace(/[\r\n\t|]+/gu," ").trim()||e].slice(0,gt).join("")}function xt(n){if(n.length===0)return "";let e=n.slice(0,pt),t=e.map(r=>{let o=O(r.family,"unknown"),i=O(r.entity,"unknown"),s=O(r.summary,"Explicit choice required.");return `- family=${o}; entity=${i}; status=${r.status}; summary=${s}`});return n.length>e.length&&t.push(`- ${n.length-e.length} additional conflict(s) omitted from SessionStart output.`),`## Withheld preference conflicts (${n.length})
11
11
  ${t.join(`
12
- `)}`}function xt(n){let e=n.now??Date.now();if(kt(n.configPath)===false)return "";let t=Rt(n.projectRoot,n.daemonResponse??"",e),r=t?{snapshot:t,source:"daemon"}:_t(n.projectRoot,{...n.cacheOptions,now:e}),{snapshot:o}=r;if(o.status==="disabled")return `## Project memory
13
- DevFlow memory snapshot=pending; source=${r.source}; reason=previous_snapshot_disabled. Memory availability is not yet known; do not conclude that the project has no memories.`;let i=new Date(o.generatedAt).toISOString(),s=o.degradation?.reason?`; reason=${o.degradation.reason}`:"",a=`DevFlow memory snapshot=${o.status}; source=${r.source}; generatedAt=${i}${s}.`,c=Et(o.conflicts);return o.markdown?[o.markdown,c,a].filter(Boolean).join(`
12
+ `)}`}function Ct(n){let e=n.now??Date.now();if(Rt(n.configPath)===false)return "";let t=Et(n.projectRoot,n.daemonResponse??"",e),r=t?{snapshot:t,source:"daemon"}:kt(n.projectRoot,{...n.cacheOptions,now:e}),{snapshot:o}=r;if(o.status==="disabled")return `## Project memory
13
+ DevFlow memory snapshot=pending; source=${r.source}; reason=previous_snapshot_disabled. Memory availability is not yet known; do not conclude that the project has no memories.`;let i=new Date(o.generatedAt).toISOString(),s=o.degradation?.reason?`; reason=${o.degradation.reason}`:"",a=`DevFlow memory snapshot=${o.status}; source=${r.source}; generatedAt=${i}${s}.`,c=xt(o.conflicts);return o.markdown?[o.markdown,c,a].filter(Boolean).join(`
14
14
  `):["## Project memory",c,`${a} Memory availability is not yet known; do not conclude that the project has no memories.`].filter(Boolean).join(`
15
- `)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,n,e,t]=process.argv;n!=="session-start"||!e?process.exitCode=2:process.stdout.write(xt({projectRoot:e,configPath:t,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}function ce(n){return `DevFlow memory decision required for ${n.turnId}. Before the final response, semantically decide whether this turn contains durable project knowledge. Call mcp__devflow__memory_commit_turn with evidence-bound candidates, or mcp__devflow__memory_skip_turn with a concrete reason. Do not claim memory success without a canonical receipt.`}function de(n){let e=ee({projectRoot:n.projectRoot,sessionId:n.sessionId,transcriptPath:n.transcriptPath,runtimeStore:n.runtimeStore}),t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{Mt(n.runtimeStore,n.sessionId,t);let r=t.getPendingMemoryTurn(n.projectRoot,n.sessionId),o=r?t.markMemoryTurnStopPrompted(r.turnId):!1,i=[];e&&i.push(e.reason),r&&o&&i.push(ce(r));let a=t.listSessionObligations(n.projectRoot,n.sessionId,["open"]).map(c=>({obligationId:c.obligationId,kind:c.kind,action:c.kind==="memory_decision"?"Call mcp__devflow__memory_decide_turn using the canonical turn ID.":c.kind==="evidence_contract"?"Return a final answer that satisfies the canonical evidence contract.":"Allow SessionEnd durable finalization to complete.",canonicalInput:c.kind==="memory_decision"&&c.turnId?{turnId:c.turnId}:void 0}));return i.length>0?{decision:"block_once",unresolved:a,additionalContext:["DevFlow has unresolved terminal obligations. Complete all actions below before stopping.",...i].join(`
15
+ `)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,n,e,t]=process.argv;n!=="session-start"||!e?process.exitCode=2:process.stdout.write(Ct({projectRoot:e,configPath:t,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}function me(n){return `DevFlow memory decision required for ${n.turnId}. Before the final response, semantically decide whether this turn contains durable project knowledge. Call mcp__devflow__memory_commit_turn with evidence-bound candidates, or mcp__devflow__memory_skip_turn with a concrete reason. Do not claim memory success without a canonical receipt. If the decision tool remains unavailable, explicitly state that the memory was not saved.`}function pe(n){let e=te({projectRoot:n.projectRoot,sessionId:n.sessionId,transcriptPath:n.transcriptPath,runtimeStore:n.runtimeStore}),t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{Dt(n.runtimeStore,n.sessionId,t);let r=t.getPendingMemoryTurn(n.projectRoot,n.sessionId),o=r?t.markMemoryTurnStopPrompted(r.turnId):!1,i=[];e&&i.push(e.reason),r&&o&&i.push(me(r)),r&&!o&&At(t,r.turnId)&&Ot(A(n.transcriptPath))&&i.push(`DevFlow explicit memory ${r.turnId} still has no canonical receipt. Remove the memory-success claim and tell the user that the memory was not saved, or complete the pending turn.`);let a=t.listSessionObligations(n.projectRoot,n.sessionId,["open"]).map(c=>({obligationId:c.obligationId,kind:c.kind,action:c.kind==="memory_decision"?"Call mcp__devflow__memory_decide_turn using the canonical turn ID.":c.kind==="evidence_contract"?"Return a final answer that satisfies the canonical evidence contract.":"Allow SessionEnd durable finalization to complete.",canonicalInput:c.kind==="memory_decision"&&c.turnId?{turnId:c.turnId}:void 0}));return i.length>0?{decision:"block_once",unresolved:a,additionalContext:["DevFlow has unresolved terminal obligations. Complete all actions below before stopping.",...i].join(`
16
16
 
17
- `)}:a.length>0?{decision:"degrade",unresolved:a,additionalContext:"DevFlow terminal obligations remain unresolved after their one-shot correction budget."}:{decision:"allow",unresolved:[]}}finally{t.close();}}function Mt(n,e,t){let r=n.get(e);if(r){for(let o of r.evidenceObligations)t.upsertSessionObligation({obligationId:`evidence:${o.obligationId}`,projectRoot:r.projectRoot,sessionId:e,executionId:r.executionId,kind:"evidence_contract",state:"open",payload:{contract:o.contract,runtimeObligationId:o.obligationId},createdAt:o.promptedAt,updatedAt:r.lastActivityAt});for(let o of r.evidenceOutcomes){let i=`evidence:${o.obligationId}`,s=t.getSessionObligation(r.projectRoot,e,i);!s||s.state!=="open"||t.resolveSessionObligation({projectRoot:r.projectRoot,sessionId:e,obligationId:i,state:o.status==="resolved"?"satisfied":"degraded",reason:o.reason,resolvedAt:o.completedAt});}}}async function Ot(n,e=v()){let t;try{t=JSON.parse(n);}catch{return null}let r=t.session_id?.trim();if(!r)return null;let o=new y(e),i=de({projectRoot:e,sessionId:r,transcriptPath:t.transcript_path,stopHookActive:t.stop_hook_active===true,runtimeStore:o});if(i.decision==="block_once")return {decision:"block",reason:i.additionalContext};let s=o.completeExecution(r);if(s?.executionId){let a=openGlobalDevFlowDatabase();try{let c=a.listSessionMemoryTurnsForReconciliation(e,r);a.reconcileSkillExecution(s.executionId,"completed",Date.now(),{...te(c),evidenceDegradations:s.evidenceDegradations,evidenceContractOutcomes:s.evidenceOutcomes,unresolvedObligations:i.unresolved,terminalState:i.decision}),a.deleteContextReceipt(e,r,s.executionId);}finally{a.close();}}return _(`/api/telemetry/sessions/${encodeURIComponent(r)}/tick`,{timestamp:Date.now()},{fallbackReason:"stop_tick_already_local"}),null}if(process.argv[1]?.endsWith("stop")||process.argv[1]?.endsWith("stop.js")){let n=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t;}),process.stdin.on("end",async()=>{let t=await Ot(e.trim()||process.argv[2]||"");t&&n(JSON.stringify(t)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),4e3).unref();}export{Ot as handleStop};
17
+ `)}:a.length>0?{decision:"degrade",unresolved:a,additionalContext:"DevFlow terminal obligations remain unresolved after their one-shot correction budget."}:{decision:"allow",unresolved:[]}}finally{t.close();}}function At(n,e){return !!n.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${e}`)}function Ot(n){if(!n)return false;let e=n.normalize("NFKC").replace(/\s+/gu," ");return /(?:未|没有|无法|失败|暂未|尚未).{0,24}(?:记住|记下|记录|保存|持久化|回执)|(?:memory|receipt).{0,24}(?:failed|missing|pending|degraded|not saved)|status=(?:pending|degraded|rejected|failed)/iu.test(e)?false:/(?:已|已经|成功).{0,20}(?:记住|记下|记录|保存|持久化)|跨会话生效|(?:memory|preference).{0,20}(?:saved|remembered|persisted)|status=(?:accepted|committed)/iu.test(e)}function Dt(n,e,t){let r=n.get(e);if(r){for(let o of r.evidenceObligations)t.upsertSessionObligation({obligationId:`evidence:${o.obligationId}`,projectRoot:r.projectRoot,sessionId:e,executionId:r.executionId,kind:"evidence_contract",state:"open",payload:{contract:o.contract,runtimeObligationId:o.obligationId},createdAt:o.promptedAt,updatedAt:r.lastActivityAt});for(let o of r.evidenceOutcomes){let i=`evidence:${o.obligationId}`,s=t.getSessionObligation(r.projectRoot,e,i);!s||s.state!=="open"||t.resolveSessionObligation({projectRoot:r.projectRoot,sessionId:e,obligationId:i,state:o.status==="resolved"?"satisfied":"degraded",reason:o.reason,resolvedAt:o.completedAt});}}}async function $t(n,e=v()){let t;try{t=JSON.parse(n);}catch{return null}let r=t.session_id?.trim();if(!r)return null;let o=new y(e),i=pe({projectRoot:e,sessionId:r,transcriptPath:t.transcript_path,stopHookActive:t.stop_hook_active===true,runtimeStore:o});if(i.decision==="block_once")return {decision:"block",reason:i.additionalContext};let s=o.completeExecution(r);if(s?.executionId){let a=openGlobalDevFlowDatabase();try{let c=a.listSessionMemoryTurnsForReconciliation(e,r);a.reconcileSkillExecution(s.executionId,"completed",Date.now(),{...ie(c),evidenceDegradations:s.evidenceDegradations,evidenceContractOutcomes:s.evidenceOutcomes,unresolvedObligations:i.unresolved,terminalState:i.decision}),a.deleteContextReceipt(e,r,s.executionId);}finally{a.close();}}return _(`/api/telemetry/sessions/${encodeURIComponent(r)}/tick`,{timestamp:Date.now()},{fallbackReason:"stop_tick_already_local"}),null}if(process.argv[1]?.endsWith("stop")||process.argv[1]?.endsWith("stop.js")){let n=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t;}),process.stdin.on("end",async()=>{let t=await $t(e.trim()||process.argv[2]||"");t&&n(JSON.stringify(t)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),4e3).unref();}export{$t as handleStop};
@@ -9,7 +9,7 @@ ${t.join(`
9
9
  `)}`}function mn(n){let e=n.now??Date.now();if(dn(n.configPath)===false)return "";let t=ln(n.projectRoot,n.daemonResponse??"",e),r=t?{snapshot:t,source:"daemon"}:h(n.projectRoot,{...n.cacheOptions,now:e}),{snapshot:o}=r;if(o.status==="disabled")return `## Project memory
10
10
  DevFlow memory snapshot=pending; source=${r.source}; reason=previous_snapshot_disabled. Memory availability is not yet known; do not conclude that the project has no memories.`;let i=new Date(o.generatedAt).toISOString(),s=o.degradation?.reason?`; reason=${o.degradation.reason}`:"",a=`DevFlow memory snapshot=${o.status}; source=${r.source}; generatedAt=${i}${s}.`,c=un(o.conflicts);return o.markdown?[o.markdown,c,a].filter(Boolean).join(`
11
11
  `):["## Project memory",c,`${a} Memory availability is not yet known; do not conclude that the project has no memories.`].filter(Boolean).join(`
12
- `)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,n,e,t]=process.argv;n!=="session-start"||!e?process.exitCode=2:process.stdout.write(mn({projectRoot:e,configPath:t,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var fn=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu;function gn(n){let e=n.trim();return e.length>0&&!fn.test(e)}function yn(n,e,t=Date.now()){let r=createHash("sha256").update(e.trim()).digest("hex"),o=createHash("sha256").update(`${n}\0${t}\0${r}`).digest("hex").slice(0,24);return {turnId:`turn:${o}`,eventId:`memory-turn:${o}`,promptHash:r,createdAt:t}}function hn(n,e,t=[]){return `memory-receipt:${createHash("sha256").update(`${n}\0${e}\0${[...t].sort().join("\0")}`).digest("hex").slice(0,24)}`}function Ve(n){return `DevFlow memory decision required for ${n.turnId}. Before the final response, semantically decide whether this turn contains durable project knowledge. Call mcp__devflow__memory_commit_turn with evidence-bound candidates, or mcp__devflow__memory_skip_turn with a concrete reason. Do not claim memory success without a canonical receipt.`}function X(n){let e=n.memoryIds.length>0?n.memoryIds.join(","):"none",t=n.status==="committed"?"accepted":n.status,r=n.status==="committed"?"; indexStatus=pending":"",o=n.status==="committed"&&n.source==="explicit_intent"?"; memoryOnlyCompleted=true; skipProjectContext=true; skipMemoryTool=true":"",i=n.status==="committed"&&n.source==="explicit_intent"?" This explicit-memory request is complete. Return the canonical receipt to the user. Do not call a memory tool, project-context tool, domain tool, or native memory write for this request.":"";return `DevFlow canonical memory receipt: status=${t}; receiptId=${n.receiptId??"missing"}; turnId=${n.turnId}; memoryIds=${e}; source=${n.source??"unknown"}${r}${o}.`+i}function Be(n){if(!gn(n.prompt))return null;let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let t=n.prompt.trim().slice(0,4e3),r=createHash("sha256").update(t).digest("hex"),o=e.listMemoryTurns(n.projectRoot,n.sessionId,5).find(d=>d.promptHash===r&&Date.now()-d.createdAt<1e4),i=o?{turnId:o.turnId,eventId:o.eventId,promptHash:o.promptHash,createdAt:o.createdAt}:yn(n.sessionId,t),s=o??e.beginMemoryTurn({...i,projectRoot:n.projectRoot,sessionId:n.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:X(s),skipSkillRouting:s.source==="explicit_intent"};let a=x(t)??void 0,c=a?"commit_explicit":"capture_prompt";return e.enqueueWork({idempotencyKey:`memory-turn:${c}:${s.turnId}`,kind:a?"memory.explicit_commit":"memory.turn_capture",projectRoot:n.projectRoot,sessionId:n.sessionId,turnId:s.turnId,payload:{operation:c,turnId:s.turnId,eventId:s.eventId,sessionId:n.sessionId,prompt:t,explicitContent:a,createdAt:s.createdAt}}),{turn:s,explicitContent:a,additionalContext:a?`DevFlow explicit memory is durably queued for ${s.turnId}, but no canonical receipt exists yet. Do not claim that it was remembered.`:Ve(s),skipSkillRouting:!!a}}finally{e.close();}}async function Ke(n){let{payload:e,memory:t,projectRoot:r}=n,o=openGlobalDevFlowDatabase();try{let i=o.getMemoryTurn(e.turnId);if(!i)throw new Error(`Memory turn ${e.turnId} does not exist`);if(i.status!=="pending")return {turn:i,additionalContext:X(i),skipSkillRouting:i.source==="explicit_intent"};if(await t.recordUserMessage(e.prompt,e.sessionId,e.prompt.slice(0,200)),await t.recordEvent({id:e.eventId,sessionId:e.sessionId,tool:"UserPromptSubmit",kind:"user_message",payload:{prompt:e.prompt,turnId:e.turnId},createdAt:e.createdAt}),e.operation==="capture_prompt"||!e.explicitContent)return {turn:i,additionalContext:Ve(i),skipSkillRouting:!1};let s=await t.saveExplicitMemoryIntent(e.explicitContent,e.sessionId,e.eventId),a=hn(i.turnId,"committed",[s.id]),c=o.commitMemoryTurn({turnId:i.turnId,receiptId:a,memoryIds:[s.id],source:"explicit_intent",reason:"explicit_user_request"});try{await t.enrichExplicitMemoryObservation(s.id);}catch(d){console.error("[devflow] Explicit memory enrichment deferred:",d.message),o.enqueueWork({idempotencyKey:`explicit-enrichment:${r}:${s.id}`,kind:"memory.explicit_enrichment",projectRoot:r,sessionId:e.sessionId,turnId:c.turnId,payload:{observationId:s.id},maxAttempts:20});}o.enqueueWork({idempotencyKey:`vector:${r}:${s.id}`,kind:"memory.vector_backfill",projectRoot:r,sessionId:e.sessionId,turnId:c.turnId,payload:{observationId:s.id},maxAttempts:20});try{await Ge({projectRoot:r,memory:t,injectConfig:loadConfig(r).sessionStart?.injectMemories,reason:"explicit_memory_commit"});}catch(d){console.error("[devflow] Memory snapshot refresh failed after canonical commit:",d.message);}return {turn:c,explicitContent:e.explicitContent,additionalContext:X(c),skipSkillRouting:!0}}finally{o.close();}}function Xe(n,e){let t=wn(n);mkdirSync(t,{recursive:true,mode:448});let r=`memory-turn-spool-${Date.now()}-${process.pid}-${randomUUID()}`,o=join(t,`${r}.json`),i=`${o}.tmp`;return writeFileSync(i,JSON.stringify({...e,prompt:e.prompt.trim().slice(0,4e3)}),{mode:384}),renameSync(i,o),r}function wn(n){return join(S(n),"memory-turn-pending")}var p=process.env.CLAUDE_PROJECT_DIR||process.cwd();async function Rn(n){let e=ee()?[Q]:[],t;try{t=JSON.parse(n);}catch{return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...e.length?{additionalContext:e.join(`
12
+ `)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,n,e,t]=process.argv;n!=="session-start"||!e?process.exitCode=2:process.stdout.write(mn({projectRoot:e,configPath:t,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var fn=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu;function gn(n){let e=n.trim();return e.length>0&&!fn.test(e)}function yn(n,e,t=Date.now()){let r=createHash("sha256").update(e.trim()).digest("hex"),o=createHash("sha256").update(`${n}\0${t}\0${r}`).digest("hex").slice(0,24);return {turnId:`turn:${o}`,eventId:`memory-turn:${o}`,promptHash:r,createdAt:t}}function hn(n,e,t=[]){return `memory-receipt:${createHash("sha256").update(`${n}\0${e}\0${[...t].sort().join("\0")}`).digest("hex").slice(0,24)}`}function Ve(n){return `DevFlow memory decision required for ${n.turnId}. Before the final response, semantically decide whether this turn contains durable project knowledge. Call mcp__devflow__memory_commit_turn with evidence-bound candidates, or mcp__devflow__memory_skip_turn with a concrete reason. Do not claim memory success without a canonical receipt. If the decision tool remains unavailable, explicitly state that the memory was not saved.`}function X(n){let e=n.memoryIds.length>0?n.memoryIds.join(","):"none",t=n.status==="committed"?"accepted":n.status,r=n.status==="committed"?"; indexStatus=pending":"",o=n.status==="committed"&&n.source==="explicit_intent"?"; memoryOnlyCompleted=true; skipProjectContext=true; skipMemoryTool=true":"",i=n.status==="committed"&&n.source==="explicit_intent"?" This explicit-memory request is complete. Return the canonical receipt to the user. Do not call a memory tool, project-context tool, domain tool, or native memory write for this request.":"";return `DevFlow canonical memory receipt: status=${t}; receiptId=${n.receiptId??"missing"}; turnId=${n.turnId}; memoryIds=${e}; source=${n.source??"unknown"}${r}${o}.`+i}function Be(n){if(!gn(n.prompt))return null;let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let t=n.prompt.trim().slice(0,4e3),r=createHash("sha256").update(t).digest("hex"),o=e.listMemoryTurns(n.projectRoot,n.sessionId,5).find(d=>d.promptHash===r&&Date.now()-d.createdAt<1e4),i=o?{turnId:o.turnId,eventId:o.eventId,promptHash:o.promptHash,createdAt:o.createdAt}:yn(n.sessionId,t),s=o??e.beginMemoryTurn({...i,projectRoot:n.projectRoot,sessionId:n.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:X(s),skipSkillRouting:s.source==="explicit_intent"};let a=x(t)??void 0,c=a?"commit_explicit":"capture_prompt";return e.enqueueWork({idempotencyKey:`memory-turn:${c}:${s.turnId}`,kind:a?"memory.explicit_commit":"memory.turn_capture",projectRoot:n.projectRoot,sessionId:n.sessionId,turnId:s.turnId,payload:{operation:c,turnId:s.turnId,eventId:s.eventId,sessionId:n.sessionId,prompt:t,explicitContent:a,createdAt:s.createdAt}}),{turn:s,explicitContent:a,additionalContext:a?`DevFlow explicit memory is durably queued for ${s.turnId}, but no canonical receipt exists yet. Do not claim that it was remembered.`:Ve(s),skipSkillRouting:!!a}}finally{e.close();}}async function Ke(n){let{payload:e,memory:t,projectRoot:r}=n,o=openGlobalDevFlowDatabase();try{let i=o.getMemoryTurn(e.turnId);if(!i)throw new Error(`Memory turn ${e.turnId} does not exist`);if(i.status!=="pending")return {turn:i,additionalContext:X(i),skipSkillRouting:i.source==="explicit_intent"};if(await t.recordUserMessage(e.prompt,e.sessionId,e.prompt.slice(0,200)),await t.recordEvent({id:e.eventId,sessionId:e.sessionId,tool:"UserPromptSubmit",kind:"user_message",payload:{prompt:e.prompt,turnId:e.turnId},createdAt:e.createdAt}),e.operation==="capture_prompt"||!e.explicitContent)return {turn:i,additionalContext:Ve(i),skipSkillRouting:!1};let s=await t.saveExplicitMemoryIntent(e.explicitContent,e.sessionId,e.eventId),a=hn(i.turnId,"committed",[s.id]),c=o.commitMemoryTurn({turnId:i.turnId,receiptId:a,memoryIds:[s.id],source:"explicit_intent",reason:"explicit_user_request"});try{await t.enrichExplicitMemoryObservation(s.id);}catch(d){console.error("[devflow] Explicit memory enrichment deferred:",d.message),o.enqueueWork({idempotencyKey:`explicit-enrichment:${r}:${s.id}`,kind:"memory.explicit_enrichment",projectRoot:r,sessionId:e.sessionId,turnId:c.turnId,payload:{observationId:s.id},maxAttempts:20});}o.enqueueWork({idempotencyKey:`vector:${r}:${s.id}`,kind:"memory.vector_backfill",projectRoot:r,sessionId:e.sessionId,turnId:c.turnId,payload:{observationId:s.id},maxAttempts:20});try{await Ge({projectRoot:r,memory:t,injectConfig:loadConfig(r).sessionStart?.injectMemories,reason:"explicit_memory_commit"});}catch(d){console.error("[devflow] Memory snapshot refresh failed after canonical commit:",d.message);}return {turn:c,explicitContent:e.explicitContent,additionalContext:X(c),skipSkillRouting:!0}}finally{o.close();}}function Xe(n,e){let t=wn(n);mkdirSync(t,{recursive:true,mode:448});let r=`memory-turn-spool-${Date.now()}-${process.pid}-${randomUUID()}`,o=join(t,`${r}.json`),i=`${o}.tmp`;return writeFileSync(i,JSON.stringify({...e,prompt:e.prompt.trim().slice(0,4e3)}),{mode:384}),renameSync(i,o),r}function wn(n){return join(S(n),"memory-turn-pending")}var p=process.env.CLAUDE_PROJECT_DIR||process.cwd();async function Rn(n){let e=ee()?[Q]:[],t;try{t=JSON.parse(n);}catch{return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...e.length?{additionalContext:e.join(`
13
13
  `)}:{}}}}let r=t.prompt||"";if(!r.trim())return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...e.length?{additionalContext:e.join(`
14
14
  `)}:{}}};let o=t.session_id?.trim(),i=me(r),s=false;if(o)try{let a=Be({projectRoot:p,sessionId:o,prompt:r});if(a){let c=a;if(a.explicitContent&&a.turn.status==="pending"){let d=new MemoryGate(p);try{c=await Ke({projectRoot:p,payload:{operation:"commit_explicit",turnId:a.turn.turnId,eventId:a.turn.eventId,sessionId:o,prompt:r.trim().slice(0,4e3),explicitContent:a.explicitContent,createdAt:a.turn.createdAt},memory:d});}catch(u){console.error("[devflow] Explicit memory commit deferred:",u.message);}finally{d.close();}}e.push(c.additionalContext),s=c.skipSkillRouting;}}catch(a){s=!!x(r);try{let c=Xe(p,{sessionId:o,prompt:r,createdAt:Date.now()});e.push(`DevFlow memory turn status=accepted; durable=true; receiptId=${c}; canonicalMemory=false; SQLite queue replay pending. Do not claim memory success without a canonical receipt.`),console.error("[devflow] Memory turn spooled after database contention:",a.message);}catch(c){e.push("DevFlow memory turn status=degraded; durable=false; no canonical receipt exists. Do not claim memory success."),console.error("[devflow] Memory turn persistence unavailable:",c.message);}}if(o&&i&&!s){let a=new k(p),c=a.get(o)?.executionId,d=a.startExecution(o,i.skillName,fe(i.skillName));if(d.executionId&&d.executionId!==c){let l=new M;try{await l.sendSessionStart(o,p,d.startedAt),await l.sendExecutionStart(d.executionId,o,i.skillName,d.lastActivityAt,p,d.requiredMcpTools);}finally{l.close();}}let u=formatSkillRuntimeOverlay(createSkillRuntimeOverlay(i.skillName,p));u&&e.push(u);}return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...e.length?{additionalContext:e.join(`
15
15
  `)}:{}}}}if(process.argv[1]?.endsWith("user-prompt-submit")||process.argv[1]?.endsWith("user-prompt-submit.js")){let n=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t;}),process.stdin.on("end",async()=>{let t=await Rn(e.trim()||process.argv[2]||"");n(JSON.stringify(t)),process.exit(0);}),process.stdin.on("error",()=>{n(JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow"}})),process.exit(0);}),setTimeout(()=>{n(JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow"}})),process.exit(0);},3e4).unref();}export{Rn as handleUserPromptSubmit};
@@ -4,17 +4,19 @@ set -euo pipefail
4
4
  # DevFlow PostToolUse Hook — talks to hook-daemon via hook-client
5
5
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6
6
  PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$SCRIPT_DIR/..}"
7
+ source "$SCRIPT_DIR/runtime-node"
8
+ DEVFLOW_NODE="$(devflow_resolve_node "$PLUGIN_ROOT")"
7
9
  CLIENT_JS="$PLUGIN_ROOT/dist/hooks/hook-client.js"
8
10
  FALLBACK_JS="$PLUGIN_ROOT/dist/hooks/post-tool-use.js"
9
11
 
10
12
  INPUT="$(cat)"
11
13
 
12
14
  if [ -f "$CLIENT_JS" ]; then
13
- node "$CLIENT_JS" post-tool-use "$INPUT" 2>/dev/null || {
14
- echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
15
+ "$DEVFLOW_NODE" "$CLIENT_JS" post-tool-use "$INPUT" 2>/dev/null || {
16
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 "$DEVFLOW_NODE" "$FALLBACK_JS" 2>/dev/null || true
15
17
  }
16
18
  elif [ -f "$FALLBACK_JS" ]; then
17
- echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
19
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 "$DEVFLOW_NODE" "$FALLBACK_JS" 2>/dev/null || true
18
20
  fi
19
21
 
20
22
  exit 0
@@ -3,17 +3,19 @@ set -euo pipefail
3
3
 
4
4
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
5
  PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$SCRIPT_DIR/..}"
6
+ source "$SCRIPT_DIR/runtime-node"
7
+ DEVFLOW_NODE="$(devflow_resolve_node "$PLUGIN_ROOT")"
6
8
  CLIENT_JS="$PLUGIN_ROOT/dist/hooks/hook-client.js"
7
9
  FALLBACK_JS="$PLUGIN_ROOT/dist/hooks/post-tool-use-failure.js"
8
10
 
9
11
  INPUT="$(cat)"
10
12
 
11
13
  if [ -f "$CLIENT_JS" ]; then
12
- node "$CLIENT_JS" post-tool-use-failure "$INPUT" 2>/dev/null || {
13
- echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
14
+ "$DEVFLOW_NODE" "$CLIENT_JS" post-tool-use-failure "$INPUT" 2>/dev/null || {
15
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 "$DEVFLOW_NODE" "$FALLBACK_JS" 2>/dev/null || true
14
16
  }
15
17
  elif [ -f "$FALLBACK_JS" ]; then
16
- echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
18
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 "$DEVFLOW_NODE" "$FALLBACK_JS" 2>/dev/null || true
17
19
  fi
18
20
 
19
21
  exit 0
@@ -3,17 +3,19 @@ set -euo pipefail
3
3
 
4
4
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
5
  PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$SCRIPT_DIR/..}"
6
+ source "$SCRIPT_DIR/runtime-node"
7
+ DEVFLOW_NODE="$(devflow_resolve_node "$PLUGIN_ROOT")"
6
8
  CLIENT_JS="$PLUGIN_ROOT/dist/hooks/hook-client.js"
7
9
  FALLBACK_JS="$PLUGIN_ROOT/dist/hooks/pre-compact.js"
8
10
 
9
11
  INPUT="$(cat)"
10
12
 
11
13
  if [ -f "$CLIENT_JS" ]; then
12
- node "$CLIENT_JS" pre-compact "$INPUT" 2>/dev/null || {
13
- echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
14
+ "$DEVFLOW_NODE" "$CLIENT_JS" pre-compact "$INPUT" 2>/dev/null || {
15
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 "$DEVFLOW_NODE" "$FALLBACK_JS" 2>/dev/null || true
14
16
  }
15
17
  elif [ -f "$FALLBACK_JS" ]; then
16
- echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
18
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 "$DEVFLOW_NODE" "$FALLBACK_JS" 2>/dev/null || true
17
19
  fi
18
20
 
19
21
  exit 0
@@ -4,20 +4,22 @@ set -euo pipefail
4
4
  # DevFlow PreToolUse Hook — talks to hook-daemon via hook-client
5
5
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6
6
  PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$SCRIPT_DIR/..}"
7
+ source "$SCRIPT_DIR/runtime-node"
8
+ DEVFLOW_NODE="$(devflow_resolve_node "$PLUGIN_ROOT")"
7
9
  CLIENT_JS="$PLUGIN_ROOT/dist/hooks/hook-client.js"
8
10
  FALLBACK_JS="$PLUGIN_ROOT/dist/hooks/pre-tool-use.js"
9
11
 
10
12
  if [ -f "$CLIENT_JS" ]; then
11
- node "$CLIENT_JS" pre-tool-use || {
13
+ "$DEVFLOW_NODE" "$CLIENT_JS" pre-tool-use || {
12
14
  echo '[devflow] hook-client failed, trying fallback' >&2
13
15
  if [ -f "$FALLBACK_JS" ]; then
14
- DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" || echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"WARNING: DevFlow is in degraded mode (daemon unreachable). Run devflow doctor for details."}}'
16
+ DEVFLOW_HOOK_DEGRADED=1 "$DEVFLOW_NODE" "$FALLBACK_JS" || echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"WARNING: DevFlow is in degraded mode (daemon unreachable). Run devflow doctor for details."}}'
15
17
  else
16
18
  echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"WARNING: DevFlow is in degraded mode (daemon unreachable). Run devflow doctor for details."}}'
17
19
  fi
18
20
  }
19
21
  elif [ -f "$FALLBACK_JS" ]; then
20
- DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" || echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"WARNING: DevFlow is in degraded mode (daemon unavailable). Run devflow doctor for details."}}'
22
+ DEVFLOW_HOOK_DEGRADED=1 "$DEVFLOW_NODE" "$FALLBACK_JS" || echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"WARNING: DevFlow is in degraded mode (daemon unavailable). Run devflow doctor for details."}}'
21
23
  else
22
24
  echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"WARNING: DevFlow is in degraded mode (daemon unavailable). Run devflow doctor for details."}}'
23
25
  fi
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env bash
2
+
3
+ devflow_resolve_node() {
4
+ local plugin_root="${1:-}"
5
+ local marker="${plugin_root}/.devflow-hook-node"
6
+ local candidate=""
7
+
8
+ if [ -n "${DEVFLOW_HOOK_NODE:-}" ] && [ -x "${DEVFLOW_HOOK_NODE}" ]; then
9
+ printf '%s\n' "${DEVFLOW_HOOK_NODE}"
10
+ return 0
11
+ fi
12
+ if [ -f "$marker" ]; then
13
+ IFS= read -r candidate < "$marker" || candidate=""
14
+ if [ -n "$candidate" ] && [ -x "$candidate" ]; then
15
+ printf '%s\n' "$candidate"
16
+ return 0
17
+ fi
18
+ fi
19
+ candidate="${HOME:-}/.hermes/node/bin/node"
20
+ if [ -x "$candidate" ]; then
21
+ printf '%s\n' "$candidate"
22
+ return 0
23
+ fi
24
+ command -v node 2>/dev/null
25
+ }
@@ -3,17 +3,19 @@ set -euo pipefail
3
3
 
4
4
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
5
  PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$SCRIPT_DIR/..}"
6
+ source "$SCRIPT_DIR/runtime-node"
7
+ DEVFLOW_NODE="$(devflow_resolve_node "$PLUGIN_ROOT")"
6
8
  CLIENT_JS="$PLUGIN_ROOT/dist/hooks/hook-client.js"
7
9
  FALLBACK_JS="$PLUGIN_ROOT/dist/hooks/session-end.js"
8
10
 
9
11
  INPUT="$(cat)"
10
12
 
11
13
  if [ -f "$CLIENT_JS" ]; then
12
- node "$CLIENT_JS" session-end "$INPUT" 2>/dev/null || {
13
- echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
14
+ "$DEVFLOW_NODE" "$CLIENT_JS" session-end "$INPUT" 2>/dev/null || {
15
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 "$DEVFLOW_NODE" "$FALLBACK_JS" 2>/dev/null || true
14
16
  }
15
17
  elif [ -f "$FALLBACK_JS" ]; then
16
- echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
18
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 "$DEVFLOW_NODE" "$FALLBACK_JS" 2>/dev/null || true
17
19
  fi
18
20
 
19
21
  exit 0