@devflow-tools/devflow 0.16.19 → 0.16.20

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.
Files changed (46) hide show
  1. package/dist/dashboard/404.html +1 -1
  2. package/dist/dashboard/accuracy.html +1 -1
  3. package/dist/dashboard/accuracy.txt +1 -1
  4. package/dist/dashboard/benchmark.html +1 -1
  5. package/dist/dashboard/benchmark.txt +1 -1
  6. package/dist/dashboard/context.html +1 -1
  7. package/dist/dashboard/context.txt +1 -1
  8. package/dist/dashboard/doctor.html +1 -1
  9. package/dist/dashboard/doctor.txt +1 -1
  10. package/dist/dashboard/executions.html +1 -1
  11. package/dist/dashboard/executions.txt +1 -1
  12. package/dist/dashboard/graph.html +1 -1
  13. package/dist/dashboard/graph.txt +1 -1
  14. package/dist/dashboard/index.html +1 -1
  15. package/dist/dashboard/index.txt +1 -1
  16. package/dist/dashboard/knowledge.html +1 -1
  17. package/dist/dashboard/knowledge.txt +1 -1
  18. package/dist/dashboard/memory.html +1 -1
  19. package/dist/dashboard/memory.txt +1 -1
  20. package/dist/dashboard/replay.html +1 -1
  21. package/dist/dashboard/replay.txt +1 -1
  22. package/dist/dashboard/runs/_.html +1 -1
  23. package/dist/dashboard/runs/_.txt +1 -1
  24. package/dist/dashboard/runs.html +1 -1
  25. package/dist/dashboard/runs.txt +1 -1
  26. package/dist/dashboard/settings.html +1 -1
  27. package/dist/dashboard/settings.txt +1 -1
  28. package/dist/dashboard/timeline.html +1 -1
  29. package/dist/dashboard/timeline.txt +1 -1
  30. package/dist/dashboard/tool-metrics.html +1 -1
  31. package/dist/dashboard/tool-metrics.txt +1 -1
  32. package/dist/dashboard/workflows.html +1 -1
  33. package/dist/dashboard/workflows.txt +1 -1
  34. package/dist/hooks/hook-daemon.js +20 -20
  35. package/dist/hooks/session-end.js +4 -4
  36. package/dist/hooks/stop.js +3 -3
  37. package/dist/plugin/.claude-plugin/plugin.json +1 -1
  38. package/dist/plugin/dist/command-registry.json +5 -5
  39. package/dist/plugin/dist/hooks/hook-daemon.js +20 -20
  40. package/dist/plugin/dist/hooks/session-end.js +4 -4
  41. package/dist/plugin/dist/hooks/stop.js +3 -3
  42. package/dist/plugin/package.json +7 -7
  43. package/package.json +12 -12
  44. package/plugin-registry.json +29 -29
  45. /package/dist/dashboard/_next/static/{V7t1iyp5xi_ydOtGqDPEW → pEkEPvlvTqJWE9N1skzzu}/_buildManifest.js +0 -0
  46. /package/dist/dashboard/_next/static/{V7t1iyp5xi_ydOtGqDPEW → pEkEPvlvTqJWE9N1skzzu}/_ssgManifest.js +0 -0
