@devflow-tools/cli 0.16.25 → 0.16.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import {getLocalApiKey,getProjectStateDir,resolveRuntimeEndpoint,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure}from'@devflow-tools/sdk';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {MemoryGate}from'@devflow-tools/memory-engine';import {existsSync as existsSync$1,readFileSync,rmSync as rmSync$1,mkdirSync as mkdirSync$1,writeFileSync as writeFileSync$1,linkSync,readdirSync,renameSync as renameSync$1,unlinkSync as unlinkSync$1}from'fs';import {join as join$1}from'path';import {homedir as homedir$1}from'os';import {request}from'node:http';import {mkdirSync,existsSync,writeFileSync,renameSync,unlinkSync,rmSync,lstatSync,openSync,constants,fstatSync,readSync,closeSync,appendFileSync}from'node:fs';import {join}from'node:path';import {homedir}from'node:os';import {createHash}from'node:crypto';import {randomUUID,createHash as createHash$1}from'crypto';function 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};
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 N(o){return o??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function _(o){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(N(o))}function G(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 Ue=getLocalApiKey(),V=join(homedir(),".devflow","errors");async function $(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 m=0;m<=s;m+=1)try{return await Be(n,o,t,i),a&&registerRuntimeHttpSuccess(n,o).transitioned&&G("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)),m<s&&await We(Math.min(100*2**m,1e3));}if(!u)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return ae(o,u),{delivered:false,suppressed:false,fallbackReason:u.message};let g=registerRuntimeHttpFailure(n,o,e.fallbackReason??(r?"local_durable_mirror":"http_delivery_failed"));return g.transitioned&&(ae(o,u),G("http_circuit_transition",{endpoint:n,path:new URL(o,n).pathname,previous:l.state.status,status:"open",failures:g.state.failures,openUntil:g.state.openUntil,fallbackReason:g.state.fallbackReason})),{delivered:false,suppressed:false,fallbackReason:g.state.fallbackReason}}function Be(o,t,e,n){return new Promise((i,r)=>{let s=JSON.stringify(e),a=new URL(t,o),l=false,u=m=>{l||(l=true,m?r(m):i());},g=request({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":Ue,"Content-Length":Buffer.byteLength(s)},timeout:n},m=>{m.on("error",u),m.on("end",()=>{let h=m.statusCode??0;u(h>=200&&h<300?void 0:new Error(`HTTP ${h}`));}),m.resume();});g.on("error",u),g.on("timeout",()=>g.destroy(new Error(`HTTP mirror timed out after ${n}ms`))),g.write(s),g.end();})}function ae(o,t){try{existsSync(V)||mkdirSync(V,{recursive:!0}),appendFileSync(join(V,"http-errors.log"),`${new Date().toISOString()} | ${o} | ${t.message}
2
+ `);}catch{}}function We(o){return new Promise(t=>setTimeout(t,o))}var ge=1e4,Ye=3e4,q=500,J=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:q}).reverse();for(let r of i)try{this.applyOperation(r.operation,r.payload),n.resolveTelemetryFailure(r.id);}catch{}n.trimTelemetryFailures(q);}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:Ke(JSON.parse(readFileSync(r,"utf8")),i)}}catch{return null}})).filter(n=>n!==null).sort((n,i)=>n.envelope.timestamp-i.envelope.timestamp||me(n.envelope.operation)-me(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:fe(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(fe(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(q),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-q)))unlinkSync$1(join$1(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},Ye).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){$(t,e,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=ge?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,ge)}...`}}};function me(o){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(o)}function fe(o){return `hook-run:${o}`}function Ke(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 he(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 Se(o){return Buffer.from(o,"utf8").toString("base64url")}function ot(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 ke(o){return `${o}:legacy-journal`}var P=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(_(t),"hook-sessions");}registerSession(t){let e=t.trim();if(!e)throw new Error("session_id_required");let n=this.get(e);if(n)return n.lastActivityAt=Date.now(),this.persist(n),n;let 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=we(r.evidenceObligations),r.evidenceDegradations=Ee(r.evidenceDegradations),r.evidenceOutcomes=_e(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??ot(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(g=>g.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(g=>g.slice(0,240))},`correction\0${e}\0${l}`),this.replayEvidenceJournal(s),s.lastActivityAt=r,this.persist(s);let u=s.evidenceObligations.find(g=>g.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,`${Se(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",Se(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=we(t.evidenceObligations),t.evidenceDegradations=Ee(t.evidenceDegradations),t.evidenceOutcomes=_e(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=st(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((r,s)=>r.at-s.at||Ie(r.kind)-Ie(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 we(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)||!Ae(e.contract))return [];let n=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:ke(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 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"&&typeof e.reason=="string"&&typeof e.degradedAt=="number"&&typeof e.attempt=="number"}).slice(-20):[]}function _e(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 st(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:ke(t.contractId);if(t.kind==="add")return Ae(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 Ie(o){return o==="add"?0:o==="correction"?1:2}function Ae(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 De(o,t){let e=ut(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 ut(o){return join(_(o),"session-finalize-pending")}var yt=512*1024,bt=500;var vt=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function St(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)=>wt(s)?"":s).trim());}return {headingLines:e,claimLines:n}}function wt(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 Et(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,yt),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(-bt),g=t.length>0?Math.min(...t.map(y=>y.promptedAt)):0,m=It(u,g),b=[...m].reverse().find(y=>_t(y.text,t))??m.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 _t(o,t){let e=new Set(t.flatMap(i=>i.contract.requiredSections)),n=kt(St(o.split(/\r?\n/u)).headingLines);return [...e].every(i=>n.found.has(i))}function Te(o){return Et(o,[]).answer}function It(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=Rt(r.timestamp);if(l>0&&l+5e3<t)continue;let u=s.content,g=typeof u=="string"?u:Array.isArray(u)?u.filter(m=>m&&typeof m=="object"&&m.type==="text").map(m=>m.text).filter(m=>typeof m=="string").join(`
4
+ `):"";if(g.trim()){let m=g.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(m).digest("hex"),y=createHash("sha256").update(`${h}\0${b}`).digest("hex");e.push({text:m,timestamp:l,fingerprint:y});}}catch{continue}}return e}function Rt(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 kt(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=vt.find(a=>r===a);s&&(n=s,t.add(s)),e.set(i,n);}return {found:t,byLine:e}}function Dt(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 k(o){return (o instanceof Error?o.message:String(o)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var S=class extends Error{constructor(t,e){super(`session_finalize_${t}:${e}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${t}`;}};function M(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 Ct(o,t=N(),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 g=u.requestSessionClosure({receiptId:a,projectRoot:t,sessionId:s,payload:l}),m=u.getWorkByIdempotencyKey(a);return {status:g.state==="closed"||g.state==="closed_with_pending_work"?"completed":"accepted",receiptId:a,workState:m?.state??"pending",closureState:g.state,pendingWorkCount:g.pendingWorkCount}}catch(g){if(!i)throw g;return De(t,{receiptId:a,...l}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{u?.close();}}async function Bn(o,t=N(),e=true,n){let i;try{i=JSON.parse(o);}catch{return}let r=i.session_id?.trim();if(!r)return;let s=new P(t),a=s.get(r),l={evidenceDegradations:a?.evidenceDegradations??[],evidenceContractOutcomes:a?.evidenceOutcomes??[],pendingEvidenceContractIds:a?.evidenceObligations.map(b=>b.contractId)??[]},u=n?.telemetry??new J,g=!n?.telemetry,m=false,h;try{try{await u.flushAndAggregate();}catch{}let b=Date.now(),y=n?.executionId??a?.executionId,x;try{let p=openGlobalDevFlowDatabase();try{x=p.listSessionMemoryTurnsForReconciliation(t,r);for(let c of x){let f=`memory:${c.turnId}`,d=p.getSessionObligation(t,r,f);d?d.state==="open"&&c.status!=="pending"&&p.resolveSessionObligation({projectRoot:t,sessionId:r,obligationId:f,state:"satisfied",receiptId:c.receiptId,reason:c.reason,resolvedAt:c.decidedAt}):p.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{p.close();}}catch(p){let c=k(p),f={...l,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:c,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw M({projectRoot:t,sessionId:r,executionId:y,stage:"turn_load",reason:c,metadata:f}),new S("turn_load",c)}let O=Dt(x),w=n?.memory??(h=new MemoryGate(t)),F={status:"completed"};try{F=typeof w.reconcileTurnObservationLineage=="function"?{status:"completed",...await w.reconcileTurnObservationLineage(x)}:{status:"unsupported_adapter",committed:0,skipped:0,quarantined:0,unlinked:0};}catch(p){let c=k(p);throw F={status:"degraded",reason:c},M({projectRoot:t,sessionId:r,executionId:y,stage:"memory_lineage",reason:c,metadata:{...O,...l,memoryLineageReconciliation:F}}),new S("memory_lineage",c)}let z={status:"unknown",selected:0,adopted:0,unknown:0,positive:0,negative:0};try{let p=Te(i.transcript_path),c=openGlobalDevFlowDatabase(),f="unknown",d="no_terminal_host_action_evidence",L,j,Q,ee=[];try{let U=c.listHostActionsForSession(t,r,y),te=U.filter(T=>T.state==="verified"),B=U.filter(T=>["failed","cancelled","degraded"].includes(T.state));B.length>0?(f="negative",d=`terminal_host_action_${B[0].state}`):te.length>0&&(f="positive",d="host_action_verified");let W=B[0]??te.at(-1);L=W?.runId,j=W?.contextReceipt,Q=W?.evidenceHash,ee=U.flatMap(T=>{let ne=T.report.toolUseIds;return Array.isArray(ne)?ne.filter(Me=>typeof Me=="string"):[]});}finally{c.close();}let Pe=await w.attributeRetrievalBenefits({sessionId:r,executionId:y,finalAnswer:p,outcome:f,outcomeReason:d,workflowRunId:L,contextReceipt:j,toolEvidence:ee,verificationReceipt:Q});z={status:p?"evaluated":"unknown",...Pe};}catch(p){z={...z,status:"degraded",reason:k(p)};}let E;try{E=await w.reconcileDecidedTurnEventWindows(r,x,b);}catch(p){let c=k(p),f={...O,...l,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:c,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw M({projectRoot:t,sessionId:r,executionId:y,stage:"event_reconciliation",reason:c,metadata:f}),new S("event_reconciliation",c)}let D;try{D=await he({projectRoot:t,sessionId:r,trigger:"session_end",memory:w,details:{eventReconciliation:E},strictPersistence:!0});}catch(p){let c=k(p),f={...O,...l,memoryEventReconciliation:{status:"completed",...E,checkpointPending:null},memoryCheckpointDegradation:c};throw M({projectRoot:t,sessionId:r,executionId:y,stage:"checkpoint",reason:c,metadata:f}),new S("checkpoint",c)}let K={memoryLineageReconciliation:F,memoryBenefitAttribution:z,memoryEventReconciliation:{status:"completed",...E,checkpointPending:D.pendingEvents},memoryDistillCheckpoint:D};try{let p=openGlobalDevFlowDatabase();try{let c=`session-finalize:${r}:events`,f=Math.max(Number(D.pendingEvents??0),Number(E.remainingUndecided??0)),d=p.getSessionObligation(t,r,c);f>0?p.upsertSessionObligation({obligationId:c,projectRoot:t,sessionId:r,executionId:y,kind:"session_finalize",state:"open",payload:{pendingEvents:f,reconciliation:E,checkpointId:D.id},reason:"active_unprocessed_session_events",createdAt:d?.createdAt??b,updatedAt:b}):d?.state==="open"&&p.resolveSessionObligation({projectRoot:t,sessionId:r,obligationId:c,state:"satisfied",reason:"session_events_reconciled",resolvedAt:b});}finally{p.close();}}catch(p){console.error("[devflow] Session finalization obligation persistence failed:",p.message);}try{await w.closeSession(r),h&&(h.close(),h=void 0);}catch(p){let c=k(p),f={...O,...l,...K,memorySessionCloseDegradation:c};throw M({projectRoot:t,sessionId:r,executionId:y,stage:"memory_close",reason:c,metadata:f}),new S("memory_close",c)}let C={...O,...l,...K};m=!0;let v;try{v=openGlobalDevFlowDatabase();let p=y;if(p)try{v.reconcileSkillExecution(p,"completed",b,C);let d=v.getSkillExecution(p);await $("/api/telemetry/skill-execution/complete",{executionId:p,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:C},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let c=v.reconcileRunningSkillExecutionsForSession(r,b,{closureReason:"session_finalize",...C});for(let d of c)await $("/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:C},{fallbackReason:"skill_execution_already_reconciled_locally"});let f=v.getLatestSkillExecutionForSession(r);if(f&&!c.some(d=>d.executionId===f.executionId)&&v.mergeSkillExecutionMetadata(f.executionId,C),e){v.deleteHookReceipt(t);let d=_(t),L=createHash("sha256").update(t).digest("hex").slice(0,12);for(let j of [`session-id-${L}`,"current-execution-id","current-skill.json","event-map.json"])rmSync(join(d,j),{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{}g&&u.close(),m&&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=Ct(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{Dt as buildMemoryTurnOutcomeMetadata,Ct as enqueueSessionEndFinalization,Bn as handleSessionEnd};
@@ -1,15 +1,15 @@
1
1
  import {MemoryGate}from'@devflow-tools/memory-engine';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {existsSync,readFileSync as readFileSync$1,rmSync,mkdirSync as mkdirSync$1,writeFileSync as writeFileSync$1,linkSync,readdirSync,renameSync as renameSync$1,unlinkSync}from'fs';import {join as join$1,dirname}from'path';import {randomUUID as randomUUID$1,createHash as createHash$1}from'crypto';import {getLocalApiKey,resolveProjectCapabilityProfile,resolveCapabilityRollout,loadConfig,formatSkillRuntimeOverlay,createSkillRuntimeOverlay,getProjectStateDir,resolveRuntimeEndpoint,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure}from'@devflow-tools/sdk';import {fileURLToPath}from'url';import {homedir as homedir$1}from'os';import {request}from'node:http';import {readFileSync,openSync,constants,fstatSync,closeSync,mkdirSync,writeFileSync,renameSync,existsSync as existsSync$1,appendFileSync,chmodSync,fsyncSync,rmSync as rmSync$1,unlinkSync as unlinkSync$1,lstatSync}from'node:fs';import {join,resolve,dirname as dirname$1,isAbsolute,basename}from'node:path';import {homedir}from'node:os';import {createHash,randomUUID}from'node:crypto';function f(n,e,t){try{let r=openGlobalDevFlowDatabase();try{r.insertEvent({kind:n,timestamp:Date.now(),duration:t,success:e.success!==!1,metadata:e});}finally{r.close();}}catch{}}var Q="WARNING: DevFlow is in degraded mode (daemon unreachable): 4-Gate enforcement and memory prefetch cache are unavailable. Run `devflow doctor` for details.";function ee(){return process.env.DEVFLOW_HOOK_DEGRADED==="1"}function nt(n){return n??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function I(n){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(nt(n))}function oe(n){return Buffer.from(n,"utf8").toString("base64url")}function st(n,e,t){let r=e?.trim();if(r){let o=/^[a-zA-Z0-9:._-]{1,192}$/.test(r)?r:`tool-${createHash$1("sha256").update(r.slice(0,1024)).digest("hex").slice(0,32)}`;return `${n}:${o}`}return `${n}:legacy-${t}-${randomUUID$1().slice(0,8)}`}function le(n){return `${n}:legacy-journal`}var E=class{constructor(e){this.projectRoot=e;this.sessions=new Map;this.sessionsDir=join$1(I(e),"hook-sessions");}registerSession(e){let t=e.trim();if(!t)throw new Error("session_id_required");let r=this.get(t);if(r)return r.lastActivityAt=Date.now(),this.persist(r),r;let o=Date.now(),i={sessionId:t,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:o,lastActivityAt:o};return this.sessions.set(t,i),this.persist(i),i}startExecution(e,t,r){let o=this.registerSession(e);return (!o.executionId||o.skillName!==t)&&(o.executionId=`exec_${Date.now()}_${randomUUID$1().slice(0,8)}`),o.skillName=t,o.requiredMcpTools=[...new Set(r)],o.lastActivityAt=Date.now(),this.persist(o),o}get(e){let t=e.trim();if(!t)return null;let r=this.sessions.get(t);if(r)return this.replayEvidenceJournal(r),r;let o=this.snapshotPath(t);if(!existsSync(o))return null;try{let i=JSON.parse(readFileSync$1(o,"utf8"));return i.sessionId!==t||i.projectRoot!==this.projectRoot?null:(i.requiredMcpTools=Array.isArray(i.requiredMcpTools)?i.requiredMcpTools:[],i.evidenceObligations=ie(i.evidenceObligations),i.evidenceDegradations=se(i.evidenceDegradations),i.evidenceOutcomes=ae(i.evidenceOutcomes),this.replayEvidenceJournal(i),this.sessions.set(t,i),i)}catch{return null}}completeExecution(e){let t=this.get(e);if(!t)return null;let r=structuredClone(t);return delete t.executionId,delete t.skillName,t.requiredMcpTools=[],t.lastActivityAt=Date.now(),this.persist(t),r}addEvidenceObligation(e,t,r=Date.now(),o){let i=this.registerSession(e),a=(o?void 0:i.evidenceObligations.find(d=>d.contractId===t.id))?.obligationId??st(t.id,o,r);this.appendEvidenceEvent(e,{kind:"add",obligationId:a,contractId:t.id,at:r,contract:t},`add\0${a}`),this.replayEvidenceJournal(i);let c=i.evidenceObligations.find(d=>d.obligationId===a);return c?(i.lastActivityAt=Date.now(),this.persist(i),structuredClone(c)):null}listEvidenceObligations(e){return (this.get(e)?.evidenceObligations??[]).map(t=>structuredClone(t))}markEvidenceCorrection(e,t,r,o,i=Date.now()){let s=this.get(e),a=s?.evidenceObligations.find(u=>u.obligationId===t);if(!s||!a)return null;let c=/^[a-f0-9]{64}$/.test(o)?o:"";if(!c)return null;this.appendEvidenceEvent(e,{kind:"correction",obligationId:t,contractId:a.contractId,at:i,fingerprint:c,violations:r.slice(0,16).map(u=>u.slice(0,240))},`correction\0${t}\0${c}`),this.replayEvidenceJournal(s),s.lastActivityAt=i,this.persist(s);let d=s.evidenceObligations.find(u=>u.obligationId===t);return d?structuredClone(d):null}resolveEvidenceObligation(e,t){let r=this.get(e);if(!r)return false;let o=r.evidenceObligations.find(s=>s.obligationId===t);if(!o)return false;let i=Date.now();return this.appendEvidenceEvent(e,{kind:"resolve",obligationId:t,contractId:o.contractId,at:i},`resolve\0${t}`),this.replayEvidenceJournal(r),r.lastActivityAt=i,this.persist(r),true}degradeEvidenceObligation(e,t,r,o=Date.now()){let i=this.get(e),s=i?.evidenceObligations.find(c=>c.obligationId===t);if(!i||!s)return false;let a=r.slice(0,240);return this.appendEvidenceEvent(e,{kind:"degrade",obligationId:t,contractId:s.contractId,at:o,reason:a},`degrade\0${t}\0${a}`),this.replayEvidenceJournal(i),i.lastActivityAt=o,this.persist(i),true}removeSession(e){let t=e.trim();t&&(this.sessions.delete(t),rmSync(this.snapshotPath(t),{force:true}),rmSync(this.evidenceJournalDir(t),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(e){return join$1(this.sessionsDir,`${oe(e)}.json`)}evidenceJournalDir(e){return join$1(this.sessionsDir,"evidence-journal",oe(e))}appendEvidenceEvent(e,t,r){let o=this.evidenceJournalDir(e);mkdirSync$1(o,{recursive:true,mode:448});let i=createHash$1("sha256").update(r).digest("hex"),s=join$1(o,`${t.kind}-${i}.json`);if(existsSync(s))return;let a=join$1(o,`.${process.pid}.${randomUUID$1()}.tmp`);writeFileSync$1(a,JSON.stringify(t),{mode:384});try{linkSync(a,s);}catch(c){if(c.code!=="EEXIST")throw c}finally{rmSync(a,{force:true});}}replayEvidenceJournal(e){e.evidenceObligations=ie(e.evidenceObligations),e.evidenceDegradations=se(e.evidenceDegradations),e.evidenceOutcomes=ae(e.evidenceOutcomes);let t=this.evidenceJournalDir(e.sessionId);if(!existsSync(t))return;let r;try{r=readdirSync(t).filter(i=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(i)).slice(0,4096);}catch{return}let o=r.flatMap(i=>{try{let s=readFileSync$1(join$1(t,i),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=at(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||ce(i.kind)-ce(s.kind));for(let i of o)this.applyEvidenceEvent(e,i);e.evidenceObligations=e.evidenceObligations.slice(-8),e.evidenceDegradations=e.evidenceDegradations.slice(-20),e.evidenceOutcomes=e.evidenceOutcomes.slice(-20);}applyEvidenceEvent(e,t){let r=e.evidenceOutcomes.find(s=>s.obligationId===t.obligationId);if(t.kind==="add"){if(r)return;let s=e.evidenceObligations.find(a=>a.obligationId===t.obligationId);s?(s.contract=t.contract,s.promptedAt=Math.min(s.promptedAt,t.at)):e.evidenceObligations.push({obligationId:t.obligationId,contractId:t.contractId,contract:t.contract,promptedAt:t.at,attempt:0,correctionRequested:false,violations:[]});return}let o=e.evidenceObligations.find(s=>s.obligationId===t.obligationId);if(t.kind==="correction"){if(!o||r||o.correctionFingerprint===t.fingerprint)return;o.attempt+=1,o.correctionRequested=true,o.correctionRequestedAt=t.at,o.correctionFingerprint=t.fingerprint,o.violations=t.violations;return}let i=o?.attempt??0;e.evidenceObligations=e.evidenceObligations.filter(s=>s.obligationId!==t.obligationId),!r&&(t.kind==="degrade"&&e.evidenceDegradations.push({obligationId:t.obligationId,contractId:t.contractId,reason:t.reason,degradedAt:t.at,attempt:i}),e.evidenceOutcomes.push({obligationId:t.obligationId,contractId:t.contractId,status:t.kind==="resolve"?"resolved":"degraded",completedAt:t.at,attempt:i,...t.kind==="degrade"?{reason:t.reason}:{}}));}persist(e){mkdirSync$1(this.sessionsDir,{recursive:true,mode:448});let t=this.snapshotPath(e.sessionId),r=`${t}.${process.pid}.${randomUUID$1()}.tmp`;writeFileSync$1(r,JSON.stringify(e),{mode:384}),renameSync$1(r,t);}};function ie(n){return Array.isArray(n)?n.flatMap(e=>{if(!e||typeof e!="object")return [];let t=e;if(typeof t.contractId!="string"||t.contractId.length===0||t.contractId.length>128||typeof t.promptedAt!="number"||typeof t.attempt!="number"||typeof t.correctionRequested!="boolean"||!Array.isArray(t.violations)||!ue(t.contract))return [];let r=typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:le(t.contractId),o=typeof t.correctionTranscriptHash=="string"?t.correctionTranscriptHash:void 0,i=t.correctionFingerprint??o;return i!==void 0&&!/^[a-f0-9]{64}$/.test(i)?[]:[{...t,obligationId:r,correctionFingerprint:i}]}).slice(-8):[]}function se(n){return Array.isArray(n)?n.filter(e=>{if(!e||typeof e!="object")return false;let t=e;return typeof t.obligationId=="string"&&typeof t.contractId=="string"&&typeof t.reason=="string"&&typeof t.degradedAt=="number"&&typeof t.attempt=="number"}).slice(-20):[]}function ae(n){return Array.isArray(n)?n.filter(e=>{if(!e||typeof e!="object")return false;let t=e;return typeof t.obligationId=="string"&&typeof t.contractId=="string"&&(t.status==="resolved"||t.status==="degraded")&&typeof t.completedAt=="number"&&typeof t.attempt=="number"&&(t.reason===void 0||typeof t.reason=="string")}).slice(-20):[]}function at(n){if(!n||typeof n!="object")return null;let e=n;if(!["add","correction","resolve","degrade"].includes(e.kind??"")||typeof e.contractId!="string"||e.contractId.length>128||typeof e.at!="number")return null;let t=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:le(e.contractId);if(e.kind==="add")return ue(e.contract)?{...e,obligationId:t}:null;if(e.kind==="correction"){let r=typeof e.fingerprint=="string"?e.fingerprint:e.transcriptHash;return typeof r=="string"&&/^[a-f0-9]{64}$/.test(r)&&Array.isArray(e.violations)&&e.violations.every(o=>typeof o=="string"&&o.length<=240)?{...e,obligationId:t,fingerprint:r}:null}return e.kind==="resolve"?{...e,obligationId:t}:typeof e.reason=="string"&&e.reason.length<=240?{...e,obligationId:t}:null}function ce(n){return n==="add"?0:n==="correction"?1:2}function ue(n){if(!n||typeof n!="object")return false;let e=n,t=e.requiredSections,r=e.prohibitedClaims;return e.version==="1.0"&&typeof e.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(e.id)&&typeof e.runtimeProfilingOccurred=="boolean"&&typeof e.samplingEvidenceOccurred=="boolean"&&Array.isArray(t)&&t.length===3&&t[0]==="\u5DE5\u5177\u53D1\u73B0"&&t[1]==="\u6A21\u578B\u5047\u8BBE"&&t[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(r)&&r.length<=16&&r.every(o=>typeof o=="string"&&o.length<=128)&&typeof e.canonicalReport=="string"&&Buffer.byteLength(e.canonicalReport,"utf8")<=48*1024&&!!e.correctionPolicy&&e.correctionPolicy.maxAttempts===1&&e.correctionPolicy.repeatedViolation==="fail_open"}function ct(n){let e=n.trim().replace(/^\//,"");if(!e.startsWith("devflow:"))return null;let t=e.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(t)?`devflow:${t.toLowerCase()}`:null}function me(n){let e=n.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!e)return null;let t=ct(e[1]);return t?{rawName:e[1],skillName:t}:null}var pt=2,ft=1;function gt(){if(process.env.CLAUDE_PLUGIN_ROOT)return process.env.CLAUDE_PLUGIN_ROOT;try{return join$1(dirname(fileURLToPath(import.meta.url)),"..","..")}catch{return process.cwd()}}function pe(n=gt()){let e=[join$1(n,"dist","command-registry.json"),join$1(n,"command-registry.json")];for(let t of e)try{if(!existsSync(t))continue;let r=JSON.parse(readFileSync$1(t,"utf8"));if(r.version!==pt&&r.version!==ft||!yt(r.commands)){console.error(`[devflow] command registry contract mismatch: ${t}`);continue}return r.commands}catch(r){console.error(`[devflow] command registry load failed: ${r.message}`);}return null}function yt(n){return !n||typeof n!="object"||Array.isArray(n)?false:Object.values(n).every(e=>{if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return N(t.mcpTools)&&N(t.blockedNative)&&(t.source===void 0||t.source==="core"||t.source==="plugin")&&(t.requiresContext===void 0||typeof t.requiresContext=="boolean")&&(t.runtimePackages===void 0||N(t.runtimePackages))&&(t.evidenceMode===void 0||["static","runtime","mixed"].includes(t.evidenceMode))})}function N(n){return Array.isArray(n)&&n.every(e=>typeof e=="string"&&e.length>0)}function fe(n){let e=pe();return e?e[n]?.mcpTools??[]:[]}function ge(n,e,t){return formatSkillRuntimeOverlay(createSkillRuntimeOverlay(n,e,{prompt:t}))}var Et=getLocalApiKey(),L=join(homedir(),".devflow","errors");async function we(n,e,t={}){let r=t.endpoint??resolveRuntimeEndpoint().url,o=t.timeout??1500,i=t.durableMirror??true,s=t.maxRetries??(i?0:2),a=t.circuitBreaker??true,c=acquireRuntimeHttpCircuit(r,n);if(a&&!c.allowed)return {delivered:false,suppressed:true,fallbackReason:c.state.fallbackReason};let d;for(let l=0;l<=s;l+=1)try{return await Rt(r,n,e,o),a&&registerRuntimeHttpSuccess(r,n).transitioned&&f("http_circuit_transition",{endpoint:r,path:new URL(n,r).pathname,previous:c.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(m){d=m instanceof Error?m:new Error(String(m)),l<s&&await Mt(Math.min(100*2**l,1e3));}if(!d)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return Se(n,d),{delivered:false,suppressed:false,fallbackReason:d.message};let u=registerRuntimeHttpFailure(r,n,t.fallbackReason??(i?"local_durable_mirror":"http_delivery_failed"));return u.transitioned&&(Se(n,d),f("http_circuit_transition",{endpoint:r,path:new URL(n,r).pathname,previous:c.state.status,status:"open",failures:u.state.failures,openUntil:u.state.openUntil,fallbackReason:u.state.fallbackReason})),{delivered:false,suppressed:false,fallbackReason:u.state.fallbackReason}}function Rt(n,e,t,r){return new Promise((o,i)=>{let s=JSON.stringify(t),a=new URL(e,n),c=false,d=l=>{c||(c=true,l?i(l):o());},u=request({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":Et,"Content-Length":Buffer.byteLength(s)},timeout:r},l=>{l.on("error",d),l.on("end",()=>{let m=l.statusCode??0;d(m>=200&&m<300?void 0:new Error(`HTTP ${m}`));}),l.resume();});u.on("error",d),u.on("timeout",()=>u.destroy(new Error(`HTTP mirror timed out after ${r}ms`))),u.write(s),u.end();})}function Se(n,e){try{existsSync$1(L)||mkdirSync(L,{recursive:!0}),appendFileSync(join(L,"http-errors.log"),`${new Date().toISOString()} | ${n} | ${e.message}
2
- `);}catch{}}function Mt(n){return new Promise(e=>setTimeout(e,n))}var Me=1e4,At=3e4,R=500,M=class{constructor(e){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=e?.apiUrl,this.cacheDir=e?.cacheDir??join$1(process.env.DEVFLOW_STATE_DIR??join$1(homedir$1(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=e?.legacyCacheDir??(e?.cacheDir?null:join$1(homedir$1(),".devflow","telemetry-cache")),this.database=e?.database??null,this.ownsDatabase=!e?.database;let t=e?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(t)&&t>=0?t:100;}async sendEvent(e){let t={...e,input:this.truncateInput(e.input)};return this.commitOrCache("tool_call",t)?(this.postHttp("/api/telemetry/tool-call",t),e.eventId):null}async sendExecutionStart(e,t,r,o,i=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:e,sessionId:t,skillName:r,startedAt:o,projectRoot:i,requiredMcpTools:s};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(e,t="completed",r=Date.now(),o){let i={executionId:e,status:t,finishedAt:r,metadata:o},s=this.commitOrCache("execution_complete",i);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",i),s}async sendSessionStart(e,t,r){let o={id:e,projectRoot:t,startedAt:r,label:t.split("/").pop()??"unknown"},i=this.commitOrCache("session_start",o);return i&&this.postHttp("/api/telemetry/sessions",o),i}async completeEvent(e){let t=this.commitOrCache("complete_event",e);return t&&(this.postHttp("/api/telemetry/tool-call/output",e),this.scheduleMetricAggregation()),t}async endSession(e,t=Date.now()){let r={sessionId:e,finishedAt:t},o=this.commitOrCache("session_end",r);return o&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(e)}/close`,{finishedAt:t})),o}async flushCache(){try{let r=this.getDatabase(),o=r.listTelemetryFailures({unresolvedOnly:!0,limit:R}).reverse();for(let i of o)try{this.applyOperation(i.operation,i.payload),r.resolveTelemetryFailure(i.id);}catch{}r.trimTelemetryFailures(R);}catch{}let t=[...new Set([this.cacheDir,this.legacyCacheDir].filter(r=>!!r))].filter(r=>existsSync(r)).flatMap(r=>readdirSync(r).filter(o=>o.endsWith(".json")).map(o=>{let i=join$1(r,o);try{return {cacheFile:i,envelope:Tt(JSON.parse(readFileSync$1(i,"utf8")),o)}}catch{return null}})).filter(r=>r!==null).sort((r,o)=>r.envelope.timestamp-o.envelope.timestamp||xe(r.envelope.operation)-xe(o.envelope.operation));for(let{cacheFile:r,envelope:o}of t)try{let i=this.getDatabase();i.insertTelemetryFailure({id:o.id,operation:o.operation,payload:o.payload,error:o.failure,createdAt:o.timestamp}),this.applyOperation(o.operation,o.payload),i.resolveTelemetryFailure(o.id),unlinkSync(r);}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(e,t){try{return this.applyOperation(e,t),!0}catch(r){return this.cacheOperation(e,t,r),false}}applyOperation(e,t){let r=this.getDatabase();switch(e){case "tool_call":this.ensureParentSession(r,t),r.insertToolCallEvent(t);return;case "execution_start":this.ensureParentSession(r,t),r.insertSkillExecution({executionId:t.executionId,sessionId:t.sessionId,skillName:t.skillName,startedAt:t.startedAt,status:"running",requiredMcpTools:t.requiredMcpTools});return;case "execution_complete":r.reconcileSkillExecution(t.executionId,t.status,t.finishedAt,t.metadata);return;case "session_start":r.ensureSession(t),r.insertRun({id:De(t.id),source:"hook",tool:"session",input:{projectRoot:t.projectRoot},status:"active",startedAt:t.startedAt,tokenUsed:0,metadata:{sessionId:t.id,projectRoot:t.projectRoot}});return;case "complete_event":if(!r.updateToolCallEvent(t.eventId,{output:t.output===void 0?void 0:JSON.stringify(t.output),error:t.error,failureCategory:t.failureCategory,duration:t.duration}))throw new Error(`Tool call event ${t.eventId} is not available for completion`);return;case "session_end":r.closeSession(t.sessionId,t.finishedAt),r.updateRun(De(t.sessionId),{status:"completed",finishedAt:t.finishedAt});return}}ensureParentSession(e,t){let r=typeof t.sessionId=="string"?t.sessionId.trim():"";if(!r)throw new Error("Canonical session ID is required for telemetry");let o=typeof t.projectRoot=="string"&&t.projectRoot.trim()?t.projectRoot:typeof t.input?.projectRoot=="string"&&t.input.projectRoot.trim()?t.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";e.ensureSession({id:r,projectRoot:o,label:o==="unknown"?void 0:o.split("/").pop(),startedAt:Number(t.startedAt??t.timestamp??Date.now())});}cacheOperation(e,t,r){let o=Date.now(),i={id:`failure:${o}:${Math.random().toString(36).slice(2,11)}`,operation:e,payload:t,failure:r instanceof Error?r.message:String(r),timestamp:o};try{let s=this.getDatabase();s.insertTelemetryFailure({id:i.id,operation:e,payload:t,error:i.failure,createdAt:o}),s.trimTelemetryFailures(R),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync$1(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${o}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync$1(s,JSON.stringify(i,null,2),{mode:384}),this.trimCompatibilityCache(),this.scheduleRetry();}catch{}}trimCompatibilityCache(){try{let e=readdirSync(this.cacheDir).filter(t=>t.endsWith(".json")).sort();for(let t of e.slice(0,Math.max(0,e.length-R)))unlinkSync(join$1(this.cacheDir,t));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},At).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(e,t){we(e,t,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(e){let t=JSON.stringify(e);return t===void 0||t.length<=Me?e:{_truncated:true,_original_size:t.length,_preview:`${t.substring(0,Me)}...`}}};function xe(n){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(n)}function De(n){return `hook-run:${n}`}function Tt(n,e){if(!n||typeof n!="object")throw new Error("Invalid telemetry cache envelope");let t=n;if(typeof t.operation=="string"&&t.payload!==void 0)return t;let r=t.type==="tool_call"?"tool_call":t.type==="execution_start"?"execution_start":null;if(!r)throw new Error("Unknown legacy telemetry cache operation");let o=t.payload??{},i=Number(o.timestamp??o.startedAt??Date.now());return {id:`legacy-cache:${e}`,operation:r,payload:o,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:i}}var jt=/^\/(?:devflow:)?[\w-]+\b\s*/iu,Pt=/\b(?:(?:do\s+not|don't|dont|never|not)(?:\s+need\s+to)?|no\s+need\s+to)\s+(?:please\s+)?(?:remember|memorize)\b|(?:不要|别|不用|无需|不必|不需要)(?:再)?(?:记住|记|记忆)/iu,$t=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,Nt=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function x(n){let e=n.trim().replace(jt,"").trim();return !e||Pt.test(e)?null:(Nt.exec(e)??$t.exec(e))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}var k=1,z="memory-snapshot-v1.json",He=512*1024,qe=256*1024,Je=2e3,Wt=500,Gt=10,zt=240,Vt=300*1e3,Kt=720*60*60*1e3,We=2147483647,Bt=100,Te=250,Yt=3e4,Xt=10,D=new Map;function Ge(n){return n.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:n.ownerUid===n.currentUid,modeSafe:(n.mode&18)===0}}function g(n){return resolve(n)}function S(n){return createHash("sha256").update(g(n)).digest("hex").slice(0,16)}function V(n,e={}){let t=S(n),r=e.stateRoot?join(e.stateRoot,t):getProjectStateDir(g(n));return join(r,z)}function O(n,e){let r=(n instanceof Error?n.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return r?`${e}:${r}`:e}function K(n,e){return Array.isArray(n)&&n.length<=e&&n.every(t=>typeof t=="string"&&t.length>0&&t.length<=512)}function Zt(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)&&K(e.memoryIds,100)&&(e.status==="withheld"||e.status==="resolved")&&(e.summary===void 0||typeof e.summary=="string"&&e.summary.length<=2e3)}function Qt(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 B(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n,o=g(e),i=S(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")>qe||!K(r.memoryIds,Je)||!Array.isArray(r.conflicts)||r.conflicts.length>Wt||!r.conflicts.every(Zt)||typeof r.generatedAt!="number"||!Number.isFinite(r.generatedAt)||r.generatedAt<0||r.generatedAt>t+Vt||!Number.isInteger(s)||s<0||s>We||!["ready","pending","degraded","disabled"].includes(String(r.status))||r.degradation!==void 0&&!Qt(r.degradation)?null:{...r,generation:s}}function Y(n,e,t,r,o=0){let i=g(n);return {version:k,projectRoot:i,projectHash:S(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:r,generation:o,status:e,degradation:{reason:t}}}function b(n,e={}){let t=e.now??Date.now(),r=V(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>He)throw new Error("cache_size_invalid");let s=Ge({...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=B(a,n,t);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&t-c.generatedAt>Kt?{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:Y(n,a?"pending":"degraded",a?"cache_missing":O(i,"cache_invalid"),t),source:"none",valid:false,stale:false}}finally{if(o!==void 0)try{closeSync(o);}catch{}}}function je(n){if(!Number.isInteger(n)||n<0||n>=We)throw new Error("memory_snapshot_generation_exhausted");return n+1}function en(n){let e=dirname$1(n);mkdirSync(e,{recursive:true,mode:448}),chmodSync(e,448);}function tn(n){en(n);let e=`${n}.lock`,t={pid:process.pid,createdAt:Date.now(),token:randomUUID()},r=JSON.stringify(t),o;try{return o=openSync(e,"wx",384),writeFileSync(o,r),fsyncSync(o),{fd:o,path:e,contents:r}}catch(i){if(o!==void 0){try{closeSync(o);}catch{}try{unlinkSync$1(e);}catch{}}if(i.code==="EEXIST")return null;throw i}}function nn(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let e=n;return Number.isInteger(e.pid)&&Number(e.pid)>0&&typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)&&typeof e.token=="string"&&e.token.length>0}function rn(n){try{return process.kill(n,0),!1}catch(e){return e.code==="ESRCH"}}function on(n){return !n.canonicalCachePath||!n.directoryIsSafe||!n.lockIsRegularFile||!n.metadataValid||!n.contentsUnchanged||!n.ownerDead&&!n.stale?false:n.currentUid!==void 0?n.directoryUid===n.currentUid&&n.lockUid===n.currentUid:true}function sn(n){return isAbsolute(n)&&resolve(n)===n&&basename(n)===z&&/^[a-f0-9]{16}$/u.test(basename(dirname$1(n)))}function an(n,e){let t=`${n}.lock`;try{let r=lstatSync(dirname$1(n)),o=lstatSync(t),i=readFileSync(t,"utf8"),s=null;try{let Z=JSON.parse(i);nn(Z)&&(s=Z);}catch{}let a=s?.createdAt??o.mtimeMs,c=Date.now()-a>e,d=s?rn(s.pid):!1,u=readFileSync(t,"utf8")===i,l=typeof process.getuid=="function"?process.getuid():void 0,m=Ge({...l!==void 0?{currentUid:l}:{},ownerUid:r.uid,mode:r.mode});return on({canonicalCachePath:sn(n),directoryIsSafe:r.isDirectory()&&!r.isSymbolicLink()&&m.modeSafe,lockIsRegularFile:o.isFile()&&!o.isSymbolicLink(),metadataValid:s!==null,ownerDead:d,stale:c,contentsUnchanged:u,...l!==void 0?{currentUid:l}:{},directoryUid:r.uid,lockUid:o.uid})?(unlinkSync$1(t),!0):!1}catch{return false}}function cn(n){try{closeSync(n.fd);}catch{}try{readFileSync(n.path,"utf8")===n.contents&&unlinkSync$1(n.path);}catch{}}function dn(n){return new Promise(e=>setTimeout(e,n))}function U(n,e,t,r){let o=Number.isFinite(n)?Math.floor(n):e;return Math.min(r,Math.max(t,o))}async function ln(n,e){let t=U(e.lockTimeoutMs,Bt,0,Te),r=U(e.lockRetryMs,Xt,1,Te),o=U(e.lockStaleMs,Yt,0,Number.MAX_SAFE_INTEGER),i=Date.now()+t;for(;;){let s=tn(n);if(s)return s;if(an(n,o))continue;let a=i-Date.now();if(a<=0)throw new Error("memory_snapshot_cache_lock_timeout");await dn(Math.min(r,a));}}async function Pe(n,e,t){let r=await ln(n,e);try{return await t()}finally{cn(r);}}function $e(n,e,t,r){let o=r.now??Date.now(),i=g(n),s={version:k,projectRoot:i,projectHash:S(i),markdown:e.markdown,memoryIds:e.memoryIds??[],conflicts:e.conflicts??[],generatedAt:o,generation:t,status:e.status??"ready",...e.degradation?{degradation:e.degradation}:{}};if(!B(s,n,o))throw new Error("memory_snapshot_payload_invalid");let a=JSON.stringify(s);if(Buffer.byteLength(a,"utf8")>He)throw new Error("memory_snapshot_cache_too_large");let c=V(n,r),d=dirname$1(c);mkdirSync(d,{recursive:true,mode:448}),chmodSync(d,448);let u=join(d,`.${z}.${process.pid}.${randomUUID()}.tmp`),l;try{l=openSync(u,"wx",384),writeFileSync(l,a),fsyncSync(l),closeSync(l),l=void 0,chmodSync(u,384),renameSync(u,c),chmodSync(c,384);let m;try{m=openSync(d,"r");try{fsyncSync(m);}catch{}}finally{m!==void 0&&closeSync(m);}return s}finally{if(l!==void 0)try{closeSync(l);}catch{}rmSync$1(u,{force:true});}}function un(n,e){let r=(D.get(n)??Promise.resolve()).catch(()=>{}).then(e),o=r.then(()=>{},()=>{});return D.set(n,o),r.finally(()=>{D.get(n)===o&&D.delete(n);})}function H(n,e,t,r,o){return n.valid?n.snapshot.generation>o?{...n,persisted:false}:{...n,snapshot:{...n.snapshot,status:"degraded",degradation:{reason:t,stale:n.stale||void 0}},persisted:false}:{snapshot:Y(e,"degraded",t,r,o),source:"none",valid:false,stale:false,persisted:false}}async function mn(n){let e=V(n.projectRoot,n.cacheOptions);return un(e,async()=>{let t=b(n.projectRoot,n.cacheOptions),r=t.valid?t.snapshot.generation:0,o;try{o=await n.load();}catch(i){let s=O(i,`refresh_failed:${n.reason}`);try{return await Pe(e,n.cacheOptions??{},()=>{let a=b(n.projectRoot,n.cacheOptions);if(a.valid)return H(a,n.projectRoot,s,n.cacheOptions?.now??Date.now(),r);let c=je(r),d=Y(n.projectRoot,"degraded",s,n.cacheOptions?.now??Date.now(),c);return {snapshot:$e(n.projectRoot,d,c,n.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(a){let c=b(n.projectRoot,n.cacheOptions);return H(c,n.projectRoot,O(a,s),n.cacheOptions?.now??Date.now(),r)}}try{return await Pe(e,n.cacheOptions??{},()=>{let i=b(n.projectRoot,n.cacheOptions);if(i.valid&&i.snapshot.generation>r)return {...i,persisted:!1};let s=je(Math.max(r,i.valid?i.snapshot.generation:0));return {snapshot:$e(n.projectRoot,o,s,n.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(i){let s=b(n.projectRoot,n.cacheOptions);return H(s,n.projectRoot,O(i,`refresh_commit_failed:${n.reason}`),n.cacheOptions?.now??Date.now(),r)}})}async function ze(n){return mn({projectRoot:n.projectRoot,reason:n.reason,cacheOptions:n.cacheOptions,load:async()=>{if(n.injectConfig===false)return {status:"disabled",markdown:"",memoryIds:[],conflicts:[]};let e=typeof n.injectConfig=="object"?n.injectConfig:{},t=Number.isFinite(e.topN)?Math.max(0,Math.floor(e.topN)):10,r=Number.isFinite(e.budgetTokens)?Math.max(1,Math.floor(e.budgetTokens)):800,o=await n.memory.getAll({purpose:"session_bootstrap",budgetTokens:r,limit:t}),s=Number.isInteger(o.truncatedCount)&&o.truncatedCount>=0?o.truncatedCount:null,a=o.memories.length===0&&s!==0,c=s!==null&&s>0?"snapshot_results_truncated":"snapshot_truncation_unknown",d=(o.conflicts??[]).map(l=>({id:l.id,kind:l.kind,family:l.family,entity:l.entity,memoryIds:l.memoryIds,status:l.status,...l.summary?{summary:l.summary}:{}})),u=a?`## Project memory
2
+ `);}catch{}}function Mt(n){return new Promise(e=>setTimeout(e,n))}var Me=1e4,At=3e4,R=500,M=class{constructor(e){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=e?.apiUrl,this.cacheDir=e?.cacheDir??join$1(process.env.DEVFLOW_STATE_DIR??join$1(homedir$1(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=e?.legacyCacheDir??(e?.cacheDir?null:join$1(homedir$1(),".devflow","telemetry-cache")),this.database=e?.database??null,this.ownsDatabase=!e?.database;let t=e?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(t)&&t>=0?t:100;}async sendEvent(e){let t={...e,input:this.truncateInput(e.input)};return this.commitOrCache("tool_call",t)?(this.postHttp("/api/telemetry/tool-call",t),e.eventId):null}async sendExecutionStart(e,t,r,o,i=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:e,sessionId:t,skillName:r,startedAt:o,projectRoot:i,requiredMcpTools:s};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(e,t="completed",r=Date.now(),o){let i={executionId:e,status:t,finishedAt:r,metadata:o},s=this.commitOrCache("execution_complete",i);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",i),s}async sendSessionStart(e,t,r){let o={id:e,projectRoot:t,startedAt:r,label:t.split("/").pop()??"unknown"},i=this.commitOrCache("session_start",o);return i&&this.postHttp("/api/telemetry/sessions",o),i}async completeEvent(e){let t=this.commitOrCache("complete_event",e);return t&&(this.postHttp("/api/telemetry/tool-call/output",e),this.scheduleMetricAggregation()),t}async endSession(e,t=Date.now()){let r={sessionId:e,finishedAt:t},o=this.commitOrCache("session_end",r);return o&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(e)}/close`,{finishedAt:t})),o}async flushCache(){try{let r=this.getDatabase(),o=r.listTelemetryFailures({unresolvedOnly:!0,limit:R}).reverse();for(let i of o)try{this.applyOperation(i.operation,i.payload),r.resolveTelemetryFailure(i.id);}catch{}r.trimTelemetryFailures(R);}catch{}let t=[...new Set([this.cacheDir,this.legacyCacheDir].filter(r=>!!r))].filter(r=>existsSync(r)).flatMap(r=>readdirSync(r).filter(o=>o.endsWith(".json")).map(o=>{let i=join$1(r,o);try{return {cacheFile:i,envelope:Tt(JSON.parse(readFileSync$1(i,"utf8")),o)}}catch{return null}})).filter(r=>r!==null).sort((r,o)=>r.envelope.timestamp-o.envelope.timestamp||xe(r.envelope.operation)-xe(o.envelope.operation));for(let{cacheFile:r,envelope:o}of t)try{let i=this.getDatabase();i.insertTelemetryFailure({id:o.id,operation:o.operation,payload:o.payload,error:o.failure,createdAt:o.timestamp}),this.applyOperation(o.operation,o.payload),i.resolveTelemetryFailure(o.id),unlinkSync(r);}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(e,t){try{return this.applyOperation(e,t),!0}catch(r){return this.cacheOperation(e,t,r),false}}applyOperation(e,t){let r=this.getDatabase();switch(e){case "tool_call":this.ensureParentSession(r,t),r.insertToolCallEvent(t);return;case "execution_start":this.ensureParentSession(r,t),r.insertSkillExecution({executionId:t.executionId,sessionId:t.sessionId,skillName:t.skillName,startedAt:t.startedAt,status:"running",requiredMcpTools:t.requiredMcpTools});return;case "execution_complete":r.reconcileSkillExecution(t.executionId,t.status,t.finishedAt,t.metadata);return;case "session_start":r.ensureSession(t),r.insertRun({id:De(t.id),source:"hook",tool:"session",input:{projectRoot:t.projectRoot},status:"active",startedAt:t.startedAt,tokenUsed:0,metadata:{sessionId:t.id,projectRoot:t.projectRoot}});return;case "complete_event":if(!r.updateToolCallEvent(t.eventId,{output:t.output===void 0?void 0:JSON.stringify(t.output),error:t.error,failureCategory:t.failureCategory,duration:t.duration}))throw new Error(`Tool call event ${t.eventId} is not available for completion`);return;case "session_end":r.closeSession(t.sessionId,t.finishedAt),r.updateRun(De(t.sessionId),{status:"completed",finishedAt:t.finishedAt});return}}ensureParentSession(e,t){let r=typeof t.sessionId=="string"?t.sessionId.trim():"";if(!r)throw new Error("Canonical session ID is required for telemetry");let o=typeof t.projectRoot=="string"&&t.projectRoot.trim()?t.projectRoot:typeof t.input?.projectRoot=="string"&&t.input.projectRoot.trim()?t.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";e.ensureSession({id:r,projectRoot:o,label:o==="unknown"?void 0:o.split("/").pop(),startedAt:Number(t.startedAt??t.timestamp??Date.now())});}cacheOperation(e,t,r){let o=Date.now(),i={id:`failure:${o}:${Math.random().toString(36).slice(2,11)}`,operation:e,payload:t,failure:r instanceof Error?r.message:String(r),timestamp:o};try{let s=this.getDatabase();s.insertTelemetryFailure({id:i.id,operation:e,payload:t,error:i.failure,createdAt:o}),s.trimTelemetryFailures(R),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync$1(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${o}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync$1(s,JSON.stringify(i,null,2),{mode:384}),this.trimCompatibilityCache(),this.scheduleRetry();}catch{}}trimCompatibilityCache(){try{let e=readdirSync(this.cacheDir).filter(t=>t.endsWith(".json")).sort();for(let t of e.slice(0,Math.max(0,e.length-R)))unlinkSync(join$1(this.cacheDir,t));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},At).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(e,t){we(e,t,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(e){let t=JSON.stringify(e);return t===void 0||t.length<=Me?e:{_truncated:true,_original_size:t.length,_preview:`${t.substring(0,Me)}...`}}};function xe(n){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(n)}function De(n){return `hook-run:${n}`}function Tt(n,e){if(!n||typeof n!="object")throw new Error("Invalid telemetry cache envelope");let t=n;if(typeof t.operation=="string"&&t.payload!==void 0)return t;let r=t.type==="tool_call"?"tool_call":t.type==="execution_start"?"execution_start":null;if(!r)throw new Error("Unknown legacy telemetry cache operation");let o=t.payload??{},i=Number(o.timestamp??o.startedAt??Date.now());return {id:`legacy-cache:${e}`,operation:r,payload:o,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:i}}var jt=/^\/(?:devflow:)?[\w-]+\b\s*/iu,Pt=/\b(?:(?:do\s+not|don't|dont|never|not)(?:\s+need\s+to)?|no\s+need\s+to)\s+(?:please\s+)?(?:remember|memorize)\b|(?:不要|别|不用|无需|不必|不需要)(?:再)?(?:记住|记|记忆)/iu,$t=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,Nt=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function x(n){let e=n.trim().replace(jt,"").trim();return !e||Pt.test(e)?null:(Nt.exec(e)??$t.exec(e))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}var k=1,G="memory-snapshot-v1.json",He=512*1024,qe=256*1024,Je=2e3,Wt=500,zt=10,Gt=240,Vt=300*1e3,Kt=720*60*60*1e3,We=2147483647,Bt=100,Te=250,Yt=3e4,Xt=10,D=new Map;function ze(n){return n.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:n.ownerUid===n.currentUid,modeSafe:(n.mode&18)===0}}function g(n){return resolve(n)}function S(n){return createHash("sha256").update(g(n)).digest("hex").slice(0,16)}function V(n,e={}){let t=S(n),r=e.stateRoot?join(e.stateRoot,t):getProjectStateDir(g(n));return join(r,G)}function O(n,e){let r=(n instanceof Error?n.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return r?`${e}:${r}`:e}function K(n,e){return Array.isArray(n)&&n.length<=e&&n.every(t=>typeof t=="string"&&t.length>0&&t.length<=512)}function Zt(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)&&K(e.memoryIds,100)&&(e.status==="withheld"||e.status==="resolved")&&(e.summary===void 0||typeof e.summary=="string"&&e.summary.length<=2e3)}function Qt(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 B(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n,o=g(e),i=S(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")>qe||!K(r.memoryIds,Je)||!Array.isArray(r.conflicts)||r.conflicts.length>Wt||!r.conflicts.every(Zt)||typeof r.generatedAt!="number"||!Number.isFinite(r.generatedAt)||r.generatedAt<0||r.generatedAt>t+Vt||!Number.isInteger(s)||s<0||s>We||!["ready","pending","degraded","disabled"].includes(String(r.status))||r.degradation!==void 0&&!Qt(r.degradation)?null:{...r,generation:s}}function Y(n,e,t,r,o=0){let i=g(n);return {version:k,projectRoot:i,projectHash:S(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:r,generation:o,status:e,degradation:{reason:t}}}function b(n,e={}){let t=e.now??Date.now(),r=V(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>He)throw new Error("cache_size_invalid");let s=ze({...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=B(a,n,t);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&t-c.generatedAt>Kt?{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:Y(n,a?"pending":"degraded",a?"cache_missing":O(i,"cache_invalid"),t),source:"none",valid:false,stale:false}}finally{if(o!==void 0)try{closeSync(o);}catch{}}}function je(n){if(!Number.isInteger(n)||n<0||n>=We)throw new Error("memory_snapshot_generation_exhausted");return n+1}function en(n){let e=dirname$1(n);mkdirSync(e,{recursive:true,mode:448}),chmodSync(e,448);}function tn(n){en(n);let e=`${n}.lock`,t={pid:process.pid,createdAt:Date.now(),token:randomUUID()},r=JSON.stringify(t),o;try{return o=openSync(e,"wx",384),writeFileSync(o,r),fsyncSync(o),{fd:o,path:e,contents:r}}catch(i){if(o!==void 0){try{closeSync(o);}catch{}try{unlinkSync$1(e);}catch{}}if(i.code==="EEXIST")return null;throw i}}function nn(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let e=n;return Number.isInteger(e.pid)&&Number(e.pid)>0&&typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)&&typeof e.token=="string"&&e.token.length>0}function rn(n){try{return process.kill(n,0),!1}catch(e){return e.code==="ESRCH"}}function on(n){return !n.canonicalCachePath||!n.directoryIsSafe||!n.lockIsRegularFile||!n.metadataValid||!n.contentsUnchanged||!n.ownerDead&&!n.stale?false:n.currentUid!==void 0?n.directoryUid===n.currentUid&&n.lockUid===n.currentUid:true}function sn(n){return isAbsolute(n)&&resolve(n)===n&&basename(n)===G&&/^[a-f0-9]{16}$/u.test(basename(dirname$1(n)))}function an(n,e){let t=`${n}.lock`;try{let r=lstatSync(dirname$1(n)),o=lstatSync(t),i=readFileSync(t,"utf8"),s=null;try{let Z=JSON.parse(i);nn(Z)&&(s=Z);}catch{}let a=s?.createdAt??o.mtimeMs,c=Date.now()-a>e,d=s?rn(s.pid):!1,u=readFileSync(t,"utf8")===i,l=typeof process.getuid=="function"?process.getuid():void 0,m=ze({...l!==void 0?{currentUid:l}:{},ownerUid:r.uid,mode:r.mode});return on({canonicalCachePath:sn(n),directoryIsSafe:r.isDirectory()&&!r.isSymbolicLink()&&m.modeSafe,lockIsRegularFile:o.isFile()&&!o.isSymbolicLink(),metadataValid:s!==null,ownerDead:d,stale:c,contentsUnchanged:u,...l!==void 0?{currentUid:l}:{},directoryUid:r.uid,lockUid:o.uid})?(unlinkSync$1(t),!0):!1}catch{return false}}function cn(n){try{closeSync(n.fd);}catch{}try{readFileSync(n.path,"utf8")===n.contents&&unlinkSync$1(n.path);}catch{}}function dn(n){return new Promise(e=>setTimeout(e,n))}function U(n,e,t,r){let o=Number.isFinite(n)?Math.floor(n):e;return Math.min(r,Math.max(t,o))}async function ln(n,e){let t=U(e.lockTimeoutMs,Bt,0,Te),r=U(e.lockRetryMs,Xt,1,Te),o=U(e.lockStaleMs,Yt,0,Number.MAX_SAFE_INTEGER),i=Date.now()+t;for(;;){let s=tn(n);if(s)return s;if(an(n,o))continue;let a=i-Date.now();if(a<=0)throw new Error("memory_snapshot_cache_lock_timeout");await dn(Math.min(r,a));}}async function Pe(n,e,t){let r=await ln(n,e);try{return await t()}finally{cn(r);}}function $e(n,e,t,r){let o=r.now??Date.now(),i=g(n),s={version:k,projectRoot:i,projectHash:S(i),markdown:e.markdown,memoryIds:e.memoryIds??[],conflicts:e.conflicts??[],generatedAt:o,generation:t,status:e.status??"ready",...e.degradation?{degradation:e.degradation}:{}};if(!B(s,n,o))throw new Error("memory_snapshot_payload_invalid");let a=JSON.stringify(s);if(Buffer.byteLength(a,"utf8")>He)throw new Error("memory_snapshot_cache_too_large");let c=V(n,r),d=dirname$1(c);mkdirSync(d,{recursive:true,mode:448}),chmodSync(d,448);let u=join(d,`.${G}.${process.pid}.${randomUUID()}.tmp`),l;try{l=openSync(u,"wx",384),writeFileSync(l,a),fsyncSync(l),closeSync(l),l=void 0,chmodSync(u,384),renameSync(u,c),chmodSync(c,384);let m;try{m=openSync(d,"r");try{fsyncSync(m);}catch{}}finally{m!==void 0&&closeSync(m);}return s}finally{if(l!==void 0)try{closeSync(l);}catch{}rmSync$1(u,{force:true});}}function un(n,e){let r=(D.get(n)??Promise.resolve()).catch(()=>{}).then(e),o=r.then(()=>{},()=>{});return D.set(n,o),r.finally(()=>{D.get(n)===o&&D.delete(n);})}function H(n,e,t,r,o){return n.valid?n.snapshot.generation>o?{...n,persisted:false}:{...n,snapshot:{...n.snapshot,status:"degraded",degradation:{reason:t,stale:n.stale||void 0}},persisted:false}:{snapshot:Y(e,"degraded",t,r,o),source:"none",valid:false,stale:false,persisted:false}}async function mn(n){let e=V(n.projectRoot,n.cacheOptions);return un(e,async()=>{let t=b(n.projectRoot,n.cacheOptions),r=t.valid?t.snapshot.generation:0,o;try{o=await n.load();}catch(i){let s=O(i,`refresh_failed:${n.reason}`);try{return await Pe(e,n.cacheOptions??{},()=>{let a=b(n.projectRoot,n.cacheOptions);if(a.valid)return H(a,n.projectRoot,s,n.cacheOptions?.now??Date.now(),r);let c=je(r),d=Y(n.projectRoot,"degraded",s,n.cacheOptions?.now??Date.now(),c);return {snapshot:$e(n.projectRoot,d,c,n.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(a){let c=b(n.projectRoot,n.cacheOptions);return H(c,n.projectRoot,O(a,s),n.cacheOptions?.now??Date.now(),r)}}try{return await Pe(e,n.cacheOptions??{},()=>{let i=b(n.projectRoot,n.cacheOptions);if(i.valid&&i.snapshot.generation>r)return {...i,persisted:!1};let s=je(Math.max(r,i.valid?i.snapshot.generation:0));return {snapshot:$e(n.projectRoot,o,s,n.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(i){let s=b(n.projectRoot,n.cacheOptions);return H(s,n.projectRoot,O(i,`refresh_commit_failed:${n.reason}`),n.cacheOptions?.now??Date.now(),r)}})}async function Ge(n){return mn({projectRoot:n.projectRoot,reason:n.reason,cacheOptions:n.cacheOptions,load:async()=>{if(n.injectConfig===false)return {status:"disabled",markdown:"",memoryIds:[],conflicts:[]};let e=typeof n.injectConfig=="object"?n.injectConfig:{},t=Number.isFinite(e.topN)?Math.max(0,Math.floor(e.topN)):10,r=Number.isFinite(e.budgetTokens)?Math.max(1,Math.floor(e.budgetTokens)):800,o=await n.memory.getAll({purpose:"session_bootstrap",budgetTokens:r,limit:t}),s=Number.isInteger(o.truncatedCount)&&o.truncatedCount>=0?o.truncatedCount:null,a=o.memories.length===0&&s!==0,c=s!==null&&s>0?"snapshot_results_truncated":"snapshot_truncation_unknown",d=(o.conflicts??[]).map(l=>({id:l.id,kind:l.kind,family:l.family,entity:l.entity,memoryIds:l.memoryIds,status:l.status,...l.summary?{summary:l.summary}:{}})),u=a?`## Project memory
3
3
  DevFlow memory snapshot=degraded; reason=${c}. Memory result completeness is not authoritative; do not conclude that the project has no memories.`:o.memories.length===0&&d.length>0?`## Project memory
4
4
  ${d.length} explicit preference conflict(s) are withheld from automatic guidance; an explicit choice is required.`:o.memories.length===0?`## Project memory
5
5
  \u672C\u9879\u76EE\u6682\u65E0\u8BB0\u5FC6`:`## Project memory (auto-injected, ${o.memories.length} items, ${o.tokenCount} tokens)
6
6
  ${o.memories.map(l=>`- **${l.title||l.type}**: ${l.content} (confidence ${l.confidence.toFixed(2)}, ${l.source})`).join(`
7
- `)}`;return {status:a?"degraded":"ready",markdown:u,memoryIds:o.memories.map(l=>l.id),conflicts:d,...a?{degradation:{reason:c}}:{}}}})}function pn(n){if(!n)return true;try{return JSON.parse(readFileSync(n,"utf8")).sessionStart?.injectMemories??!0}catch{return true}}function fn(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=g(n);return {version:k,projectRoot:i,projectHash:S(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:t,generation:0,status:"disabled"}}let o=B(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")<=qe){let i=g(n);return {version:k,projectRoot:i,projectHash:S(i),markdown:r.markdown,memoryIds:K(r.memoryIds,Je)?r.memoryIds:[],conflicts:[],generatedAt:t,generation:0,status:"ready"}}}catch{}return null}function q(n,e){return [...(n??e).replace(/[\r\n\t|]+/gu," ").trim()||e].slice(0,zt).join("")}function gn(n){if(n.length===0)return "";let e=n.slice(0,Gt),t=e.map(r=>{let o=q(r.family,"unknown"),i=q(r.entity,"unknown"),s=q(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})
7
+ `)}`;return {status:a?"degraded":"ready",markdown:u,memoryIds:o.memories.map(l=>l.id),conflicts:d,...a?{degradation:{reason:c}}:{}}}})}function pn(n){if(!n)return true;try{return JSON.parse(readFileSync(n,"utf8")).sessionStart?.injectMemories??!0}catch{return true}}function fn(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=g(n);return {version:k,projectRoot:i,projectHash:S(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:t,generation:0,status:"disabled"}}let o=B(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")<=qe){let i=g(n);return {version:k,projectRoot:i,projectHash:S(i),markdown:r.markdown,memoryIds:K(r.memoryIds,Je)?r.memoryIds:[],conflicts:[],generatedAt:t,generation:0,status:"ready"}}}catch{}return null}function q(n,e){return [...(n??e).replace(/[\r\n\t|]+/gu," ").trim()||e].slice(0,Gt).join("")}function gn(n){if(n.length===0)return "";let e=n.slice(0,zt),t=e.map(r=>{let o=q(r.family,"unknown"),i=q(r.entity,"unknown"),s=q(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
8
  ${t.join(`
9
9
  `)}`}function yn(n){let e=n.now??Date.now();if(pn(n.configPath)===false)return "";let t=fn(n.projectRoot,n.daemonResponse??"",e),r=t?{snapshot:t,source:"daemon"}:b(n.projectRoot,{...n.cacheOptions,now:e}),{snapshot:o}=r;if(o.status==="disabled")return `## Project memory
10
10
  DevFlow memory snapshot=pending; source=${r.source}; reason=previous_snapshot_disabled. Memory availability is not yet known; do not conclude that the project has no memories.`;let i=new Date(o.generatedAt).toISOString(),s=o.degradation?.reason?`; reason=${o.degradation.reason}`:"",a=`DevFlow memory snapshot=${o.status}; source=${r.source}; generatedAt=${i}${s}.`,c=gn(o.conflicts);return o.markdown?[o.markdown,c,a].filter(Boolean).join(`
11
11
  `):["## Project memory",c,`${a} Memory availability is not yet known; do not conclude that the project has no memories.`].filter(Boolean).join(`
12
- `)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,n,e,t]=process.argv;n!=="session-start"||!e?process.exitCode=2:process.stdout.write(yn({projectRoot:e,configPath:t,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var bn=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu;function vn(n){let e=n.trim();return e.length>0&&!bn.test(e)}function Sn(n,e,t=Date.now()){let r=createHash("sha256").update(e.trim()).digest("hex"),o=createHash("sha256").update(`${n}\0${t}\0${r}`).digest("hex").slice(0,24);return {turnId:`turn:${o}`,eventId:`memory-turn:${o}`,promptHash:r,createdAt:t}}function In(n,e,t=[]){return `memory-receipt:${createHash("sha256").update(`${n}\0${e}\0${[...t].sort().join("\0")}`).digest("hex").slice(0,24)}`}function Ke(n){return `DevFlow memory decision required for ${n.turnId}. Before the final response, semantically decide whether this turn contains durable project knowledge. Call mcp__devflow__memory_commit_turn with evidence-bound candidates, or mcp__devflow__memory_skip_turn with a concrete reason. Do not claim memory success without a canonical receipt. For candidates, preserve exact package names, flags, versions, paths, and identifiers; provide subject, predicate, value, polarity, and entities when known. Do not save assistant echoes, task narration, retries, or unverified guesses. Express a change from an old choice as the new durable value. If the decision tool remains unavailable, explicitly state that the memory was not saved.`}function X(n){let e=n.memoryIds.length>0?n.memoryIds.join(","):"none",t=n.status==="committed"?"accepted":n.status,r=n.status==="committed"?"; indexStatus=pending":"",o=n.status==="committed"&&n.source==="explicit_intent"?"; memoryOnlyCompleted=true; skipProjectContext=true; skipMemoryTool=true":"",i=n.status==="committed"&&n.source==="explicit_intent"?" This explicit-memory request is complete. Return the canonical receipt to the user. Do not call a memory tool, project-context tool, domain tool, or native memory write for this request.":"";return `DevFlow canonical memory receipt: status=${t}; receiptId=${n.receiptId??"missing"}; turnId=${n.turnId}; memoryIds=${e}; source=${n.source??"unknown"}${r}${o}.`+i}function Be(n){if(!vn(n.prompt))return null;let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let t=n.prompt.trim().slice(0,4e3),r=createHash("sha256").update(t).digest("hex"),o=e.listMemoryTurns(n.projectRoot,n.sessionId,5).find(d=>d.promptHash===r&&Date.now()-d.createdAt<1e4),i=o?{turnId:o.turnId,eventId:o.eventId,promptHash:o.promptHash,createdAt:o.createdAt}:Sn(n.sessionId,t),s=o??e.beginMemoryTurn({...i,projectRoot:n.projectRoot,sessionId:n.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:X(s),skipSkillRouting:s.source==="explicit_intent"};let a=x(t)??void 0,c=a?"commit_explicit":"capture_prompt";return e.enqueueWork({idempotencyKey:`memory-turn:${c}:${s.turnId}`,kind:a?"memory.explicit_commit":"memory.turn_capture",projectRoot:n.projectRoot,sessionId:n.sessionId,turnId:s.turnId,payload:{operation:c,turnId:s.turnId,eventId:s.eventId,sessionId:n.sessionId,prompt:t,explicitContent:a,createdAt:s.createdAt}}),{turn:s,explicitContent:a,additionalContext:a?`DevFlow explicit memory is durably queued for ${s.turnId}, but no canonical receipt exists yet. Do not claim that it was remembered.`:Ke(s),skipSkillRouting:!!a}}finally{e.close();}}async function Ye(n){let{payload:e,memory:t,projectRoot:r}=n,o=openGlobalDevFlowDatabase();try{let i=o.getMemoryTurn(e.turnId);if(!i)throw new Error(`Memory turn ${e.turnId} does not exist`);if(i.status!=="pending")return {turn:i,additionalContext:X(i),skipSkillRouting:i.source==="explicit_intent"};if(await t.recordUserMessage(e.prompt,e.sessionId,e.prompt.slice(0,200)),await t.recordEvent({id:e.eventId,sessionId:e.sessionId,tool:"UserPromptSubmit",kind:"user_message",payload:{prompt:e.prompt,turnId:e.turnId},createdAt:e.createdAt}),e.operation==="capture_prompt"||!e.explicitContent)return {turn:i,additionalContext:Ke(i),skipSkillRouting:!1};let s=await t.saveExplicitMemoryIntent(e.explicitContent,e.sessionId,e.eventId),a=In(i.turnId,"committed",[s.id]),c=o.commitMemoryTurn({turnId:i.turnId,receiptId:a,memoryIds:[s.id],source:"explicit_intent",reason:"explicit_user_request"});try{await t.enrichExplicitMemoryObservation(s.id);}catch(d){console.error("[devflow] Explicit memory enrichment deferred:",d.message),o.enqueueWork({idempotencyKey:`explicit-enrichment:${r}:${s.id}`,kind:"memory.explicit_enrichment",projectRoot:r,sessionId:e.sessionId,turnId:c.turnId,payload:{observationId:s.id},maxAttempts:20});}o.enqueueWork({idempotencyKey:`vector:${r}:${s.id}`,kind:"memory.vector_backfill",projectRoot:r,sessionId:e.sessionId,turnId:c.turnId,payload:{observationId:s.id},maxAttempts:20});try{await ze({projectRoot:r,memory:t,injectConfig:loadConfig(r).sessionStart?.injectMemories,reason:"explicit_memory_commit"});}catch(d){console.error("[devflow] Memory snapshot refresh failed after canonical commit:",d.message);}return {turn:c,explicitContent:e.explicitContent,additionalContext:X(c),skipSkillRouting:!0}}finally{o.close();}}function Ze(n,e){let t=Rn(n);mkdirSync(t,{recursive:true,mode:448});let r=`memory-turn-spool-${Date.now()}-${process.pid}-${randomUUID()}`,o=join(t,`${r}.json`),i=`${o}.tmp`;return writeFileSync(i,JSON.stringify({...e,prompt:e.prompt.trim().slice(0,4e3)}),{mode:384}),renameSync(i,o),r}function Rn(n){return join(I(n),"memory-turn-pending")}function Qe(n){let e=Date.now();try{let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100});try{let r=`context-prefetch:${createHash("sha256").update(`${n.projectRoot}\0${n.sessionId}\0${n.executionId}\0${Dn(n.prompt)}\0${n.profileFingerprint}`).digest("hex")}`,o=t.enqueueWork({idempotencyKey:r,kind:"context.prefetch",projectRoot:n.projectRoot,sessionId:n.sessionId,payload:n,maxAttempts:3});return f("prefetch_queue",{projectRoot:n.projectRoot,skillName:n.skillName,accepted:!0,workState:o.state,latencyMs:Date.now()-e}),{accepted:!0,workItemId:o.id}}finally{t.close();}}catch(t){let r=t instanceof Error?t.message:String(t);return f("prefetch_queue",{projectRoot:n.projectRoot,skillName:n.skillName,accepted:false,reason:r,latencyMs:Date.now()-e}),{accepted:false,reason:r}}}function Dn(n){return n.trim().toLowerCase().replace(/\s+/g," ").slice(0,4e3)}var p=process.env.CLAUDE_PROJECT_DIR||process.cwd();async function Tn(n){let e=ee()?[Q]:[],t;try{t=JSON.parse(n);}catch{return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...e.length?{additionalContext:e.join(`
12
+ `)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,n,e,t]=process.argv;n!=="session-start"||!e?process.exitCode=2:process.stdout.write(yn({projectRoot:e,configPath:t,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var bn=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu;function vn(n){let e=n.trim();return e.length>0&&!bn.test(e)}function Sn(n,e,t=Date.now()){let r=createHash("sha256").update(e.trim()).digest("hex"),o=createHash("sha256").update(`${n}\0${t}\0${r}`).digest("hex").slice(0,24);return {turnId:`turn:${o}`,eventId:`memory-turn:${o}`,promptHash:r,createdAt:t}}function In(n,e,t=[]){return `memory-receipt:${createHash("sha256").update(`${n}\0${e}\0${[...t].sort().join("\0")}`).digest("hex").slice(0,24)}`}function Ke(n){return `DevFlow memory decision required for ${n.turnId}. Before the final response, semantically decide whether this turn contains durable project knowledge. Call mcp__devflow__memory_commit_turn with evidence-bound candidates, or mcp__devflow__memory_skip_turn with a concrete reason. Do not claim memory success without a canonical receipt. For candidates, preserve exact package names, flags, versions, paths, and identifiers; provide subject, predicate, value, polarity, and entities when known. Do not save assistant echoes, task narration, retries, or unverified guesses. Express a change from an old choice as the new durable value. If the decision tool remains unavailable, explicitly state that the memory was not saved.`}function X(n){let e=n.memoryIds.length>0?n.memoryIds.join(","):"none",t=n.status==="committed"?"accepted":n.status,r=n.status==="committed"?"; indexStatus=pending":"",o=n.status==="committed"&&n.source==="explicit_intent"?"; memoryOnlyCompleted=true; skipProjectContext=true; skipMemoryTool=true":"",i=n.status==="committed"&&n.source==="explicit_intent"?" This explicit-memory request is complete. Return the canonical receipt to the user. Do not call a memory tool, project-context tool, domain tool, or native memory write for this request.":"";return `DevFlow canonical memory receipt: status=${t}; receiptId=${n.receiptId??"missing"}; turnId=${n.turnId}; memoryIds=${e}; source=${n.source??"unknown"}${r}${o}.`+i}function Be(n){if(!vn(n.prompt))return null;let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let t=n.prompt.trim().slice(0,4e3),r=createHash("sha256").update(t).digest("hex"),o=e.listMemoryTurns(n.projectRoot,n.sessionId,5).find(d=>d.promptHash===r&&Date.now()-d.createdAt<1e4),i=o?{turnId:o.turnId,eventId:o.eventId,promptHash:o.promptHash,createdAt:o.createdAt}:Sn(n.sessionId,t),s=o??e.beginMemoryTurn({...i,projectRoot:n.projectRoot,sessionId:n.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:X(s),skipSkillRouting:s.source==="explicit_intent"};let a=x(t)??void 0,c=a?"commit_explicit":"capture_prompt";return e.enqueueWork({idempotencyKey:`memory-turn:${c}:${s.turnId}`,kind:a?"memory.explicit_commit":"memory.turn_capture",projectRoot:n.projectRoot,sessionId:n.sessionId,turnId:s.turnId,payload:{operation:c,turnId:s.turnId,eventId:s.eventId,sessionId:n.sessionId,prompt:t,explicitContent:a,createdAt:s.createdAt}}),{turn:s,explicitContent:a,additionalContext:a?`DevFlow explicit memory is durably queued for ${s.turnId}, but no canonical receipt exists yet. Do not claim that it was remembered.`:Ke(s),skipSkillRouting:!!a}}finally{e.close();}}async function Ye(n){let{payload:e,memory:t,projectRoot:r}=n,o=openGlobalDevFlowDatabase();try{let i=o.getMemoryTurn(e.turnId);if(!i)throw new Error(`Memory turn ${e.turnId} does not exist`);if(i.status!=="pending"){if(i.receiptId&&typeof t.reconcileTurnObservationLineage=="function")try{await t.reconcileTurnObservationLineage([i]);}catch{}return {turn:i,additionalContext:X(i),skipSkillRouting:i.source==="explicit_intent"}}if(await t.recordUserMessage(e.prompt,e.sessionId,e.prompt.slice(0,200)),await t.recordEvent({id:e.eventId,sessionId:e.sessionId,tool:"UserPromptSubmit",kind:"user_message",payload:{prompt:e.prompt,turnId:e.turnId},createdAt:e.createdAt}),e.operation==="capture_prompt"||!e.explicitContent)return {turn:i,additionalContext:Ke(i),skipSkillRouting:!1};let s=await t.saveExplicitMemoryIntent(e.explicitContent,e.sessionId,e.eventId),a=In(i.turnId,"committed",[s.id]),c=o.commitMemoryTurn({turnId:i.turnId,receiptId:a,memoryIds:[s.id],source:"explicit_intent",reason:"explicit_user_request"});try{typeof t.finalizeTurnDecision=="function"&&await t.finalizeTurnDecision({turnEventId:i.eventId,sessionId:i.sessionId,turnId:i.turnId,receiptId:a,status:"committed",memoryIds:[s.id],reason:"explicit_user_request"});}catch(d){console.error("[devflow] Canonical memory lineage finalization deferred:",d.message);}try{await t.enrichExplicitMemoryObservation(s.id);}catch(d){console.error("[devflow] Explicit memory enrichment deferred:",d.message),o.enqueueWork({idempotencyKey:`explicit-enrichment:${r}:${s.id}`,kind:"memory.explicit_enrichment",projectRoot:r,sessionId:e.sessionId,turnId:c.turnId,payload:{observationId:s.id},maxAttempts:20});}o.enqueueWork({idempotencyKey:`vector:${r}:${s.id}`,kind:"memory.vector_backfill",projectRoot:r,sessionId:e.sessionId,turnId:c.turnId,payload:{observationId:s.id},maxAttempts:20});try{await Ge({projectRoot:r,memory:t,injectConfig:loadConfig(r).sessionStart?.injectMemories,reason:"explicit_memory_commit"});}catch(d){console.error("[devflow] Memory snapshot refresh failed after canonical commit:",d.message);}return {turn:c,explicitContent:e.explicitContent,additionalContext:X(c),skipSkillRouting:!0}}finally{o.close();}}function Ze(n,e){let t=Rn(n);mkdirSync(t,{recursive:true,mode:448});let r=`memory-turn-spool-${Date.now()}-${process.pid}-${randomUUID()}`,o=join(t,`${r}.json`),i=`${o}.tmp`;return writeFileSync(i,JSON.stringify({...e,prompt:e.prompt.trim().slice(0,4e3)}),{mode:384}),renameSync(i,o),r}function Rn(n){return join(I(n),"memory-turn-pending")}function Qe(n){let e=Date.now();try{let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100});try{let r=`context-prefetch:${createHash("sha256").update(`${n.projectRoot}\0${n.sessionId}\0${n.executionId}\0${Dn(n.prompt)}\0${n.profileFingerprint}`).digest("hex")}`,o=t.enqueueWork({idempotencyKey:r,kind:"context.prefetch",projectRoot:n.projectRoot,sessionId:n.sessionId,payload:n,maxAttempts:3});return f("prefetch_queue",{projectRoot:n.projectRoot,skillName:n.skillName,accepted:!0,workState:o.state,latencyMs:Date.now()-e}),{accepted:!0,workItemId:o.id}}finally{t.close();}}catch(t){let r=t instanceof Error?t.message:String(t);return f("prefetch_queue",{projectRoot:n.projectRoot,skillName:n.skillName,accepted:false,reason:r,latencyMs:Date.now()-e}),{accepted:false,reason:r}}}function Dn(n){return n.trim().toLowerCase().replace(/\s+/g," ").slice(0,4e3)}var p=process.env.CLAUDE_PROJECT_DIR||process.cwd();async function Tn(n){let e=ee()?[Q]:[],t;try{t=JSON.parse(n);}catch{return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...e.length?{additionalContext:e.join(`
13
13
  `)}:{}}}}let r=t.prompt||"";if(!r.trim())return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...e.length?{additionalContext:e.join(`
14
14
  `)}:{}}};let o=t.session_id?.trim(),i=me(r),s=false,a;if(o)try{let c=Be({projectRoot:p,sessionId:o,prompt:r});if(c){let d=c;if(c.explicitContent&&c.turn.status==="pending"){let u=new MemoryGate(p);try{d=await Ye({projectRoot:p,payload:{operation:"commit_explicit",turnId:c.turn.turnId,eventId:c.turn.eventId,sessionId:o,prompt:r.trim().slice(0,4e3),explicitContent:c.explicitContent,createdAt:c.turn.createdAt},memory:u});}catch(l){console.error("[devflow] Explicit memory commit deferred:",l.message);}finally{u.close();}}e.push(d.additionalContext),s=d.skipSkillRouting;}}catch(c){s=!!x(r);try{let d=Ze(p,{sessionId:o,prompt:r,createdAt:Date.now()});e.push(`DevFlow memory turn status=accepted; durable=true; receiptId=${d}; canonicalMemory=false; SQLite queue replay pending. Do not claim memory success without a canonical receipt.`),console.error("[devflow] Memory turn spooled after database contention:",c.message);}catch(d){e.push("DevFlow memory turn status=degraded; durable=false; no canonical receipt exists. Do not claim memory success."),console.error("[devflow] Memory turn persistence unavailable:",d.message);}}if(o&&i&&!s){let c=new E(p),d=c.get(o)?.executionId,u=c.startExecution(o,i.skillName,fe(i.skillName));if(a=u.executionId,u.executionId&&u.executionId!==d){let m=new M;try{await m.sendSessionStart(o,p,u.startedAt),await m.sendExecutionStart(u.executionId,o,i.skillName,u.lastActivityAt,p,u.requiredMcpTools);}finally{m.close();}}let l=ge(i.skillName,p,r);l&&e.push(l);}if(o&&i&&a&&!s){let c=resolveProjectCapabilityProfile(p),d=resolveCapabilityRollout(p).config.retrievalSessions;Qe({prompt:r.trimStart().replace(/^\/devflow:[a-z0-9][a-z0-9-]*\b/i,"").trim()||r,projectRoot:p,sessionId:o,executionId:a,skillName:i.skillName,profileFingerprint:c.fingerprint,rolloutMode:d,retrievalVersion:"r2.v1",createdAt:Date.now()});}return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...e.length?{additionalContext:e.join(`
15
15
  `)}:{}}}}if(process.argv[1]?.endsWith("user-prompt-submit")||process.argv[1]?.endsWith("user-prompt-submit.js")){let n=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t;}),process.stdin.on("end",async()=>{let t=await Tn(e.trim()||process.argv[2]||"");n(JSON.stringify(t)),process.exit(0);}),process.stdin.on("error",()=>{n(JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow"}})),process.exit(0);}),setTimeout(()=>{n(JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow"}})),process.exit(0);},3e4).unref();}export{Tn as handleUserPromptSubmit};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devflow-tools/claude-code-plugin",
3
- "version": "0.16.25",
3
+ "version": "0.16.27",
4
4
  "description": "DevFlow — Developer Intelligence Platform for Claude Code",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -12,21 +12,21 @@
12
12
  "verify:runtime-dependencies": "npx tsx scripts/verify-runtime-dependencies.ts"
13
13
  },
14
14
  "dependencies": {
15
- "@devflow-tools/benchmark": "0.16.25",
16
- "@devflow-tools/context-engine": "0.16.25",
17
- "@devflow-tools/database": "0.16.25",
18
- "@devflow-tools/memory-engine": "0.16.25",
19
- "@devflow-tools/sdk": "0.16.25",
20
- "@devflow-tools/server": "0.16.25",
21
- "@devflow-tools/telemetry": "0.16.25",
22
- "@devflow-tools/workflow-engine": "0.16.25"
15
+ "@devflow-tools/benchmark": "0.16.27",
16
+ "@devflow-tools/context-engine": "0.16.27",
17
+ "@devflow-tools/database": "0.16.27",
18
+ "@devflow-tools/memory-engine": "0.16.27",
19
+ "@devflow-tools/sdk": "0.16.27",
20
+ "@devflow-tools/server": "0.16.27",
21
+ "@devflow-tools/telemetry": "0.16.27",
22
+ "@devflow-tools/workflow-engine": "0.16.27"
23
23
  },
24
24
  "allowScripts": {
25
25
  "better-sqlite3@12.11.1": true,
26
26
  "sharp@0.32.6": true
27
27
  },
28
28
  "devDependencies": {
29
- "@devflow-tools/mcp-server": "0.16.25"
29
+ "@devflow-tools/mcp-server": "0.16.27"
30
30
  },
31
31
  "keywords": [
32
32
  "pi-package",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devflow-tools/cli",
3
- "version": "0.16.25",
3
+ "version": "0.16.27",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "scripts": {
@@ -12,31 +12,31 @@
12
12
  },
13
13
  "dependencies": {
14
14
  "@colbymchenry/codegraph": "^1.1.1",
15
- "@devflow-tools/adapters": "0.16.25",
16
- "@devflow-tools/benchmark": "0.16.25",
17
- "@devflow-tools/context-engine": "0.16.25",
18
- "@devflow-tools/database": "0.16.25",
19
- "@devflow-tools/knowledge-engine": "0.16.25",
20
- "@devflow-tools/mcp-server": "0.16.25",
21
- "@devflow-tools/memory-engine": "0.16.25",
22
- "@devflow-tools/plugin-animation": "0.16.25",
23
- "@devflow-tools/plugin-css": "0.16.25",
24
- "@devflow-tools/plugin-docker": "0.16.25",
25
- "@devflow-tools/plugin-electron": "0.16.25",
26
- "@devflow-tools/plugin-git": "0.16.25",
27
- "@devflow-tools/plugin-graphql": "0.16.25",
28
- "@devflow-tools/plugin-nest": "0.16.25",
29
- "@devflow-tools/plugin-nextjs": "0.16.25",
30
- "@devflow-tools/plugin-performance": "0.16.25",
31
- "@devflow-tools/plugin-react": "0.16.25",
32
- "@devflow-tools/plugin-tailwind": "0.16.25",
33
- "@devflow-tools/plugin-taro": "0.16.25",
34
- "@devflow-tools/plugin-ui-layout": "0.16.25",
35
- "@devflow-tools/plugin-vue": "0.16.25",
36
- "@devflow-tools/sdk": "0.16.25",
37
- "@devflow-tools/server": "0.16.25",
38
- "@devflow-tools/telemetry": "0.16.25",
39
- "@devflow-tools/workflow-engine": "0.16.25",
15
+ "@devflow-tools/adapters": "0.16.27",
16
+ "@devflow-tools/benchmark": "0.16.27",
17
+ "@devflow-tools/context-engine": "0.16.27",
18
+ "@devflow-tools/database": "0.16.27",
19
+ "@devflow-tools/knowledge-engine": "0.16.27",
20
+ "@devflow-tools/mcp-server": "0.16.27",
21
+ "@devflow-tools/memory-engine": "0.16.27",
22
+ "@devflow-tools/plugin-animation": "0.16.27",
23
+ "@devflow-tools/plugin-css": "0.16.27",
24
+ "@devflow-tools/plugin-docker": "0.16.27",
25
+ "@devflow-tools/plugin-electron": "0.16.27",
26
+ "@devflow-tools/plugin-git": "0.16.27",
27
+ "@devflow-tools/plugin-graphql": "0.16.27",
28
+ "@devflow-tools/plugin-nest": "0.16.27",
29
+ "@devflow-tools/plugin-nextjs": "0.16.27",
30
+ "@devflow-tools/plugin-performance": "0.16.27",
31
+ "@devflow-tools/plugin-react": "0.16.27",
32
+ "@devflow-tools/plugin-tailwind": "0.16.27",
33
+ "@devflow-tools/plugin-taro": "0.16.27",
34
+ "@devflow-tools/plugin-ui-layout": "0.16.27",
35
+ "@devflow-tools/plugin-vue": "0.16.27",
36
+ "@devflow-tools/sdk": "0.16.27",
37
+ "@devflow-tools/server": "0.16.27",
38
+ "@devflow-tools/telemetry": "0.16.27",
39
+ "@devflow-tools/workflow-engine": "0.16.27",
40
40
  "@inquirer/prompts": "^7.10.1",
41
41
  "chalk": "^5.3.0",
42
42
  "commander": "^12.0.0"
@@ -49,5 +49,5 @@
49
49
  "dist",
50
50
  "bin"
51
51
  ],
52
- "gitHead": "22b0d1c0bf96b9ce3a6ea445db07f084a52adb7c"
52
+ "gitHead": "964af33767bf232606e63d973b3a29d7d53c8119"
53
53
  }