@@ -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(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
+ 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 j(o){return o??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function w(o){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(j(o))}function W(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 He=getLocalApiKey(),G=join(homedir(),".devflow","errors");async function O(o,t,e={}){let n=e.endpoint??resolveRuntimeEndpoint().url,i=e.timeout??1500,r=e.durableMirror??true,s=e.maxRetries??(r?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 Ue(n,o,t,i),a&&registerRuntimeHttpSuccess(n,o).transitioned&&W("http_circuit_transition",{endpoint:n,path:new URL(o,n).pathname,previous:l.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(h){u=h instanceof Error?h:new Error(String(h)),g<s&&await Be(Math.min(100*2**g,1e3));}if(!u)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return se(o,u),{delivered:false,suppressed:false,fallbackReason:u.message};let p=registerRuntimeHttpFailure(n,o,e.fallbackReason??(r?"local_durable_mirror":"http_delivery_failed"));return p.transitioned&&(se(o,u),W("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 Ue(o,t,e,n){return new Promise((i,r)=>{let s=JSON.stringify(e),a=new URL(t,o),l=false,u=g=>{l||(l=true,g?r(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":He,"Content-Length":Buffer.byteLength(s)},timeout:n},g=>{g.on("error",u),g.on("end",()=>{let h=g.statusCode??0;u(h>=200&&h<300?void 0:new Error(`HTTP ${h}`));}),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 se(o,t){try{existsSync(G)||mkdirSync(G,{recursive:!0}),appendFileSync(join(G,"http-errors.log"),`${new Date().toISOString()} | ${o} | ${t.message}
2
+ `);}catch{}}function Be(o){return new Promise(t=>setTimeout(t,o))}var pe=1e4,Xe=3e4,L=500,N=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,r=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:t,sessionId:e,skillName:n,startedAt:i,projectRoot:r,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 r={executionId:t,status:e,finishedAt:n,metadata:i},s=this.commitOrCache("execution_complete",r);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",r),s}async sendSessionStart(t,e,n){let i={id:t,projectRoot:e,startedAt:n,label:e.split("/").pop()??"unknown"},r=this.commitOrCache("session_start",i);return r&&this.postHttp("/api/telemetry/sessions",i),r}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:L}).reverse();for(let r of i)try{this.applyOperation(r.operation,r.payload),n.resolveTelemetryFailure(r.id);}catch{}n.trimTelemetryFailures(L);}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 r=join$1(n,i);try{return {cacheFile:r,envelope:Ye(JSON.parse(readFileSync(r,"utf8")),i)}}catch{return null}})).filter(n=>n!==null).sort((n,i)=>n.envelope.timestamp-i.envelope.timestamp||ge(n.envelope.operation)-ge(i.envelope.operation));for(let{cacheFile:n,envelope:i}of e)try{let r=this.getDatabase();r.insertTelemetryFailure({id:i.id,operation:i.operation,payload:i.payload,error:i.failure,createdAt:i.timestamp}),this.applyOperation(i.operation,i.payload),r.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:me(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(me(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(),r={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:r.id,operation:t,payload:e,error:r.failure,createdAt:i}),s.trimTelemetryFailures(L),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(r,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-L)))unlinkSync$1(join$1(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},Xe).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<=pe?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,pe)}...`}}};function ge(o){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(o)}function me(o){return `hook-run:${o}`}function Ye(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 i=e.payload??{},r=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:r}}async function fe(o){let t=!o.memory,e=o.memory??new MemoryGate(o.projectRoot),n=0,i=0;try{await e.forceWarmUp(),o.trigger==="session_end"&&(n=await e.releasePendingDistillLeases(o.sessionId)),i=e.getPendingEventCount(o.sessionId,o.trigger!=="session_end");}finally{t&&e.close();}let r={pendingEvents:i,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:i,releasedLeases:n,details:o.details,createdAt:a}),s.insertEvent({kind:"memory_distill_requested",timestamp:a,success:!0,metadata:{...r,projectRoot:o.projectRoot}});}finally{s.close();}}catch(s){throw s}return r}function ve(o){return Buffer.from(o,"utf8").toString("base64url")}function rt(o,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 `${o}:${i}`}return `${o}:legacy-${e}-${randomUUID().slice(0,8)}`}function Re(o){return `${o}:legacy-journal`}var D=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(w(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(),r={sessionId:e,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:i,lastActivityAt:i};return this.sessions.set(e,r),this.persist(r),r}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 r=JSON.parse(readFileSync(i,"utf8"));return r.sessionId!==e||r.projectRoot!==this.projectRoot?null:(r.requiredMcpTools=Array.isArray(r.requiredMcpTools)?r.requiredMcpTools:[],r.evidenceObligations=Se(r.evidenceObligations),r.evidenceDegradations=we(r.evidenceDegradations),r.evidenceOutcomes=Ee(r.evidenceOutcomes),this.replayEvidenceJournal(r),this.sessions.set(e,r),r)}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 r=this.registerSession(t),a=(i?void 0:r.evidenceObligations.find(u=>u.contractId===e.id))?.obligationId??rt(e.id,i,n);this.appendEvidenceEvent(t,{kind:"add",obligationId:a,contractId:e.id,at:n,contract:e},`add\0${a}`),this.replayEvidenceJournal(r);let l=r.evidenceObligations.find(u=>u.obligationId===a);return l?(r.lastActivityAt=Date.now(),this.persist(r),structuredClone(l)):null}listEvidenceObligations(t){return (this.get(t)?.evidenceObligations??[]).map(e=>structuredClone(e))}markEvidenceCorrection(t,e,n,i,r=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:r,fingerprint:l,violations:n.slice(0,16).map(p=>p.slice(0,240))},`correction\0${e}\0${l}`),this.replayEvidenceJournal(s),s.lastActivityAt=r,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 r=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:i.contractId,at:r},`resolve\0${e}`),this.replayEvidenceJournal(n),n.lastActivityAt=r,this.persist(n),true}degradeEvidenceObligation(t,e,n,i=Date.now()){let r=this.get(t),s=r?.evidenceObligations.find(l=>l.obligationId===e);if(!r||!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(r),r.lastActivityAt=i,this.persist(r),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,`${ve(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",ve(t))}appendEvidenceEvent(t,e,n){let i=this.evidenceJournalDir(t);mkdirSync$1(i,{recursive:true,mode:448});let r=createHash$1("sha256").update(n).digest("hex"),s=join$1(i,`${e.kind}-${r}.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=Se(t.evidenceObligations),t.evidenceDegradations=we(t.evidenceDegradations),t.evidenceOutcomes=Ee(t.evidenceOutcomes);let e=this.evidenceJournalDir(t.sessionId);if(!existsSync$1(e))return;let n;try{n=readdirSync(e).filter(r=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(r)).slice(0,4096);}catch{return}let i=n.flatMap(r=>{try{let s=readFileSync(join$1(e,r),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=ot(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((r,s)=>r.at-s.at||_e(r.kind)-_e(s.kind));for(let r of i)this.applyEvidenceEvent(t,r);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 r=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:r}),t.evidenceOutcomes.push({obligationId:e.obligationId,contractId:e.contractId,status:e.kind==="resolve"?"resolved":"degraded",completedAt:e.at,attempt:r,...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 Se(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)||!ke(e.contract))return [];let n=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:Re(e.contractId),i=typeof e.correctionTranscriptHash=="string"?e.correctionTranscriptHash:void 0,r=e.correctionFingerprint??i;return r!==void 0&&!/^[a-f0-9]{64}$/.test(r)?[]:[{...e,obligationId:n,correctionFingerprint:r}]}).slice(-8):[]}function we(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 Ee(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 ot(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:Re(t.contractId);if(t.kind==="add")return ke(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 _e(o){return o==="add"?0:o==="correction"?1:2}function ke(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(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 Oe(o,t){let e=dt(o);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(r){try{unlinkSync(i);}catch{}if(!existsSync(n))throw r}return t.receiptId}function dt(o){return join(w(o),"session-finalize-pending")}var ht=512*1024,yt=500;var bt=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function vt(o){let t=false,e=[],n=[];for(let i of o){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,(r,s)=>St(s)?"":s).trim());}return {headingLines:e,claimLines:n}}function St(o){let t=o.trim().slice(0,256);return !t||/\s/.test(t)||o.trim().length>256?false:/^[A-Za-z_$][\w$.-]*$/.test(t)||/^(['"])[^'"`]*\1$/.test(t)}function wt(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 i=fstatSync(e);if(!i.isFile()||i.dev!==n.dev||i.ino!==n.ino)return {degradationReason:"transcript_path_changed"};let r=Math.min(i.size,ht),s=Buffer.alloc(r),a=0;for(;a<r;){let y=readSync(e,s,a,r-a,i.size-r+a);if(y===0)break;a+=y;}let l=s.subarray(0,a).toString("utf8");i.size>r&&(l=l.slice(Math.max(0,l.indexOf(`
3
+ `)+1)));let u=l.split(/\r?\n/).slice(-yt),p=t.length>0?Math.min(...t.map(y=>y.promptedAt)):0,g=_t(u,p),b=[...g].reverse().find(y=>Et(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 Et(o,t){let e=new Set(t.flatMap(i=>i.contract.requiredSections)),n=Rt(vt(o.split(/\r?\n/u)).headingLines);return [...e].every(i=>n.found.has(i))}function Ce(o){return wt(o,[]).answer}function _t(o,t){let e=[];for(let n=0;n<o.length;n++){let i=o[n];if(i.trim())try{let r=JSON.parse(i),s=r.message;if(!s||typeof s!="object"||s.role!=="assistant")continue;let a=s,l=It(r.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(),h=typeof a.id=="string"&&a.id?`message:${a.id}`:typeof r.uuid=="string"&&r.uuid?`uuid:${r.uuid}`:`record:${String(r.timestamp??"")}:${n}:${createHash("sha256").update(i).digest("hex")}`,b=createHash("sha256").update(g).digest("hex"),y=createHash("sha256").update(`${h}\0${b}`).digest("hex");e.push({text:g,timestamp:l,fingerprint:y});}}catch{continue}}return e}function It(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 Rt(o){let t=new Set,e=new Map,n;for(let i=0;i<o.length;i++){let r=o[i].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=bt.find(a=>r===a);s&&(n=s,t.add(s)),e.set(i,n);}return {found:t,byLine:e}}function Ot(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 R=class extends Error{constructor(t,e){super(`session_finalize_${t}:${e}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${t}`;}};function J(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 Dt(o,t=j(),e=true,n,i=true){let r;try{r=JSON.parse(o);}catch{return null}let s=r.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(!i)throw p;return Oe(t,{receiptId:a,...l}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{u?.close();}}async function Un(o,t=j(),e=true,n){let i;try{i=JSON.parse(o);}catch{return}let r=i.session_id?.trim();if(!r)return;let s=new D(t),a=s.get(r),l={evidenceDegradations:a?.evidenceDegradations??[],evidenceContractOutcomes:a?.evidenceOutcomes??[],pendingEvidenceContractIds:a?.evidenceObligations.map(b=>b.contractId)??[]},u=n?.telemetry??new N,p=!n?.telemetry,g=false,h;try{try{await u.flushAndAggregate();}catch{}let b=Date.now(),y=n?.executionId??a?.executionId,T;try{let m=openGlobalDevFlowDatabase();try{T=m.listSessionMemoryTurnsForReconciliation(t,r);for(let c of T){let f=`memory:${c.turnId}`,d=m.getSessionObligation(t,r,f);d?d.state==="open"&&c.status!=="pending"&&m.resolveSessionObligation({projectRoot:t,sessionId:r,obligationId:f,state:"satisfied",receiptId:c.receiptId,reason:c.reason,resolvedAt:c.decidedAt}):m.upsertSessionObligation({obligationId:f,projectRoot:t,sessionId:r,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),f={...l,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:c,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw J({projectRoot:t,sessionId:r,executionId:y,stage:"turn_load",reason:c,metadata:f}),new R("turn_load",c)}let $=Ot(T),P=n?.memory??(h=new MemoryGate(t)),M={status:"unknown",selected:0,adopted:0,unknown:0,positive:0,negative:0};try{let m=Ce(i.transcript_path),c=openGlobalDevFlowDatabase(),f="unknown",d="no_terminal_host_action_evidence",F,z,K,Q=[];try{let H=c.listHostActionsForSession(t,r,y),ee=H.filter(x=>x.state==="verified"),U=H.filter(x=>["failed","cancelled","degraded"].includes(x.state));U.length>0?(f="negative",d=`terminal_host_action_${U[0].state}`):ee.length>0&&(f="positive",d="host_action_verified");let B=U[0]??ee.at(-1);F=B?.runId,z=B?.contextReceipt,K=B?.evidenceHash,Q=H.flatMap(x=>{let te=x.report.toolUseIds;return Array.isArray(te)?te.filter(Pe=>typeof Pe=="string"):[]});}finally{c.close();}let $e=await P.attributeRetrievalBenefits({sessionId:r,executionId:y,finalAnswer:m,outcome:f,outcomeReason:d,workflowRunId:F,contextReceipt:z,toolEvidence:Q,verificationReceipt:K});M={status:m?"evaluated":"unknown",...$e};}catch(m){M={...M,status:"degraded",reason:C(m)};}let S;try{S=await P.reconcileDecidedTurnEventWindows(r,T,b);}catch(m){let c=C(m),f={...$,...l,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:c,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw J({projectRoot:t,sessionId:r,executionId:y,stage:"event_reconciliation",reason:c,metadata:f}),new R("event_reconciliation",c)}let k;try{k=await fe({projectRoot:t,sessionId:r,trigger:"session_end",memory:P,details:{eventReconciliation:S},strictPersistence:!0});}catch(m){let c=C(m),f={...$,...l,memoryEventReconciliation:{status:"completed",...S,checkpointPending:null},memoryCheckpointDegradation:c};throw J({projectRoot:t,sessionId:r,executionId:y,stage:"checkpoint",reason:c,metadata:f}),new R("checkpoint",c)}let Y={memoryBenefitAttribution:M,memoryEventReconciliation:{status:"completed",...S,checkpointPending:k.pendingEvents},memoryDistillCheckpoint:k};try{let m=openGlobalDevFlowDatabase();try{let c=`session-finalize:${r}:events`,f=Math.max(Number(k.pendingEvents??0),Number(S.remainingUndecided??0)),d=m.getSessionObligation(t,r,c);f>0?m.upsertSessionObligation({obligationId:c,projectRoot:t,sessionId:r,executionId:y,kind:"session_finalize",state:"open",payload:{pendingEvents:f,reconciliation:S,checkpointId:k.id},reason:"active_unprocessed_session_events",createdAt:d?.createdAt??b,updatedAt:b}):d?.state==="open"&&m.resolveSessionObligation({projectRoot:t,sessionId:r,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 P.closeSession(r),h&&(h.close(),h=void 0);}catch(m){let c=C(m),f={...$,...l,...Y,memorySessionCloseDegradation:c};throw J({projectRoot:t,sessionId:r,executionId:y,stage:"memory_close",reason:c,metadata:f}),new R("memory_close",c)}let A={...$,...l,...Y};g=!0;let v;try{v=openGlobalDevFlowDatabase();let m=y;if(m)try{v.reconcileSkillExecution(m,"completed",b,A);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:A},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let c=v.reconcileRunningSkillExecutionsForSession(r,b,{closureReason:"session_finalize",...A});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:A},{fallbackReason:"skill_execution_already_reconciled_locally"});let f=v.getLatestSkillExecutionForSession(r);if(f&&!c.some(d=>d.executionId===f.executionId)&&v.mergeSkillExecutionMetadata(f.executionId,A),e){v.deleteHookReceipt(t);let d=w(t),F=createHash("sha256").update(t).digest("hex").slice(0,12);for(let z of [`session-id-${F}`,"current-execution-id","current-skill.json","event-map.json"])rmSync(join(d,z),{force:!0});}v.deleteContextReceipt(t,r);}catch{}finally{v?.close();}try{await u.endSession(r),await u.flushAndAggregate();}catch{}}finally{if(h)try{h.close();}catch{}p&&u.close(),g&&s.removeSession(r);}}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=Dt(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{Ot as buildMemoryTurnOutcomeMetadata,Dt as enqueueSessionEndFinalization,Un as handleSessionEnd};
@@ -5,9 +5,9 @@ import {getLocalApiKey,resolveRuntimeEndpoint,acquireRuntimeHttpCircuit,register
5
5
 
6
6
  `)].join(`
7
7
 
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})
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 f of n.matchAll(o))ee(n,f.index??0,f[0],"p0")||r.add("unsupported_p0_severity");let i=/(?:中高|高)(?:风险|优先级)|严重(?:问题|风险)|\bhigh[- ](?:risk|severity|priority)\b/gi;for(let f of n.matchAll(i))ee(n,f.index??0,f[0],"high")||r.add("unsupported_high_severity");let s=/(?:性能)?瓶颈|卡顿|掉帧|CPU\s*(?:热点|尖峰)|\bbottleneck\b|\bjank\b|\bdropped frames?\b|\bCPU hotspot\b/gi;for(let f of n.matchAll(s))Xe(n,f.index??0,f[0])||(/(?:瓶颈|bottleneck)/i.test(f[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),g=/(?:建议|应该|应当|使用|添加|采用|切换|包裹|优化|节流|\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&&g&&!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),g=[...u].reverse().find(p=>Ze(p.text,e))??u.at(-1);return g?.text?{answer:g.text,fingerprint:g.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")}`,g=createHash("sha256").update(u).digest("hex"),p=createHash("sha256").update(`${m}\0${g}`).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,ft=240,gt=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+gt||!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,ft).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
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
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(`
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devflow-tools/claude-code-plugin",
3
- "version": "0.16.19",
3
+ "version": "0.16.20",
4
4
  "description": "DevFlow — Developer Intelligence Platform for Claude Code",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -11,18 +11,18 @@
11
11
  "prepack": "npm run verify:manifest"
12
12
  },
13
13
  "dependencies": {
14
- "@devflow-tools/database": "0.16.19",
15
- "@devflow-tools/memory-engine": "0.16.19",
16
- "@devflow-tools/sdk": "0.16.19",
17
- "@devflow-tools/telemetry": "0.16.19",
18
- "@devflow-tools/workflow-engine": "0.16.19"
14
+ "@devflow-tools/database": "0.16.20",
15
+ "@devflow-tools/memory-engine": "0.16.20",
16
+ "@devflow-tools/sdk": "0.16.20",
17
+ "@devflow-tools/telemetry": "0.16.20",
18
+ "@devflow-tools/workflow-engine": "0.16.20"
19
19
  },
20
20
  "allowScripts": {
21
21
  "better-sqlite3@12.11.1": true,
22
22
  "sharp@0.32.6": true
23
23
  },
24
24
  "devDependencies": {
25
- "@devflow-tools/mcp-server": "0.16.19"
25
+ "@devflow-tools/mcp-server": "0.16.20"
26
26
  },
27
27
  "keywords": [
28
28
  "pi-package",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devflow-tools/devflow",
3
- "version": "0.16.19",
3
+ "version": "0.16.20",
4
4
  "type": "module",
5
5
  "description": "DevFlow - Developer Intelligence Platform (Distribution Package)",
6
6
  "bin": {
@@ -16,17 +16,17 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "@colbymchenry/codegraph": "^1.1.1",
19
- "@devflow-tools/adapters": "0.16.19",
20
- "@devflow-tools/benchmark": "0.16.19",
21
- "@devflow-tools/context-engine": "0.16.19",
22
- "@devflow-tools/database": "0.16.19",
23
- "@devflow-tools/knowledge-engine": "0.16.19",
24
- "@devflow-tools/mcp-server": "0.16.19",
25
- "@devflow-tools/memory-engine": "0.16.19",
26
- "@devflow-tools/sdk": "0.16.19",
27
- "@devflow-tools/server": "0.16.19",
28
- "@devflow-tools/telemetry": "0.16.19",
29
- "@devflow-tools/workflow-engine": "0.16.19",
19
+ "@devflow-tools/adapters": "0.16.20",
20
+ "@devflow-tools/benchmark": "0.16.20",
21
+ "@devflow-tools/context-engine": "0.16.20",
22
+ "@devflow-tools/database": "0.16.20",
23
+ "@devflow-tools/knowledge-engine": "0.16.20",
24
+ "@devflow-tools/mcp-server": "0.16.20",
25
+ "@devflow-tools/memory-engine": "0.16.20",
26
+ "@devflow-tools/sdk": "0.16.20",
27
+ "@devflow-tools/server": "0.16.20",
28
+ "@devflow-tools/telemetry": "0.16.20",
29
+ "@devflow-tools/workflow-engine": "0.16.20",
30
30
  "@inquirer/prompts": "^7.10.1",
31
31
  "@modelcontextprotocol/sdk": "^1.0.0",
32
32
  "@nestjs/common": "^10.4.0",
@@ -1,172 +1,172 @@
1
1
  {
2
2
  "version": "1.0.0",
3
- "lastUpdated": "2026-07-28T06:42:40.570Z",
3
+ "lastUpdated": "2026-07-28T07:45:57.634Z",
4
4
  "plugins": [
5
5
  {
6
6
  "name": "@devflow-tools/plugin-animation",
7
- "version": "0.16.19",
7
+ "version": "0.16.20",
8
8
  "description": "",
9
9
  "tags": [],
10
10
  "compatibleStacks": [
11
11
  "animation"
12
12
  ],
13
- "size": "68902 B",
13
+ "size": "69078 B",
14
14
  "author": "DevFlow Team",
15
15
  "homepage": ""
16
16
  },
17
17
  {
18
18
  "name": "@devflow-tools/plugin-css",
19
- "version": "0.16.19",
19
+ "version": "0.16.20",
20
20
  "description": "",
21
21
  "tags": [],
22
22
  "compatibleStacks": [
23
23
  "css"
24
24
  ],
25
- "size": "56322 B",
25
+ "size": "56492 B",
26
26
  "author": "DevFlow Team",
27
27
  "homepage": ""
28
28
  },
29
29
  {
30
30
  "name": "@devflow-tools/plugin-docker",
31
- "version": "0.16.19",
31
+ "version": "0.16.20",
32
32
  "description": "",
33
33
  "tags": [],
34
34
  "compatibleStacks": [
35
35
  "docker"
36
36
  ],
37
- "size": "84934 B",
37
+ "size": "85107 B",
38
38
  "author": "DevFlow Team",
39
39
  "homepage": ""
40
40
  },
41
41
  {
42
42
  "name": "@devflow-tools/plugin-electron",
43
- "version": "0.16.19",
43
+ "version": "0.16.20",
44
44
  "description": "",
45
45
  "tags": [],
46
46
  "compatibleStacks": [
47
47
  "electron"
48
48
  ],
49
- "size": "100634 B",
49
+ "size": "100809 B",
50
50
  "author": "DevFlow Team",
51
51
  "homepage": ""
52
52
  },
53
53
  {
54
54
  "name": "@devflow-tools/plugin-git",
55
- "version": "0.16.19",
55
+ "version": "0.16.20",
56
56
  "description": "",
57
57
  "tags": [],
58
58
  "compatibleStacks": [
59
59
  "git"
60
60
  ],
61
- "size": "66630 B",
61
+ "size": "66800 B",
62
62
  "author": "DevFlow Team",
63
63
  "homepage": ""
64
64
  },
65
65
  {
66
66
  "name": "@devflow-tools/plugin-graphql",
67
- "version": "0.16.19",
67
+ "version": "0.16.20",
68
68
  "description": "",
69
69
  "tags": [],
70
70
  "compatibleStacks": [
71
71
  "graphql"
72
72
  ],
73
- "size": "68628 B",
73
+ "size": "68802 B",
74
74
  "author": "DevFlow Team",
75
75
  "homepage": ""
76
76
  },
77
77
  {
78
78
  "name": "@devflow-tools/plugin-nest",
79
- "version": "0.16.19",
79
+ "version": "0.16.20",
80
80
  "description": "",
81
81
  "tags": [],
82
82
  "compatibleStacks": [
83
83
  "nest"
84
84
  ],
85
- "size": "105439 B",
85
+ "size": "105610 B",
86
86
  "author": "DevFlow Team",
87
87
  "homepage": ""
88
88
  },
89
89
  {
90
90
  "name": "@devflow-tools/plugin-nextjs",
91
- "version": "0.16.19",
91
+ "version": "0.16.20",
92
92
  "description": "",
93
93
  "tags": [],
94
94
  "compatibleStacks": [
95
95
  "nextjs"
96
96
  ],
97
- "size": "67020 B",
97
+ "size": "67193 B",
98
98
  "author": "DevFlow Team",
99
99
  "homepage": ""
100
100
  },
101
101
  {
102
102
  "name": "@devflow-tools/plugin-performance",
103
- "version": "0.16.19",
103
+ "version": "0.16.20",
104
104
  "description": "",
105
105
  "tags": [],
106
106
  "compatibleStacks": [
107
107
  "performance"
108
108
  ],
109
- "size": "117173 B",
109
+ "size": "117351 B",
110
110
  "author": "DevFlow Team",
111
111
  "homepage": ""
112
112
  },
113
113
  {
114
114
  "name": "@devflow-tools/plugin-react",
115
- "version": "0.16.19",
115
+ "version": "0.16.20",
116
116
  "description": "",
117
117
  "tags": [],
118
118
  "compatibleStacks": [
119
119
  "react"
120
120
  ],
121
- "size": "244740 B",
121
+ "size": "244912 B",
122
122
  "author": "DevFlow Team",
123
123
  "homepage": ""
124
124
  },
125
125
  {
126
126
  "name": "@devflow-tools/plugin-tailwind",
127
- "version": "0.16.19",
127
+ "version": "0.16.20",
128
128
  "description": "",
129
129
  "tags": [],
130
130
  "compatibleStacks": [
131
131
  "tailwind"
132
132
  ],
133
- "size": "73332 B",
133
+ "size": "73507 B",
134
134
  "author": "DevFlow Team",
135
135
  "homepage": ""
136
136
  },
137
137
  {
138
138
  "name": "@devflow-tools/plugin-taro",
139
- "version": "0.16.19",
139
+ "version": "0.16.20",
140
140
  "description": "",
141
141
  "tags": [],
142
142
  "compatibleStacks": [
143
143
  "taro"
144
144
  ],
145
- "size": "77119 B",
145
+ "size": "77290 B",
146
146
  "author": "DevFlow Team",
147
147
  "homepage": ""
148
148
  },
149
149
  {
150
150
  "name": "@devflow-tools/plugin-ui-layout",
151
- "version": "0.16.19",
151
+ "version": "0.16.20",
152
152
  "description": "",
153
153
  "tags": [],
154
154
  "compatibleStacks": [
155
155
  "ui-layout"
156
156
  ],
157
- "size": "54273 B",
157
+ "size": "54449 B",
158
158
  "author": "DevFlow Team",
159
159
  "homepage": ""
160
160
  },
161
161
  {
162
162
  "name": "@devflow-tools/plugin-vue",
163
- "version": "0.16.19",
163
+ "version": "0.16.20",
164
164
  "description": "",
165
165
  "tags": [],
166
166
  "compatibleStacks": [
167
167
  "vue"
168
168
  ],
169
- "size": "85297 B",
169
+ "size": "85467 B",
170
170
  "author": "DevFlow Team",
171
171
  "homepage": ""
172
172
  }