@devflow-tools/cli 0.18.0 → 0.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,42 +1,42 @@
1
- import {createServer,createConnection}from'net';import {createHash,randomUUID as randomUUID$1}from'node:crypto';import {execFileSync,spawn as spawn$1}from'node:child_process';import {join as join$1,dirname}from'path';import {mkdirSync,lstatSync,openSync,writeFileSync,fstatSync,closeSync,readFileSync,unlinkSync,existsSync as existsSync$1,readdirSync,rmSync,linkSync,renameSync as renameSync$1}from'fs';import {getLocalApiKey,getDevFlowStateRoot,getDaemonSocketPath,getDaemonPidPath,resolveCapabilityRollout,loadConfig,readRuntimeEndpointState,updateRuntimeEndpointStatus,resolveRuntimeEndpoint,writeRuntimeEndpointState,selectHostAdapter,getProjectStateDir,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,claudeCodeRuntimeAdapter,semanticTextHash,stableRuntimeHash,resolveRuntimeActivationSnapshot,getDaemonRegistryPath,getProjectHash,createDefaultHostAdapterRegistry}from'@devflow-tools/sdk';import {openGlobalDevFlowDatabase,retrievalLedgerTransitionId,stableLearningJson}from'@devflow-tools/database';import {request as request$1}from'node:http';import {mkdirSync as mkdirSync$1,existsSync,writeFileSync as writeFileSync$1,renameSync,unlinkSync as unlinkSync$1,readFileSync as readFileSync$1,openSync as openSync$1,constants,fstatSync as fstatSync$1,closeSync as closeSync$1,readdirSync as readdirSync$1,rmSync as rmSync$1,appendFileSync,realpathSync,statSync,readSync,lstatSync as lstatSync$1,chmodSync,fsyncSync}from'node:fs';import {join,dirname as dirname$1,basename,resolve,relative,sep,isAbsolute}from'node:path';import {fileURLToPath}from'url';import {emitSemanticControlLog,SemanticRuntimeEventProjector}from'@devflow-tools/telemetry';import {spawn}from'child_process';import {request}from'http';import {createRequire}from'node:module';import {prepareEmbeddingModel,MemoryGate}from'@devflow-tools/memory-engine';import {randomUUID,createHash as createHash$1}from'crypto';import {TaskKernel,TaskEventStore}from'@devflow-tools/task-runtime';import {homedir}from'node:os';import {GraderRegistry}from'@devflow-tools/benchmark';import {createManagedWorktree,createWorkerArtifacts,launchWorker,readWorkerHandoff,verifyWorkerOutput,SerializedWorkerMergeQueue,cleanupManagedWorktree,workerCoordinationRoot,writeJsonAtomic}from'@devflow-tools/workflow-engine';function Q(t,e,n){try{let o=openGlobalDevFlowDatabase();try{o.insertEvent({kind:t,timestamp:Date.now(),duration:n,success:e.success!==!1,metadata:e});}finally{o.close();}}catch{}}var bi=getLocalApiKey(),pt=join(getDevFlowStateRoot(),"errors");async function J(t,e,n={}){let o=n.endpoint??resolveRuntimeEndpoint().url,r=n.timeout??1500,i=n.durableMirror??true,s=n.maxRetries??(i?0:2),a=n.circuitBreaker??true,c=acquireRuntimeHttpCircuit(o,t);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 Ri(o,t,e,r),a&&registerRuntimeHttpSuccess(o,t).transitioned&&Q("http_circuit_transition",{endpoint:o,path:new URL(t,o).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 Si(Math.min(100*2**l,1e3));}if(!d)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return Tn(t,d),{delivered:false,suppressed:false,fallbackReason:d.message};let u=registerRuntimeHttpFailure(o,t,n.fallbackReason??(i?"local_durable_mirror":"http_delivery_failed"));return u.transitioned&&(Tn(t,d),Q("http_circuit_transition",{endpoint:o,path:new URL(t,o).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 Ri(t,e,n,o){return new Promise((r,i)=>{let s=JSON.stringify(n),a=new URL(e,t),c=false,d=l=>{c||(c=true,l?i(l):r());},u=request$1({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":bi,"Content-Length":Buffer.byteLength(s)},timeout:o},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 ${o}ms`))),u.write(s),u.end();})}function Tn(t,e){try{existsSync(pt)||mkdirSync$1(pt,{recursive:!0}),appendFileSync(join(pt,"http-errors.log"),`${new Date().toISOString()} | ${t} | ${e.message}
2
- `);}catch{}}function Si(t){return new Promise(e=>setTimeout(e,t))}var On=1e4,Di=3e4,De=500,Z=class{constructor(e){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=e?.apiUrl,this.cacheDir=e?.cacheDir??join$1(getDevFlowStateRoot(),"global","telemetry-cache"),this.database=e?.database??null,this.ownsDatabase=!e?.database;let n=e?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(n)&&n>=0?n:100;}async sendEvent(e){let n={...e,input:this.truncateInput(e.input)};return this.commitOrCache("tool_call",n)?(this.postHttp("/api/telemetry/tool-call",n),e.eventId):null}async sendExecutionStart(e,n,o,r,i=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:e,sessionId:n,skillName:o,startedAt:r,projectRoot:i,requiredMcpTools:s};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(e,n="completed",o=Date.now(),r){let i={executionId:e,status:n,finishedAt:o,metadata:r},s=this.commitOrCache("execution_complete",i);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",i),s}async sendSessionStart(e,n,o){let r={id:e,projectRoot:n,startedAt:o,label:n.split("/").pop()??"unknown"},i=this.commitOrCache("session_start",r);return i&&this.postHttp("/api/telemetry/sessions",r),i}async completeEvent(e){let n=this.commitOrCache("complete_event",e);return n&&(this.postHttp("/api/telemetry/tool-call/output",e),this.scheduleMetricAggregation()),n}async endSession(e,n=Date.now()){let o={sessionId:e,finishedAt:n},r=this.commitOrCache("session_end",o);return r&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(e)}/close`,{finishedAt:n})),r}async flushCache(){try{let n=this.getDatabase(),o=n.listTelemetryFailures({unresolvedOnly:!0,limit:De}).reverse();for(let r of o)try{this.applyOperation(r.operation,r.payload),n.resolveTelemetryFailure(r.id);}catch{}n.trimTelemetryFailures(De);}catch{}let e=(existsSync$1(this.cacheDir)?readdirSync(this.cacheDir):[]).filter(n=>n.endsWith(".json")).map(n=>{let o=join$1(this.cacheDir,n);try{return {cacheFile:o,envelope:Mi(JSON.parse(readFileSync(o,"utf8")))}}catch{return null}}).filter(n=>n!==null).sort((n,o)=>n.envelope.timestamp-o.envelope.timestamp||Pn(n.envelope.operation)-Pn(o.envelope.operation));for(let{cacheFile:n,envelope:o}of e)try{let r=this.getDatabase();r.insertTelemetryFailure({id:o.id,operation:o.operation,payload:o.payload,error:o.failure,createdAt:o.timestamp}),this.applyOperation(o.operation,o.payload),r.resolveTelemetryFailure(o.id),unlinkSync(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(e,n){try{return this.applyOperation(e,n),!0}catch(o){return this.cacheOperation(e,n,o),false}}applyOperation(e,n){let o=this.getDatabase();switch(e){case "tool_call":this.ensureParentSession(o,n),o.insertToolCallEvent(n);return;case "execution_start":this.ensureParentSession(o,n),o.insertSkillExecution({executionId:n.executionId,sessionId:n.sessionId,skillName:n.skillName,startedAt:n.startedAt,status:"running",requiredMcpTools:n.requiredMcpTools});return;case "execution_complete":o.reconcileSkillExecution(n.executionId,n.status,n.finishedAt,n.metadata);return;case "session_start":o.ensureSession(n),o.insertRun({id:jn(n.id),source:"hook",tool:"session",input:{projectRoot:n.projectRoot},status:"active",startedAt:n.startedAt,tokenUsed:0,metadata:{sessionId:n.id,projectRoot:n.projectRoot}});return;case "complete_event":if(!o.updateToolCallEvent(n.eventId,{output:n.output===void 0?void 0:JSON.stringify(n.output),error:n.error,failureCategory:n.failureCategory,duration:n.duration}))throw new Error(`Tool call event ${n.eventId} is not available for completion`);return;case "session_end":o.closeSession(n.sessionId,n.finishedAt),o.updateRun(jn(n.sessionId),{status:"completed",finishedAt:n.finishedAt});return}}ensureParentSession(e,n){let o=typeof n.sessionId=="string"?n.sessionId.trim():"";if(!o)throw new Error("Canonical session ID is required for telemetry");let r=typeof n.projectRoot=="string"&&n.projectRoot.trim()?n.projectRoot:typeof n.input?.projectRoot=="string"&&n.input.projectRoot.trim()?n.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";e.ensureSession({id:o,projectRoot:r,label:r==="unknown"?void 0:r.split("/").pop(),startedAt:Number(n.startedAt??n.timestamp??Date.now())});}cacheOperation(e,n,o){let r=Date.now(),i={id:`failure:${r}:${Math.random().toString(36).slice(2,11)}`,operation:e,payload:n,failure:o instanceof Error?o.message:String(o),timestamp:r};try{let s=this.getDatabase();s.insertTelemetryFailure({id:i.id,operation:e,payload:n,error:i.failure,createdAt:r}),s.trimTelemetryFailures(De),this.scheduleRetry();return}catch{}try{existsSync$1(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${r}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(s,JSON.stringify(i,null,2),{mode:384}),this.trimRetryCache(),this.scheduleRetry();}catch{}}trimRetryCache(){try{let e=readdirSync(this.cacheDir).filter(n=>n.endsWith(".json")).sort();for(let n of e.slice(0,Math.max(0,e.length-De)))unlinkSync(join$1(this.cacheDir,n));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},Di).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,n){J(e,n,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(e){let n=JSON.stringify(e);return n===void 0||n.length<=On?e:{_truncated:true,_original_size:n.length,_preview:`${n.substring(0,On)}...`}}};function Pn(t){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(t)}function jn(t){return `hook-run:${t}`}function Mi(t){if(!t||typeof t!="object")throw new Error("Invalid telemetry cache envelope");let e=t;if(typeof e.id!="string"||typeof e.operation!="string"||e.payload===void 0||typeof e.failure!="string"||typeof e.timestamp!="number")throw new Error("Invalid telemetry cache envelope");return e}function Me(t){return t??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function P(t){return getProjectStateDir(Me(t))}var y=emitSemanticControlLog;var Li=2,Ni=1;function qi(){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 $n(t=qi()){let e=[join$1(t,"dist","command-registry.json"),join$1(t,"command-registry.json")];for(let n of e)try{if(!existsSync$1(n))continue;let o=JSON.parse(readFileSync(n,"utf8"));if(o.version!==Li&&o.version!==Ni||!Wi(o.commands)){y({event:"hook.runtime.degraded",identity:{projectRoot:process.env.CLAUDE_PROJECT_DIR||process.cwd()},level:"warn",timestamp:Date.now(),data:{stage:"command_registry",reason:"contract_mismatch",registryPath:n}});continue}return o.commands}catch(o){y({event:"hook.runtime.degraded",identity:{projectRoot:process.env.CLAUDE_PROJECT_DIR||process.cwd()},level:"warn",timestamp:Date.now(),data:{stage:"command_registry",reason:o.message,fallback:"next_registry_candidate"}});}return null}function Wi(t){return !t||typeof t!="object"||Array.isArray(t)?false:Object.values(t).every(e=>{if(!e||typeof e!="object"||Array.isArray(e))return false;let n=e;return Oe(n.mcpTools)&&Oe(n.blockedNative)&&(n.source===void 0||n.source==="core"||n.source==="plugin")&&(n.requiresContext===void 0||typeof n.requiresContext=="boolean")&&(n.runtimePackages===void 0||Oe(n.runtimePackages))&&(n.hostTools===void 0||Ui(n.hostTools))&&(n.evidenceMode===void 0||["static","runtime","mixed"].includes(n.evidenceMode))})}function Ui(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&Object.entries(t).every(([e,n])=>e.length>0&&Oe(n))}function Oe(t){return Array.isArray(t)&&t.every(e=>typeof e=="string"&&e.length>0)}var Ki={react:["react","react-dom"],nextjs:["next","react"],vue:["vue"],nest:["@nestjs/core"],tailwind:["tailwindcss"],taro:["@tarojs/taro"],electron:["electron"],graphql:["graphql"]};function Gi(t,e){let n=join(t,"package.json"),o=Nn(n),r=ts(o,e),i=join(t,"package-lock.json"),s=Nn(i),a=ns(s,e);return a?{packageName:e,...r?{declaredRange:r}:{},resolvedVersion:a,evidencePath:relative(t,i)||"package-lock.json",confidence:"high"}:r?{packageName:e,declaredRange:r,evidencePath:relative(t,n)||"package.json",confidence:"medium"}:{packageName:e,confidence:"unknown"}}function qn(t,e,n={}){let o=t.replace(/^devflow:/,"").split(":").pop()??t,r=(Ki[o]??[]).map(a=>Gi(e,a)),i=n.rolloutMode??resolveCapabilityRollout(e).config.learningOverlays;if(i==="off")return {skillName:t,projectRoot:e,packages:r,learned:[],shadowEligible:[],rolloutMode:i};let s=n.database??openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let c=s.listLearningCandidates({projectRoot:e,states:["shadow","evaluated","active"],limit:100}).filter(m=>m.projectRoot===e||m.scope==="global").filter(m=>!m.expiresAt||m.expiresAt>(n.now??Date.now())).filter(m=>Qi(m,t,n)).sort((m,f)=>f.confidence-m.confidence||f.updatedAt-m.updatedAt),d=Xi(c.map(m=>Yi(m,m.state==="active"?"active":"shadow")),n),u=i==="on"?d.filter(m=>m.state==="active"):[],l=d.filter(m=>m.state==="shadow"||i==="shadow");try{s.insertEvent({kind:"learning_overlay_match",timestamp:Date.now(),success:!0,metadata:{projectRoot:e,skillName:t,rolloutMode:i,eligible:d.map(m=>`${m.candidateId}@${m.version}`),injected:u.map(m=>`${m.candidateId}@${m.version}`)}});}catch{}return {skillName:t,projectRoot:e,packages:r,learned:u,shadowEligible:l,rolloutMode:i}}finally{n.database||s.close();}}function Wn(t){let e=[],n=t.packages.map(o=>{let r=o.resolvedVersion??o.declaredRange??"unknown";return `${o.packageName}=${r} (confidence=${o.confidence}${o.evidencePath?`, source=${o.evidencePath}`:""})`}).join("; ");return n&&e.push(`DevFlow runtime project-version evidence for ${t.skillName}: ${n}. Treat target-project evidence as authoritative; do not apply a hardcoded framework version.`),t.learned.length>0&&e.push([`DevFlow governed project instructions for ${t.skillName}:`,...t.learned.map(o=>`- ${o.instruction}`),"Apply only to this request and keep canonical Skill/MCP requirements unchanged."].join(`
1
+ import {createServer,createConnection}from'net';import {createHash,randomUUID as randomUUID$1}from'node:crypto';import {execFileSync,spawn as spawn$1}from'node:child_process';import {join as join$1,dirname}from'path';import {mkdirSync,lstatSync,openSync,writeFileSync,fstatSync,closeSync,readFileSync,unlinkSync,existsSync as existsSync$1,readdirSync,rmSync,linkSync,renameSync as renameSync$1}from'fs';import {getLocalApiKey,getDevFlowStateRoot,getDaemonSocketPath,getDaemonPidPath,resolveCapabilityRollout,loadConfig,readRuntimeEndpointState,updateRuntimeEndpointStatus,resolveRuntimeEndpoint,writeRuntimeEndpointState,selectHostAdapter,getProjectStateDir,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,claudeCodeRuntimeAdapter,semanticTextHash,stableRuntimeHash,resolveRuntimeActivationSnapshot,getDaemonRegistryPath,getProjectHash,createDefaultHostAdapterRegistry}from'@devflow-tools/sdk';import {openGlobalDevFlowDatabase,retrievalLedgerTransitionId,stableLearningJson}from'@devflow-tools/database';import {request as request$1}from'node:http';import {mkdirSync as mkdirSync$1,existsSync,writeFileSync as writeFileSync$1,renameSync,unlinkSync as unlinkSync$1,readFileSync as readFileSync$1,openSync as openSync$1,constants,fstatSync as fstatSync$1,closeSync as closeSync$1,readdirSync as readdirSync$1,rmSync as rmSync$1,appendFileSync,realpathSync,statSync,readSync,lstatSync as lstatSync$1,chmodSync,fsyncSync}from'node:fs';import {join,dirname as dirname$1,basename,resolve,relative,sep,isAbsolute}from'node:path';import {emitSemanticControlLog,SemanticRuntimeEventProjector,rotateDiagnosticLogFile}from'@devflow-tools/telemetry';import {fileURLToPath}from'url';import {spawn}from'child_process';import {request}from'http';import {createRequire}from'node:module';import {prepareEmbeddingModel,MemoryGate}from'@devflow-tools/memory-engine';import {randomUUID,createHash as createHash$1}from'crypto';import {TaskKernel,TaskEventStore}from'@devflow-tools/task-runtime';import {homedir}from'node:os';import {GraderRegistry}from'@devflow-tools/benchmark';import {createManagedWorktree,createWorkerArtifacts,launchWorker,readWorkerHandoff,verifyWorkerOutput,SerializedWorkerMergeQueue,cleanupManagedWorktree,workerCoordinationRoot,writeJsonAtomic}from'@devflow-tools/workflow-engine';function Q(t,e,n){try{let o=openGlobalDevFlowDatabase();try{o.insertEvent({kind:t,timestamp:Date.now(),duration:n,success:e.success!==!1,metadata:e});}finally{o.close();}}catch{}}var Ri=getLocalApiKey(),pt=join(getDevFlowStateRoot(),"errors");async function J(t,e,n={}){let o=n.endpoint??resolveRuntimeEndpoint().url,r=n.timeout??1500,i=n.durableMirror??true,s=n.maxRetries??(i?0:2),a=n.circuitBreaker??true,c=acquireRuntimeHttpCircuit(o,t);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 Si(o,t,e,r),a&&registerRuntimeHttpSuccess(o,t).transitioned&&Q("http_circuit_transition",{endpoint:o,path:new URL(t,o).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 xi(Math.min(100*2**l,1e3));}if(!d)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return Tn(t,d),{delivered:false,suppressed:false,fallbackReason:d.message};let u=registerRuntimeHttpFailure(o,t,n.fallbackReason??(i?"local_durable_mirror":"http_delivery_failed"));return u.transitioned&&(Tn(t,d),Q("http_circuit_transition",{endpoint:o,path:new URL(t,o).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 Si(t,e,n,o){return new Promise((r,i)=>{let s=JSON.stringify(n),a=new URL(e,t),c=false,d=l=>{c||(c=true,l?i(l):r());},u=request$1({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":Ri,"Content-Length":Buffer.byteLength(s)},timeout:o},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 ${o}ms`))),u.write(s),u.end();})}function Tn(t,e){try{existsSync(pt)||mkdirSync$1(pt,{recursive:!0});let n=join(pt,"http-errors.log"),o=`${new Date().toISOString()} | ${t} | ${e.message}
2
+ `;rotateDiagnosticLogFile({path:n,maxBytes:50*1024*1024,maxFiles:5,incomingBytes:Buffer.byteLength(o)}),appendFileSync(n,o);}catch{}}function xi(t){return new Promise(e=>setTimeout(e,t))}var On=1e4,Mi=3e4,De=500,Z=class{constructor(e){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=e?.apiUrl,this.cacheDir=e?.cacheDir??join$1(getDevFlowStateRoot(),"global","telemetry-cache"),this.database=e?.database??null,this.ownsDatabase=!e?.database;let n=e?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(n)&&n>=0?n:100;}async sendEvent(e){let n={...e,input:this.truncateInput(e.input)};return this.commitOrCache("tool_call",n)?(this.postHttp("/api/telemetry/tool-call",n),e.eventId):null}async sendExecutionStart(e,n,o,r,i=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:e,sessionId:n,skillName:o,startedAt:r,projectRoot:i,requiredMcpTools:s};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(e,n="completed",o=Date.now(),r){let i={executionId:e,status:n,finishedAt:o,metadata:r},s=this.commitOrCache("execution_complete",i);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",i),s}async sendSessionStart(e,n,o){let r={id:e,projectRoot:n,startedAt:o,label:n.split("/").pop()??"unknown"},i=this.commitOrCache("session_start",r);return i&&this.postHttp("/api/telemetry/sessions",r),i}async completeEvent(e){let n=this.commitOrCache("complete_event",e);return n&&(this.postHttp("/api/telemetry/tool-call/output",e),this.scheduleMetricAggregation()),n}async endSession(e,n=Date.now()){let o={sessionId:e,finishedAt:n},r=this.commitOrCache("session_end",o);return r&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(e)}/close`,{finishedAt:n})),r}async flushCache(){try{let n=this.getDatabase(),o=n.listTelemetryFailures({unresolvedOnly:!0,limit:De}).reverse();for(let r of o)try{this.applyOperation(r.operation,r.payload),n.resolveTelemetryFailure(r.id);}catch{}n.trimTelemetryFailures(De);}catch{}let e=(existsSync$1(this.cacheDir)?readdirSync(this.cacheDir):[]).filter(n=>n.endsWith(".json")).map(n=>{let o=join$1(this.cacheDir,n);try{return {cacheFile:o,envelope:Oi(JSON.parse(readFileSync(o,"utf8")))}}catch{return null}}).filter(n=>n!==null).sort((n,o)=>n.envelope.timestamp-o.envelope.timestamp||Pn(n.envelope.operation)-Pn(o.envelope.operation));for(let{cacheFile:n,envelope:o}of e)try{let r=this.getDatabase();r.insertTelemetryFailure({id:o.id,operation:o.operation,payload:o.payload,error:o.failure,createdAt:o.timestamp}),this.applyOperation(o.operation,o.payload),r.resolveTelemetryFailure(o.id),unlinkSync(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(e,n){try{return this.applyOperation(e,n),!0}catch(o){return this.cacheOperation(e,n,o),false}}applyOperation(e,n){let o=this.getDatabase();switch(e){case "tool_call":this.ensureParentSession(o,n),o.insertToolCallEvent(n);return;case "execution_start":this.ensureParentSession(o,n),o.insertSkillExecution({executionId:n.executionId,sessionId:n.sessionId,skillName:n.skillName,startedAt:n.startedAt,status:"running",requiredMcpTools:n.requiredMcpTools});return;case "execution_complete":o.reconcileSkillExecution(n.executionId,n.status,n.finishedAt,n.metadata);return;case "session_start":o.ensureSession(n),o.insertRun({id:jn(n.id),source:"hook",tool:"session",input:{projectRoot:n.projectRoot},status:"active",startedAt:n.startedAt,tokenUsed:0,metadata:{sessionId:n.id,projectRoot:n.projectRoot}});return;case "complete_event":if(!o.updateToolCallEvent(n.eventId,{output:n.output===void 0?void 0:JSON.stringify(n.output),error:n.error,failureCategory:n.failureCategory,duration:n.duration}))throw new Error(`Tool call event ${n.eventId} is not available for completion`);return;case "session_end":o.closeSession(n.sessionId,n.finishedAt),o.updateRun(jn(n.sessionId),{status:"completed",finishedAt:n.finishedAt});return}}ensureParentSession(e,n){let o=typeof n.sessionId=="string"?n.sessionId.trim():"";if(!o)throw new Error("Canonical session ID is required for telemetry");let r=typeof n.projectRoot=="string"&&n.projectRoot.trim()?n.projectRoot:typeof n.input?.projectRoot=="string"&&n.input.projectRoot.trim()?n.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";e.ensureSession({id:o,projectRoot:r,label:r==="unknown"?void 0:r.split("/").pop(),startedAt:Number(n.startedAt??n.timestamp??Date.now())});}cacheOperation(e,n,o){let r=Date.now(),i={id:`failure:${r}:${Math.random().toString(36).slice(2,11)}`,operation:e,payload:n,failure:o instanceof Error?o.message:String(o),timestamp:r};try{let s=this.getDatabase();s.insertTelemetryFailure({id:i.id,operation:e,payload:n,error:i.failure,createdAt:r}),s.trimTelemetryFailures(De),this.scheduleRetry();return}catch{}try{existsSync$1(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${r}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(s,JSON.stringify(i,null,2),{mode:384}),this.trimRetryCache(),this.scheduleRetry();}catch{}}trimRetryCache(){try{let e=readdirSync(this.cacheDir).filter(n=>n.endsWith(".json")).sort();for(let n of e.slice(0,Math.max(0,e.length-De)))unlinkSync(join$1(this.cacheDir,n));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},Mi).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,n){J(e,n,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(e){let n=JSON.stringify(e);return n===void 0||n.length<=On?e:{_truncated:true,_original_size:n.length,_preview:`${n.substring(0,On)}...`}}};function Pn(t){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(t)}function jn(t){return `hook-run:${t}`}function Oi(t){if(!t||typeof t!="object")throw new Error("Invalid telemetry cache envelope");let e=t;if(typeof e.id!="string"||typeof e.operation!="string"||e.payload===void 0||typeof e.failure!="string"||typeof e.timestamp!="number")throw new Error("Invalid telemetry cache envelope");return e}function Me(t){return t??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function P(t){return getProjectStateDir(Me(t))}var y=emitSemanticControlLog;var Ni=2,qi=1;function Wi(){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 $n(t=Wi()){let e=[join$1(t,"dist","command-registry.json"),join$1(t,"command-registry.json")];for(let n of e)try{if(!existsSync$1(n))continue;let o=JSON.parse(readFileSync(n,"utf8"));if(o.version!==Ni&&o.version!==qi||!Ui(o.commands)){y({event:"hook.runtime.degraded",identity:{projectRoot:process.env.CLAUDE_PROJECT_DIR||process.cwd()},level:"warn",timestamp:Date.now(),data:{stage:"command_registry",reason:"contract_mismatch",registryPath:n}});continue}return o.commands}catch(o){y({event:"hook.runtime.degraded",identity:{projectRoot:process.env.CLAUDE_PROJECT_DIR||process.cwd()},level:"warn",timestamp:Date.now(),data:{stage:"command_registry",reason:o.message,fallback:"next_registry_candidate"}});}return null}function Ui(t){return !t||typeof t!="object"||Array.isArray(t)?false:Object.values(t).every(e=>{if(!e||typeof e!="object"||Array.isArray(e))return false;let n=e;return Oe(n.mcpTools)&&Oe(n.blockedNative)&&(n.source===void 0||n.source==="core"||n.source==="plugin")&&(n.requiresContext===void 0||typeof n.requiresContext=="boolean")&&(n.runtimePackages===void 0||Oe(n.runtimePackages))&&(n.hostTools===void 0||zi(n.hostTools))&&(n.evidenceMode===void 0||["static","runtime","mixed"].includes(n.evidenceMode))})}function zi(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&Object.entries(t).every(([e,n])=>e.length>0&&Oe(n))}function Oe(t){return Array.isArray(t)&&t.every(e=>typeof e=="string"&&e.length>0)}var Gi={react:["react","react-dom"],nextjs:["next","react"],vue:["vue"],nest:["@nestjs/core"],tailwind:["tailwindcss"],taro:["@tarojs/taro"],electron:["electron"],graphql:["graphql"]};function Yi(t,e){let n=join(t,"package.json"),o=Nn(n),r=ns(o,e),i=join(t,"package-lock.json"),s=Nn(i),a=os(s,e);return a?{packageName:e,...r?{declaredRange:r}:{},resolvedVersion:a,evidencePath:relative(t,i)||"package-lock.json",confidence:"high"}:r?{packageName:e,declaredRange:r,evidencePath:relative(t,n)||"package.json",confidence:"medium"}:{packageName:e,confidence:"unknown"}}function qn(t,e,n={}){let o=t.replace(/^devflow:/,"").split(":").pop()??t,r=(Gi[o]??[]).map(a=>Yi(e,a)),i=n.rolloutMode??resolveCapabilityRollout(e).config.learningOverlays;if(i==="off")return {skillName:t,projectRoot:e,packages:r,learned:[],shadowEligible:[],rolloutMode:i};let s=n.database??openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let c=s.listLearningCandidates({projectRoot:e,states:["shadow","evaluated","active"],limit:100}).filter(m=>m.projectRoot===e||m.scope==="global").filter(m=>!m.expiresAt||m.expiresAt>(n.now??Date.now())).filter(m=>Zi(m,t,n)).sort((m,f)=>f.confidence-m.confidence||f.updatedAt-m.updatedAt),d=Qi(c.map(m=>Xi(m,m.state==="active"?"active":"shadow")),n),u=i==="on"?d.filter(m=>m.state==="active"):[],l=d.filter(m=>m.state==="shadow"||i==="shadow");try{s.insertEvent({kind:"learning_overlay_match",timestamp:Date.now(),success:!0,metadata:{projectRoot:e,skillName:t,rolloutMode:i,eligible:d.map(m=>`${m.candidateId}@${m.version}`),injected:u.map(m=>`${m.candidateId}@${m.version}`)}});}catch{}return {skillName:t,projectRoot:e,packages:r,learned:u,shadowEligible:l,rolloutMode:i}}finally{n.database||s.close();}}function Wn(t){let e=[],n=t.packages.map(o=>{let r=o.resolvedVersion??o.declaredRange??"unknown";return `${o.packageName}=${r} (confidence=${o.confidence}${o.evidencePath?`, source=${o.evidencePath}`:""})`}).join("; ");return n&&e.push(`DevFlow runtime project-version evidence for ${t.skillName}: ${n}. Treat target-project evidence as authoritative; do not apply a hardcoded framework version.`),t.learned.length>0&&e.push([`DevFlow governed project instructions for ${t.skillName}:`,...t.learned.map(o=>`- ${o.instruction}`),"Apply only to this request and keep canonical Skill/MCP requirements unchanged."].join(`
3
3
  `)),e.join(`
4
- `)}function Yi(t,e){return {candidateId:t.id,version:t.overlayVersion,state:e,instruction:t.instruction,trigger:t.trigger,confidence:t.confidence,evidenceReceipt:t.graderReceipt??`candidate:${t.id}:v${t.overlayVersion}`,expiresAt:t.expiresAt}}function Xi(t,e){let n=Math.max(0,Math.min(e.maxLearnedEntries??3,3)),o=Math.max(0,Math.min(e.learnedCharacterBudget??1600,4e3)),r=[],i=0;for(let s of t){if(r.length>=n)break;let a=s.instruction.length+4;i+a>o||(r.push(s),i+=a);}return r}function Qi(t,e,n){let o=t.trigger,r=e.replace(/^devflow:/,"").split(":").pop()??e,i=Pe(o.skills);if(i.length>0&&!i.some(m=>m===e||m===r||m.endsWith(`:${r}`)))return false;let s=(n.prompt??"").normalize("NFKC").toLocaleLowerCase("en-US"),a=(n.command??"").normalize("NFKC").toLocaleLowerCase("en-US"),c=[...n.files??[],...Zi(n.prompt??"")].map(m=>m.replaceAll("\\","/").toLocaleLowerCase("en-US")),d=Pe(o.commands).map(Ln);if(d.length>0&&!d.some(m=>a.includes(m)||s.includes(m)))return false;let u=Pe(o.entities).map(Ln);if(u.length>0&&!u.some(m=>s.includes(m)||a.includes(m)))return false;let l=Pe(o.files).map(m=>m.replaceAll("\\","/").toLocaleLowerCase("en-US"));return !(l.length>0&&!l.some(m=>c.some(f=>es(f,m))))}function Zi(t){return t.match(/(?:^|\s)((?:src|app|apps|packages|plugins|lib|test|tests)\/[A-Za-z0-9_./@-]+)/gu)?.map(e=>e.trim())??[]}function es(t,e){if(!e.includes("*"))return t===e||t.includes(e);let n=e.replace(/[.+?^${}()|[\]\\]/gu,"\\$&").replaceAll("*",".*");return new RegExp(`^${n}$`,"u").test(t)}function Pe(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.trim().length>0):[]}function Ln(t){return t.normalize("NFKC").trim().toLocaleLowerCase("en-US")}function Nn(t){if(!existsSync(t))return null;try{let e=JSON.parse(readFileSync$1(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function ts(t,e){for(let n of ["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let o=t?.[n];if(!o||typeof o!="object"||Array.isArray(o))continue;let r=o[e];if(typeof r=="string"&&r.trim())return r.trim()}}function ns(t,e){let n=t?.packages;if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n[`node_modules/${e}`];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.version;if(typeof i=="string"&&i.trim())return i.trim()}}let o=t?.dependencies;if(o&&typeof o=="object"&&!Array.isArray(o)){let r=o[e];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.version;if(typeof i=="string"&&i.trim())return i.trim()}}}function Un(t){let e=$n();return e?e[t]?.mcpTools??[]:[]}function zn(t,e,n){return Wn(qn(t,e,{prompt:n}))}var ht=getDevFlowStateRoot(),yt=join$1(ht,"server-refs.json"),us=600*1e3,ms=500;function ps(){existsSync$1(ht)||mkdirSync(ht,{recursive:true});}function je(){try{if(existsSync$1(yt))return JSON.parse(readFileSync(yt,"utf-8"))}catch{}return {sessions:[],lastActivity:0}}function Bn(t){ps(),writeFileSync(yt,JSON.stringify(t));}var $e=class{constructor(e){this.process=null;this.idleTimer=null;this.onShutdown=null;this.ownerToken=null;this.projectRoot=e;}setOnShutdown(e){this.onShutdown=e;}addRef(e){let n=je();n.sessions.includes(e)||n.sessions.push(e),n.lastActivity=Date.now(),Bn(n),this.resetIdleTimer();}removeRef(e){let n=je();n.sessions=n.sessions.filter(o=>o!==e),n.lastActivity=Date.now(),Bn(n),n.sessions.length===0&&this.resetIdleTimer();}get activeSessions(){return je().sessions.length}async ensureRunning(){return await this.healthCheck()?true:(await this.startServer(),this.waitForReady())}get isRunning(){return this.process!==null&&!this.process.killed}async stop(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.process){this.process.kill("SIGTERM"),await new Promise(n=>{let o=setTimeout(()=>{this.process&&!this.process.killed&&this.process.kill("SIGKILL"),n();},5e3);this.process?this.process.on("exit",()=>{clearTimeout(o),n();}):(clearTimeout(o),n());}),this.process=null;let e=readRuntimeEndpointState();e&&e.ownerToken===this.ownerToken&&updateRuntimeEndpointStatus("stopped");}}async startServer(){let e=fs(this.projectRoot);this.ownerToken=randomUUID$1();let n=resolveRuntimeEndpoint();this.process=spawn(process.execPath,[e,"--devflow-instance-token",this.ownerToken],{cwd:this.projectRoot,env:{...process.env,NODE_ENV:process.env.NODE_ENV||"development"},stdio:["ignore","pipe","pipe"]}),writeRuntimeEndpointState({url:n.url,port:n.port,pid:this.process.pid??0,ownerToken:this.ownerToken,status:"launching"}),this.process.stdout?.on("data",o=>{}),this.process.stderr?.on("data",o=>{}),this.process.on("exit",o=>{let r=readRuntimeEndpointState();r&&r.ownerToken===this.ownerToken&&updateRuntimeEndpointStatus("stopped"),this.process=null,this.onShutdown&&this.onShutdown();}),this.process.on("error",()=>{let o=readRuntimeEndpointState();o&&o.ownerToken===this.ownerToken&&updateRuntimeEndpointStatus("degraded"),this.process=null;});}async waitForReady(){let e=Date.now()+3e4;for(;Date.now()<e;){if(await this.healthCheck())return true;await new Promise(n=>setTimeout(n,ms));}return false}healthCheck(){return new Promise(e=>{let n=resolveRuntimeEndpoint(),o=new URL("/api/health",n.url),r=request({hostname:o.hostname,port:o.port,path:o.pathname,method:"GET",timeout:2e3},i=>{let s=i.statusCode===200;s&&readRuntimeEndpointState()&&updateRuntimeEndpointStatus("healthy"),i.resume(),e(s);});r.on("error",()=>e(false)),r.on("timeout",()=>{r.destroy(),e(false);}),r.end();})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),!(je().sessions.length>0)&&(this.idleTimer=setTimeout(()=>{this.stop();},us).unref());}};function fs(t){let e=createRequire(import.meta.url),n=[()=>e.resolve("@devflow-tools/server/dist/main.js"),()=>join$1(t,"node_modules","@devflow-tools","server","dist","main.js"),()=>join$1(t,"apps","server","dist","main.js")];for(let o of n)try{let r=o();if(existsSync$1(r))return r}catch{}throw new Error("DevFlow server entry point is not installed or built")}function _t(t){if(!t||typeof t!="object"||Array.isArray(t))return {};let e=t,n={};for(let o of ["lastMcpCall","bypassCount"])if(o in e){let r=e[o];if(r==null)continue;n[o]=typeof r=="number"&&Number.isFinite(r)&&r>=0?r:0;}return n}function gs(t,e){return t.lastMcpCall===e.lastMcpCall&&t.bypassCount===e.bypassCount}function hs(t,e,n){let o=n instanceof Error?n.message:String(n);y({event:"hook.runtime.degraded",identity:{projectRoot:t},level:"warn",timestamp:Date.now(),data:{stage:"enforcement_receipt",operation:e,reason:o,fallback:"fail_open"}});}function Vn(t,e,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let r={},i=o.updateHookReceipt(t,a=>(r=_t(a),_t(e(r)))),s=_t(i);return {receipt:s,applied:!0,changed:!gs(r,s)}}catch(r){return hs(t,n,r),{receipt:{},applied:false,changed:false}}finally{try{o?.close();}catch{}}}function Fe(t,e){return Vn(t,()=>e,"write").applied}function It(t,e){return Vn(t,e,"update")}var Jn={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},ys=new Set(["Write","Edit","NotebookEdit"]),vs=new Set(["failed","timeout","unavailable"]);function _s(t){switch(t){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var ee=class{constructor(e,n,o){this.projectRoot=e;this.sessionId=n;this.executionId=o;}getPhase(){if(!this.sessionId||!this.executionId)return "idle";let e;try{e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let n=e.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(n&&n.expiresAt>Date.now())return "context_ready";n&&e.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId);}catch{}finally{try{e?.close();}catch{}}return "context_gathering"}getContextReceipt(){if(!this.sessionId||!this.executionId)return null;let e;try{e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let n=e.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);return n&&n.expiresAt>Date.now()?n:(n&&e.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId),null)}catch{return null}finally{try{e?.close();}catch{}}}evaluate(e,n){let o=this.getPhase();if(n||e==="Skill")return {permissionDecision:"allow"};if(o==="context_gathering"&&Jn[e])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_REQUIRED",reason:`DevFlow context required. Call mcp__devflow__get_project_context, then retry ${e}.`};if(o==="context_ready"){if(ys.has(e)){let c=this.evaluateRequiredAction();if(c)return c}return {permissionDecision:"allow"}}let r=Jn[e];if(!r)return {permissionDecision:"allow"};let i=It(this.projectRoot,c=>({...c,bypassCount:(c.bypassCount??0)+1}));if(!i.applied)return {permissionDecision:"allow"};let s=i.receipt.bypassCount??0,a=_s(e);return s>=a?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \u6B21\u76F4\u63A5\u4F7F\u7528 ${e}\uFF0C\u5EFA\u8BAE\u7528 mcp__devflow__${r} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){Fe(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}recordDomainActionOutcome(e,n,o,r){if(!this.sessionId||!this.executionId)return false;let i;try{i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let s=i.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(!s||s.expiresAt<=Date.now()||s.canonicalAction?.tool!==e)return !1;let a=Date.now(),c=r?.trim()?`${r.trim()}:${n}`:`${e}:${n}:${a}`,d=s.actionAttempts??[];return i.upsertContextReceipt({...s,actionAttempts:d.some(u=>u.id===c||r&&u.toolUseId===r&&u.status===n)?d:[...d,{id:c,tool:e,status:n,attemptedAt:a,toolUseId:r,reason:o?.slice(0,500)}].slice(-20),actionSatisfiedAt:n==="succeeded"?a:s.actionSatisfiedAt,actionDegradation:n==="succeeded"?void 0:s.actionDegradation}),!0}catch{return false}finally{try{i?.close();}catch{}}}evaluateRequiredAction(){let e=this.getContextReceipt(),n=e?.canonicalAction;if(!e||!n||!n.required||n.status!=="required")return null;let o=n.binding;if(o.requiredContextReceipt!==e.contextHash||o.projectRoot!==this.projectRoot||o.sessionId!==this.sessionId||o.requestId!==e.requestId||o.executionId&&o.executionId!==this.executionId)return {permissionDecision:"deny",reasonCode:"DEVFLOW_ACTION_BINDING_STALE",reason:"DevFlow canonical action binding is stale or mismatched. Call mcp__devflow__get_project_context again before writing."};if(e.actionSatisfiedAt)return null;if(e.actionDegradation?.authorizedByContextReceipt===e.contextHash)return {permissionDecision:"allow",additionalContext:`DevFlow degraded fallback authorized by context receipt ${e.contextHash}: ${e.actionDegradation.reason}`};let r=(e.actionAttempts??[]).filter(i=>i.tool===n.tool&&vs.has(i.status));if(r.length>0){let i=r.at(-1),s={missedTool:n.tool,failedAttemptCount:r.length,reason:`${i.status}:${i.reason??"canonical domain action did not complete"}`,authorizedByContextReceipt:e.contextHash,authorizedAt:Date.now()};return this.persistDegradation(e,s),{permissionDecision:"allow",additionalContext:`DevFlow canonical tool mcp__devflow__${n.tool} ${i.status}; degraded direct write authorized by context receipt ${e.contextHash}. Preserve the action contract and verification plan.`}}return {permissionDecision:"deny",reasonCode:"DEVFLOW_REQUIRED_ACTION",reason:`DevFlow required action not completed. Call mcp__devflow__${n.tool} using context receipt ${e.contextHash}, then retry the write. Direct fallback is allowed only after unavailable, failed, or timeout evidence.`}}persistDegradation(e,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let r=o.getContextReceipt(e.projectRoot,e.sessionId,e.executionId);if(!r||r.contextHash!==e.contextHash||r.actionDegradation)return;o.upsertContextReceipt({...r,actionDegradation:n});let i=o.getSkillExecution(e.executionId);if(!i)return;let s=i.metadata&&typeof i.metadata=="object"?i.metadata:{},a=Array.isArray(s.requiredActionDegradations)?s.requiredActionDegradations:[];o.updateSkillExecution(e.executionId,{missedMcpTools:[...new Set([...i.missedMcpTools??[],n.missedTool])],failedToolCalls:Math.max(i.failedToolCalls??0,n.failedAttemptCount),fallbackCount:(i.fallbackCount??0)+1,fallbackReasons:[...new Set([...i.fallbackReasons??[],`required_action_${n.reason}`])],metadata:{...s,requiredActionDegradations:[...a,n]}});}catch{}finally{try{o?.close();}catch{}}}};var Ss=10,xs=5e3,Es=3e4,Ts=new Int32Array(new SharedArrayBuffer(4)),Zn=0;function As(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.rootPath=="string"&&e.rootPath.length>0&&typeof e.projectHash=="string"&&e.projectHash.length>0&&typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.startedAt=="number"&&Number.isFinite(e.startedAt)&&e.startedAt>=0}function eo(t){if(!existsSync(t))return {entries:[],needsRepair:false};try{let e=JSON.parse(readFileSync$1(t,"utf8"));if(!Array.isArray(e))return {entries:[],needsRepair:!0};let n=e.filter(As);return {entries:n,needsRepair:n.length!==e.length}}catch{return {entries:[],needsRepair:true}}}function to(t,e){mkdirSync$1(dirname$1(t),{recursive:true});let n=`${t}.${process.pid}.${Date.now()}.${Zn++}.tmp`,o;try{o=openSync$1(n,"wx"),writeFileSync$1(o,JSON.stringify(e,null,2)),closeSync$1(o),o=void 0,renameSync(n,t);}finally{try{o!==void 0&&closeSync$1(o);}finally{rmSync$1(n,{force:true});}}}function no(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function oo(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)&&typeof e.token=="string"&&e.token.length>0}function Kn(t,e){try{return readFileSync$1(t,"utf8")!==e?!1:(rmSync$1(t),!0)}catch(n){return n.code==="ENOENT"}}function Cs(t){try{let e=readFileSync$1(t,"utf8"),n;try{let r=JSON.parse(e);oo(r)&&(n=r);}catch{}return n?no(n.pid)?!1:Kn(t,e):Date.now()-statSync(t).mtimeMs>Es&&Kn(t,e)}catch(e){return e.code==="ENOENT"}}function Ds(t){mkdirSync$1(dirname$1(t),{recursive:true});let e=`${t}.lock`,n=Date.now()+xs;for(;;){let o=`${process.pid}:${Date.now()}:${Zn++}`,r;try{return r=openSync$1(e,"wx"),writeFileSync$1(r,JSON.stringify({pid:process.pid,createdAt:Date.now(),token:o})),closeSync$1(r),r=void 0,{path:e,token:o}}catch(i){if(r!==void 0)try{closeSync$1(r);}finally{rmSync$1(e,{force:true});}if(i.code!=="EEXIST")throw i}if(!Cs(e)){if(Date.now()>=n)throw new Error(`Timed out acquiring daemon registry lock: ${e}`);Atomics.wait(Ts,0,0,Ss);}}}function Ms(t){try{let e=readFileSync$1(t.path,"utf8"),n=JSON.parse(e);oo(n)&&n.token===t.token&&rmSync$1(t.path);}catch(e){if(e.code!=="ENOENT")throw e}}function ro(t){let e=getDaemonRegistryPath(),n=Ds(e);try{return t(e)}finally{Ms(n);}}function io(t,e){ro(n=>{let o=eo(n).entries.filter(r=>r.rootPath!==t&&no(r.pid));o.push({rootPath:t,projectHash:getProjectHash(t),pid:e,startedAt:Date.now()}),to(n,o);});}function so(t,e){ro(n=>{let o=eo(n).entries.filter(r=>r.rootPath!==t||e!==void 0&&r.pid!==e);to(n,o);});}async function ge(t){let e=!t.memory,n=t.memory??new MemoryGate(t.projectRoot),o=0,r=0;try{await n.forceWarmUp(),t.trigger==="session_end"&&(o=await n.releasePendingDistillLeases(t.sessionId)),r=n.getPendingEventCount(t.sessionId,t.trigger!=="session_end");}finally{e&&n.close();}let i=Date.now(),s=t.trigger==="session_end"&&t.sessionId?`distill:session_end:${createHash("sha256").update(`${t.projectRoot}\0${t.sessionId}`).digest("hex").slice(0,24)}`:`distill:${i}:${Math.random().toString(36).slice(2,10)}`,a={id:s,pendingEvents:r,releasedLeases:o,trigger:t.trigger,sessionId:t.sessionId,details:t.details};try{let c=openGlobalDevFlowDatabase();try{c.recordMemoryDistillCheckpoint({id:s,projectRoot:t.projectRoot,sessionId:t.sessionId,trigger:t.trigger,pendingEvents:r,releasedLeases:o,details:t.details,createdAt:i}),c.insertEvent({kind:"memory_distill_requested",timestamp:i,success:!0,metadata:{...a,projectRoot:t.projectRoot}});}finally{c.close();}}catch(c){if(t.strictPersistence)throw c}return a}function ao(t){if(t.pendingEvents===0)return "";let e=t.sessionId?`\uFF0CsessionId=${t.sessionId}`:"";return `Memory distill checkpoint: ${t.pendingEvents} \u4E2A\u4E8B\u4EF6\u5F85\u63D0\u70BC${e}\u3002\u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210\u540E\uFF0C\u8C03\u7528 mcp__devflow__memory_request_distill\uFF1B\u6309\u8FD4\u56DE\u7684 nextPage \u5206\u9875\u8BFB\u53D6\u5168\u90E8\u4E8B\u4EF6\uFF0C\u63D0\u70BC observations\uFF0C\u518D\u8C03\u7528 mcp__devflow__memory_save_distilled \u5E76\u786E\u8BA4\u4FDD\u5B58\u7ED3\u679C\u3002`}function mo(t){return Buffer.from(t,"utf8").toString("base64url")}function Ls(t,e,n){let o=e?.trim();if(o){let r=/^[a-zA-Z0-9:._-]{1,192}$/.test(o)?o:`tool-${createHash$1("sha256").update(o.slice(0,1024)).digest("hex").slice(0,32)}`;return `${t}:${r}`}return `${t}:legacy-${n}-${randomUUID().slice(0,8)}`}function vo(t){return `${t}:legacy-journal`}var q=class{constructor(e){this.projectRoot=e;this.sessions=new Map;this.sessionsDir=join$1(P(e),"hook-sessions");}registerSession(e){let n=e.trim();if(!n)throw new Error("session_id_required");let o=this.get(n);if(o)return o.lastActivityAt=Date.now(),this.persist(o),o;let r=Date.now(),i={sessionId:n,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:r,lastActivityAt:r};return this.sessions.set(n,i),this.persist(i),i}startExecution(e,n,o){let r=this.registerSession(e);return (!r.executionId||r.skillName!==n)&&(r.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),r.skillName=n,r.requiredMcpTools=[...new Set(o)],r.lastActivityAt=Date.now(),this.persist(r),r}bindTaskIdentity(e,n){let o=this.registerSession(e);return o.activeTurnId=n.turnId,o.activeRequestId=n.requestId,o.intentArtifactHash=n.intentArtifactHash,o.lastActivityAt=Date.now(),this.persist(o),o}get(e){let n=e.trim();if(!n)return null;let o=this.sessions.get(n);if(o)return this.replayEvidenceJournal(o),o;let r=this.snapshotPath(n);if(!existsSync$1(r))return null;try{let i=JSON.parse(readFileSync(r,"utf8"));return i.sessionId!==n||i.projectRoot!==this.projectRoot?null:(i.requiredMcpTools=Array.isArray(i.requiredMcpTools)?i.requiredMcpTools:[],i.evidenceObligations=po(i.evidenceObligations),i.evidenceDegradations=fo(i.evidenceDegradations),i.evidenceOutcomes=go(i.evidenceOutcomes),this.replayEvidenceJournal(i),this.sessions.set(n,i),i)}catch{return null}}completeExecution(e){let n=this.get(e);if(!n)return null;let o=structuredClone(n);return delete n.executionId,delete n.skillName,n.requiredMcpTools=[],n.lastActivityAt=Date.now(),this.persist(n),o}addEvidenceObligation(e,n,o=Date.now(),r){let i=this.registerSession(e),a=(r?void 0:i.evidenceObligations.find(d=>d.contractId===n.id))?.obligationId??Ls(n.id,r,o);this.appendEvidenceEvent(e,{kind:"add",obligationId:a,contractId:n.id,at:o,contract:n},`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(n=>structuredClone(n))}markEvidenceCorrection(e,n,o,r,i=Date.now()){let s=this.get(e),a=s?.evidenceObligations.find(u=>u.obligationId===n);if(!s||!a)return null;let c=/^[a-f0-9]{64}$/.test(r)?r:"";if(!c)return null;this.appendEvidenceEvent(e,{kind:"correction",obligationId:n,contractId:a.contractId,at:i,fingerprint:c,violations:o.slice(0,16).map(u=>u.slice(0,240))},`correction\0${n}\0${c}`),this.replayEvidenceJournal(s),s.lastActivityAt=i,this.persist(s);let d=s.evidenceObligations.find(u=>u.obligationId===n);return d?structuredClone(d):null}resolveEvidenceObligation(e,n){let o=this.get(e);if(!o)return false;let r=o.evidenceObligations.find(s=>s.obligationId===n);if(!r)return false;let i=Date.now();return this.appendEvidenceEvent(e,{kind:"resolve",obligationId:n,contractId:r.contractId,at:i},`resolve\0${n}`),this.replayEvidenceJournal(o),o.lastActivityAt=i,this.persist(o),true}resolveDegradedEvidence(e,n){let o=this.get(e),r=o?.evidenceDegradations.find(s=>s.obligationId===n);if(!o||!r)return false;let i=Date.now();return this.appendEvidenceEvent(e,{kind:"resolve",obligationId:n,contractId:r.contractId,at:i},`resolve-degraded\0${n}\0${i}`),this.replayEvidenceJournal(o),o.lastActivityAt=i,this.persist(o),true}degradeEvidenceObligation(e,n,o,r=Date.now()){let i=this.get(e),s=i?.evidenceObligations.find(c=>c.obligationId===n);if(!i||!s)return false;let a=o.slice(0,240);return this.appendEvidenceEvent(e,{kind:"degrade",obligationId:n,contractId:s.contractId,at:r,reason:a},`degrade\0${n}\0${a}`),this.replayEvidenceJournal(i),i.lastActivityAt=r,this.persist(i),true}removeSession(e){let n=e.trim();n&&(this.sessions.delete(n),rmSync(this.snapshotPath(n),{force:true}),rmSync(this.evidenceJournalDir(n),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(e){return join$1(this.sessionsDir,`${mo(e)}.json`)}evidenceJournalDir(e){return join$1(this.sessionsDir,"evidence-journal",mo(e))}appendEvidenceEvent(e,n,o){let r=this.evidenceJournalDir(e);mkdirSync(r,{recursive:true,mode:448});let i=createHash$1("sha256").update(o).digest("hex"),s=join$1(r,`${n.kind}-${i}.json`);if(existsSync$1(s))return;let a=join$1(r,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync(a,JSON.stringify(n),{mode:384});try{linkSync(a,s);}catch(c){if(c.code!=="EEXIST")throw c}finally{rmSync(a,{force:true});}}replayEvidenceJournal(e){e.evidenceObligations=po(e.evidenceObligations),e.evidenceDegradations=fo(e.evidenceDegradations),e.evidenceOutcomes=go(e.evidenceOutcomes);let n=this.evidenceJournalDir(e.sessionId);if(!existsSync$1(n))return;let o;try{o=readdirSync(n).filter(i=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(i)).slice(0,4096);}catch{return}let r=o.flatMap(i=>{try{let s=readFileSync(join$1(n,i),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=Ns(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||ho(i.kind)-ho(s.kind));for(let i of r)this.applyEvidenceEvent(e,i);e.evidenceObligations=e.evidenceObligations.slice(-8),e.evidenceDegradations=e.evidenceDegradations.slice(-20),e.evidenceOutcomes=e.evidenceOutcomes.slice(-20);}applyEvidenceEvent(e,n){let o=e.evidenceOutcomes.find(s=>s.obligationId===n.obligationId);if(n.kind==="add"){if(o)return;let s=e.evidenceObligations.find(a=>a.obligationId===n.obligationId);s?(s.contract=n.contract,s.promptedAt=Math.min(s.promptedAt,n.at)):e.evidenceObligations.push({obligationId:n.obligationId,contractId:n.contractId,contract:n.contract,promptedAt:n.at,attempt:0,correctionRequested:false,violations:[]});return}let r=e.evidenceObligations.find(s=>s.obligationId===n.obligationId);if(n.kind==="correction"){if(!r||o||r.correctionFingerprint===n.fingerprint)return;r.attempt+=1,r.correctionRequested=true,r.correctionRequestedAt=n.at,r.correctionFingerprint=n.fingerprint,r.violations=n.violations;return}let i=r?.attempt??o?.attempt??0;if(n.kind==="resolve"&&o?.status==="degraded")e.evidenceOutcomes=e.evidenceOutcomes.filter(s=>s.obligationId!==n.obligationId),e.evidenceDegradations=e.evidenceDegradations.filter(s=>s.obligationId!==n.obligationId);else if(o)return;n.kind==="degrade"?(e.evidenceObligations=e.evidenceObligations.filter(s=>s.obligationId!==n.obligationId),e.evidenceDegradations.push({obligationId:n.obligationId,contractId:n.contractId,reason:n.reason,degradedAt:n.at,attempt:i,contract:r?.contract})):e.evidenceObligations=e.evidenceObligations.filter(s=>s.obligationId!==n.obligationId),e.evidenceOutcomes.push({obligationId:n.obligationId,contractId:n.contractId,status:n.kind==="resolve"?"resolved":"degraded",completedAt:n.at,attempt:i,...n.kind==="degrade"?{reason:n.reason}:{}});}persist(e){mkdirSync(this.sessionsDir,{recursive:true,mode:448});let n=this.snapshotPath(e.sessionId),o=`${n}.${process.pid}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(e),{mode:384}),renameSync$1(o,n);}};function po(t){return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!="object")return [];let n=e;if(typeof n.contractId!="string"||n.contractId.length===0||n.contractId.length>128||typeof n.promptedAt!="number"||typeof n.attempt!="number"||typeof n.correctionRequested!="boolean"||!Array.isArray(n.violations)||!_o(n.contract))return [];let o=typeof n.obligationId=="string"&&n.obligationId.length>0&&n.obligationId.length<=384?n.obligationId:vo(n.contractId),r=typeof n.correctionTranscriptHash=="string"?n.correctionTranscriptHash:void 0,i=n.correctionFingerprint??r;return i!==void 0&&!/^[a-f0-9]{64}$/.test(i)?[]:[{...n,obligationId:o,correctionFingerprint:i}]}).slice(-8):[]}function fo(t){return Array.isArray(t)?t.filter(e=>{if(!e||typeof e!="object")return false;let n=e;return typeof n.obligationId=="string"&&typeof n.contractId=="string"&&typeof n.reason=="string"&&typeof n.degradedAt=="number"&&typeof n.attempt=="number"}).slice(-20):[]}function go(t){return Array.isArray(t)?t.filter(e=>{if(!e||typeof e!="object")return false;let n=e;return typeof n.obligationId=="string"&&typeof n.contractId=="string"&&(n.status==="resolved"||n.status==="degraded")&&typeof n.completedAt=="number"&&typeof n.attempt=="number"&&(n.reason===void 0||typeof n.reason=="string")}).slice(-20):[]}function Ns(t){if(!t||typeof t!="object")return null;let e=t,n=e.kind;if(n!=="add"&&n!=="correction"&&n!=="resolve"&&n!=="degrade"||typeof e.contractId!="string"||e.contractId.length>128||typeof e.at!="number")return null;let r={obligationId:typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:vo(e.contractId),contractId:e.contractId,at:e.at};if(n==="add")return _o(e.contract)?{kind:n,...r,contract:e.contract}:null;if(n==="correction"){let i=typeof e.fingerprint=="string"?e.fingerprint:e.transcriptHash;return typeof i=="string"&&/^[a-f0-9]{64}$/.test(i)&&Array.isArray(e.violations)&&e.violations.every(s=>typeof s=="string"&&s.length<=240)?{kind:n,...r,fingerprint:i,violations:e.violations}:null}return n==="resolve"?{kind:n,...r}:typeof e.reason=="string"&&e.reason.length<=240?{kind:n,...r,reason:e.reason}:null}function ho(t){return t==="add"?0:t==="correction"?1:2}function _o(t){if(!t||typeof t!="object")return false;let e=t,n=e.requiredSections,o=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(n)&&n.length===3&&n[0]==="\u5DE5\u5177\u53D1\u73B0"&&n[1]==="\u6A21\u578B\u5047\u8BBE"&&n[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(o)&&o.length<=16&&o.every(r=>typeof r=="string"&&r.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 ko(t,e){let n=xo(t);mkdirSync$1(n,{recursive:true,mode:448});let o=join(n,`${e.receiptId}.json`);if(existsSync(o))return e.receiptId;let r=`${o}.${process.pid}.tmp`;writeFileSync$1(r,JSON.stringify(e),{mode:384});try{renameSync(r,o);}catch(i){try{unlinkSync$1(r);}catch{}if(!existsSync(o))throw i}return e.receiptId}function bo(t){let e=xo(t);mkdirSync$1(e,{recursive:true,mode:448});let n=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(e,n),r=/\.json\.claim-\d+$/u.test(n),i=r?o:`${o}.claim-${process.pid}`;if(!r)try{renameSync(o,i);}catch{return null}try{let s=JSON.parse(readFileSync$1(i,"utf8"));if(typeof s.receiptId!="string"||typeof s.inputJson!="string"||typeof s.sessionId!="string"||typeof s.cleanupSharedState!="boolean")throw unlinkSync$1(i),new Error("session_finalize_spool_payload_invalid");return {receiptId:basename(n).replace(/\.json(?:\.claim-\d+)?$/u,""),payload:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function Ro(t){unlinkSync$1(t.path);}function So(t){try{renameSync(t.path,t.path.replace(/\.claim-\d+$/u,""));}catch{}}function xo(t){return join(P(t),"session-finalize-pending")}function C(t){let{projectRoot:e,...n}=t;try{return new St(e).dispatchBoundary(n).snapshot??null}catch(o){return y({event:"hook.runtime.degraded",identity:{projectRoot:e,sessionId:t.sessionId,...t.turnId?{turnId:t.turnId}:{},...t.requestId?{requestId:t.requestId}:{},...t.executionId?{executionId:t.executionId}:{}},level:"error",timestamp:Date.now(),data:{stage:t.kind,reason:o instanceof Error?o.message:String(o),tool:t.producer}}),null}}var St=class{constructor(e){this.projectRoot=e;}dispatchBoundary(e){let n=Gs(e.kind,e.payload??{});if(!n)return {handled:false};let o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let r=Ks(o,{projectRoot:this.projectRoot,sessionId:e.sessionId,...e.turnId?{turnId:e.turnId}:{},...e.requestId?{requestId:e.requestId}:{},...e.executionId?{executionId:e.executionId}:{}});return r?{handled:!0,snapshot:new TaskKernel(new TaskEventStore(o),new SemanticRuntimeEventProjector).dispatch({definition:r.definition,kind:n.kind,payload:n.payload,idempotencyKey:`host:${r.definition.definitionHash}:${e.dedupeKey}`,producer:e.producer}).snapshot}:{handled:!1}}finally{o.close();}}};function Ks(t,e){let n=e.executionId?t.getActiveContextReceipt(e.projectRoot,e.sessionId,e.executionId):null,o=e.turnId??n?.canonicalAction?.binding.turnId,r=e.requestId??n?.requestId;if(!o&&!r)return null;let i=t.listLatestTaskIntentArtifacts(e.projectRoot,e.sessionId).find(s=>o?s.turnId===o:s.requestId===r);if(!i)return null;for(let s of [...new Set([i.version,2,1])]){let a=t.getTaskAggregateSnapshot(e.projectRoot,e.sessionId,i.turnId,s);if(!a)continue;let c=t.getTaskDefinitionV2(a.taskDefinitionHash);if(c)return {definition:c,snapshot:a}}return null}function Gs(t,e){switch(t){case "action.lease.issued":return {kind:"action_lease_issued",payload:e};case "action.succeeded":return {kind:"action_completed",payload:e};case "action.failed":return {kind:"action_failed",payload:e};case "verification.succeeded":return {kind:"verification_completed",payload:e};case "verification.failed":return {kind:"verification_failed",payload:e};case "memory.committed":return {kind:"memory_episode_persisted",payload:e};case "memory.skipped":return {kind:"memory_decision_completed",payload:e};case "memory.pending":return {kind:"memory_extraction_queued",payload:e};case "memory.failed":return {kind:"memory_extraction_failed",payload:e};case "durable_work.owned":return {kind:"durable_work_leased",payload:{...e,fencingToken:Number.isSafeInteger(e.fencingToken)?e.fencingToken:0}};case "durable_work.completed":return {kind:"durable_work_completed",payload:e};case "durable_work.dead_lettered":return {kind:"durable_work_dead_lettered",payload:e};default:return null}}var na=256*1024,oa=48*1024,ra=512*1024,ia=500,sa=5,he=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function aa(t){return t==="react_audit_performance"||t.endsWith("__react_audit_performance")}function ca(t){let e=ye(t,0,new Set);return e?_a(e.contract,e.canonicalReport):null}function Co(t){if(!t.sessionId||!aa(t.toolName))return null;let e=ca(t.toolResponse);if(!e)return null;let n=Date.now(),o=t.runtimeStore.addEvidenceObligation(t.sessionId,e,n,t.toolUseId),r=t.runtimeStore.get(t.sessionId);if(o&&r){let i=openGlobalDevFlowDatabase();try{i.upsertSessionObligation({obligationId:`evidence:${o.obligationId}`,projectRoot:r.projectRoot,sessionId:t.sessionId,executionId:r.executionId,kind:"evidence_contract",state:"open",payload:{contract:e,runtimeObligationId:o.obligationId},createdAt:n,updatedAt:n});}finally{i.close();}y({event:"verification.completed",identity:{projectRoot:r.projectRoot,sessionId:t.sessionId,executionId:r.executionId},level:"info",timestamp:n,data:{stage:"performance_detector_coverage",status:"obligation_opened",contractId:e.id,obligationId:o.obligationId,detectorCoverage:ze(t.toolResponse),runtimeProfilingOccurred:e.runtimeProfilingOccurred,samplingEvidenceOccurred:e.samplingEvidenceOccurred,toolUseId:t.toolUseId}});}return da(e)}function da(t){return [`DevFlow performance evidence contract ${t.id} is active.`,`The final performance answer MUST contain these three sections exactly: ${t.requiredSections.join(" / ")}.`,t.runtimeProfilingOccurred?"Only claims directly supported by the returned runtime measurements may be stated as measured facts.":"No runtime profiling occurred. Treat every finding as a static candidate: do not assign P0/high-risk severity, claim a confirmed bottleneck/jank/frame drop/CPU hotspot, quantify performance or benefit, or recommend requestAnimationFrame as generic throttling without sampling evidence.",`samplingEvidenceOccurred=${t.samplingEvidenceOccurred}. RAF recommendations are permitted only when this structured contract field is true; answer text cannot self-declare sampling evidence.`,"Use the canonical report below directly or preserve its evidence boundaries. Stop will request one correction for unsupported claims, then fail open with degradation telemetry.",t.canonicalReport].join(`
4
+ `)}function Xi(t,e){return {candidateId:t.id,version:t.overlayVersion,state:e,instruction:t.instruction,trigger:t.trigger,confidence:t.confidence,evidenceReceipt:t.graderReceipt??`candidate:${t.id}:v${t.overlayVersion}`,expiresAt:t.expiresAt}}function Qi(t,e){let n=Math.max(0,Math.min(e.maxLearnedEntries??3,3)),o=Math.max(0,Math.min(e.learnedCharacterBudget??1600,4e3)),r=[],i=0;for(let s of t){if(r.length>=n)break;let a=s.instruction.length+4;i+a>o||(r.push(s),i+=a);}return r}function Zi(t,e,n){let o=t.trigger,r=e.replace(/^devflow:/,"").split(":").pop()??e,i=Pe(o.skills);if(i.length>0&&!i.some(m=>m===e||m===r||m.endsWith(`:${r}`)))return false;let s=(n.prompt??"").normalize("NFKC").toLocaleLowerCase("en-US"),a=(n.command??"").normalize("NFKC").toLocaleLowerCase("en-US"),c=[...n.files??[],...es(n.prompt??"")].map(m=>m.replaceAll("\\","/").toLocaleLowerCase("en-US")),d=Pe(o.commands).map(Ln);if(d.length>0&&!d.some(m=>a.includes(m)||s.includes(m)))return false;let u=Pe(o.entities).map(Ln);if(u.length>0&&!u.some(m=>s.includes(m)||a.includes(m)))return false;let l=Pe(o.files).map(m=>m.replaceAll("\\","/").toLocaleLowerCase("en-US"));return !(l.length>0&&!l.some(m=>c.some(f=>ts(f,m))))}function es(t){return t.match(/(?:^|\s)((?:src|app|apps|packages|plugins|lib|test|tests)\/[A-Za-z0-9_./@-]+)/gu)?.map(e=>e.trim())??[]}function ts(t,e){if(!e.includes("*"))return t===e||t.includes(e);let n=e.replace(/[.+?^${}()|[\]\\]/gu,"\\$&").replaceAll("*",".*");return new RegExp(`^${n}$`,"u").test(t)}function Pe(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.trim().length>0):[]}function Ln(t){return t.normalize("NFKC").trim().toLocaleLowerCase("en-US")}function Nn(t){if(!existsSync(t))return null;try{let e=JSON.parse(readFileSync$1(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function ns(t,e){for(let n of ["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let o=t?.[n];if(!o||typeof o!="object"||Array.isArray(o))continue;let r=o[e];if(typeof r=="string"&&r.trim())return r.trim()}}function os(t,e){let n=t?.packages;if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n[`node_modules/${e}`];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.version;if(typeof i=="string"&&i.trim())return i.trim()}}let o=t?.dependencies;if(o&&typeof o=="object"&&!Array.isArray(o)){let r=o[e];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.version;if(typeof i=="string"&&i.trim())return i.trim()}}}function Un(t){let e=$n();return e?e[t]?.mcpTools??[]:[]}function zn(t,e,n){return Wn(qn(t,e,{prompt:n}))}var ht=getDevFlowStateRoot(),yt=join$1(ht,"server-refs.json"),ms=600*1e3,ps=500;function fs(){existsSync$1(ht)||mkdirSync(ht,{recursive:true});}function je(){try{if(existsSync$1(yt))return JSON.parse(readFileSync(yt,"utf-8"))}catch{}return {sessions:[],lastActivity:0}}function Bn(t){fs(),writeFileSync(yt,JSON.stringify(t));}var $e=class{constructor(e){this.process=null;this.idleTimer=null;this.onShutdown=null;this.ownerToken=null;this.projectRoot=e;}setOnShutdown(e){this.onShutdown=e;}addRef(e){let n=je();n.sessions.includes(e)||n.sessions.push(e),n.lastActivity=Date.now(),Bn(n),this.resetIdleTimer();}removeRef(e){let n=je();n.sessions=n.sessions.filter(o=>o!==e),n.lastActivity=Date.now(),Bn(n),n.sessions.length===0&&this.resetIdleTimer();}get activeSessions(){return je().sessions.length}async ensureRunning(){return await this.healthCheck()?true:(await this.startServer(),this.waitForReady())}get isRunning(){return this.process!==null&&!this.process.killed}async stop(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.process){this.process.kill("SIGTERM"),await new Promise(n=>{let o=setTimeout(()=>{this.process&&!this.process.killed&&this.process.kill("SIGKILL"),n();},5e3);this.process?this.process.on("exit",()=>{clearTimeout(o),n();}):(clearTimeout(o),n());}),this.process=null;let e=readRuntimeEndpointState();e&&e.ownerToken===this.ownerToken&&updateRuntimeEndpointStatus("stopped");}}async startServer(){let e=gs(this.projectRoot);this.ownerToken=randomUUID$1();let n=resolveRuntimeEndpoint();this.process=spawn(process.execPath,[e,"--devflow-instance-token",this.ownerToken],{cwd:this.projectRoot,env:{...process.env,NODE_ENV:process.env.NODE_ENV||"development"},stdio:["ignore","pipe","pipe"]}),writeRuntimeEndpointState({url:n.url,port:n.port,pid:this.process.pid??0,ownerToken:this.ownerToken,status:"launching"}),this.process.stdout?.on("data",o=>{}),this.process.stderr?.on("data",o=>{}),this.process.on("exit",o=>{let r=readRuntimeEndpointState();r&&r.ownerToken===this.ownerToken&&updateRuntimeEndpointStatus("stopped"),this.process=null,this.onShutdown&&this.onShutdown();}),this.process.on("error",()=>{let o=readRuntimeEndpointState();o&&o.ownerToken===this.ownerToken&&updateRuntimeEndpointStatus("degraded"),this.process=null;});}async waitForReady(){let e=Date.now()+3e4;for(;Date.now()<e;){if(await this.healthCheck())return true;await new Promise(n=>setTimeout(n,ps));}return false}healthCheck(){return new Promise(e=>{let n=resolveRuntimeEndpoint(),o=new URL("/api/health",n.url),r=request({hostname:o.hostname,port:o.port,path:o.pathname,method:"GET",timeout:2e3},i=>{let s=i.statusCode===200;s&&readRuntimeEndpointState()&&updateRuntimeEndpointStatus("healthy"),i.resume(),e(s);});r.on("error",()=>e(false)),r.on("timeout",()=>{r.destroy(),e(false);}),r.end();})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),!(je().sessions.length>0)&&(this.idleTimer=setTimeout(()=>{this.stop();},ms).unref());}};function gs(t){let e=createRequire(import.meta.url),n=[()=>e.resolve("@devflow-tools/server/dist/main.js"),()=>join$1(t,"node_modules","@devflow-tools","server","dist","main.js"),()=>join$1(t,"apps","server","dist","main.js")];for(let o of n)try{let r=o();if(existsSync$1(r))return r}catch{}throw new Error("DevFlow server entry point is not installed or built")}function _t(t){if(!t||typeof t!="object"||Array.isArray(t))return {};let e=t,n={};for(let o of ["lastMcpCall","bypassCount"])if(o in e){let r=e[o];if(r==null)continue;n[o]=typeof r=="number"&&Number.isFinite(r)&&r>=0?r:0;}return n}function hs(t,e){return t.lastMcpCall===e.lastMcpCall&&t.bypassCount===e.bypassCount}function ys(t,e,n){let o=n instanceof Error?n.message:String(n);y({event:"hook.runtime.degraded",identity:{projectRoot:t},level:"warn",timestamp:Date.now(),data:{stage:"enforcement_receipt",operation:e,reason:o,fallback:"fail_open"}});}function Vn(t,e,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let r={},i=o.updateHookReceipt(t,a=>(r=_t(a),_t(e(r)))),s=_t(i);return {receipt:s,applied:!0,changed:!hs(r,s)}}catch(r){return ys(t,n,r),{receipt:{},applied:false,changed:false}}finally{try{o?.close();}catch{}}}function Fe(t,e){return Vn(t,()=>e,"write").applied}function It(t,e){return Vn(t,e,"update")}var Jn={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},vs=new Set(["Write","Edit","NotebookEdit"]),_s=new Set(["failed","timeout","unavailable"]);function Is(t){switch(t){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var ee=class{constructor(e,n,o){this.projectRoot=e;this.sessionId=n;this.executionId=o;}getPhase(){if(!this.sessionId||!this.executionId)return "idle";let e;try{e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let n=e.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(n&&n.expiresAt>Date.now())return "context_ready";n&&e.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId);}catch{}finally{try{e?.close();}catch{}}return "context_gathering"}getContextReceipt(){if(!this.sessionId||!this.executionId)return null;let e;try{e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let n=e.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);return n&&n.expiresAt>Date.now()?n:(n&&e.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId),null)}catch{return null}finally{try{e?.close();}catch{}}}evaluate(e,n){let o=this.getPhase();if(n||e==="Skill")return {permissionDecision:"allow"};if(o==="context_gathering"&&Jn[e])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_REQUIRED",reason:`DevFlow context required. Call mcp__devflow__get_project_context, then retry ${e}.`};if(o==="context_ready"){if(vs.has(e)){let c=this.evaluateRequiredAction();if(c)return c}return {permissionDecision:"allow"}}let r=Jn[e];if(!r)return {permissionDecision:"allow"};let i=It(this.projectRoot,c=>({...c,bypassCount:(c.bypassCount??0)+1}));if(!i.applied)return {permissionDecision:"allow"};let s=i.receipt.bypassCount??0,a=Is(e);return s>=a?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \u6B21\u76F4\u63A5\u4F7F\u7528 ${e}\uFF0C\u5EFA\u8BAE\u7528 mcp__devflow__${r} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){Fe(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}recordDomainActionOutcome(e,n,o,r){if(!this.sessionId||!this.executionId)return false;let i;try{i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let s=i.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(!s||s.expiresAt<=Date.now()||s.canonicalAction?.tool!==e)return !1;let a=Date.now(),c=r?.trim()?`${r.trim()}:${n}`:`${e}:${n}:${a}`,d=s.actionAttempts??[];return i.upsertContextReceipt({...s,actionAttempts:d.some(u=>u.id===c||r&&u.toolUseId===r&&u.status===n)?d:[...d,{id:c,tool:e,status:n,attemptedAt:a,toolUseId:r,reason:o?.slice(0,500)}].slice(-20),actionSatisfiedAt:n==="succeeded"?a:s.actionSatisfiedAt,actionDegradation:n==="succeeded"?void 0:s.actionDegradation}),!0}catch{return false}finally{try{i?.close();}catch{}}}evaluateRequiredAction(){let e=this.getContextReceipt(),n=e?.canonicalAction;if(!e||!n||!n.required||n.status!=="required")return null;let o=n.binding;if(o.requiredContextReceipt!==e.contextHash||o.projectRoot!==this.projectRoot||o.sessionId!==this.sessionId||o.requestId!==e.requestId||o.executionId&&o.executionId!==this.executionId)return {permissionDecision:"deny",reasonCode:"DEVFLOW_ACTION_BINDING_STALE",reason:"DevFlow canonical action binding is stale or mismatched. Call mcp__devflow__get_project_context again before writing."};if(e.actionSatisfiedAt)return null;if(e.actionDegradation?.authorizedByContextReceipt===e.contextHash)return {permissionDecision:"allow",additionalContext:`DevFlow degraded fallback authorized by context receipt ${e.contextHash}: ${e.actionDegradation.reason}`};let r=(e.actionAttempts??[]).filter(i=>i.tool===n.tool&&_s.has(i.status));if(r.length>0){let i=r.at(-1),s={missedTool:n.tool,failedAttemptCount:r.length,reason:`${i.status}:${i.reason??"canonical domain action did not complete"}`,authorizedByContextReceipt:e.contextHash,authorizedAt:Date.now()};return this.persistDegradation(e,s),{permissionDecision:"allow",additionalContext:`DevFlow canonical tool mcp__devflow__${n.tool} ${i.status}; degraded direct write authorized by context receipt ${e.contextHash}. Preserve the action contract and verification plan.`}}return {permissionDecision:"deny",reasonCode:"DEVFLOW_REQUIRED_ACTION",reason:`DevFlow required action not completed. Call mcp__devflow__${n.tool} using context receipt ${e.contextHash}, then retry the write. Direct fallback is allowed only after unavailable, failed, or timeout evidence.`}}persistDegradation(e,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let r=o.getContextReceipt(e.projectRoot,e.sessionId,e.executionId);if(!r||r.contextHash!==e.contextHash||r.actionDegradation)return;o.upsertContextReceipt({...r,actionDegradation:n});let i=o.getSkillExecution(e.executionId);if(!i)return;let s=i.metadata&&typeof i.metadata=="object"?i.metadata:{},a=Array.isArray(s.requiredActionDegradations)?s.requiredActionDegradations:[];o.updateSkillExecution(e.executionId,{missedMcpTools:[...new Set([...i.missedMcpTools??[],n.missedTool])],failedToolCalls:Math.max(i.failedToolCalls??0,n.failedAttemptCount),fallbackCount:(i.fallbackCount??0)+1,fallbackReasons:[...new Set([...i.fallbackReasons??[],`required_action_${n.reason}`])],metadata:{...s,requiredActionDegradations:[...a,n]}});}catch{}finally{try{o?.close();}catch{}}}};var xs=10,Es=5e3,Ts=3e4,As=new Int32Array(new SharedArrayBuffer(4)),Zn=0;function Cs(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.rootPath=="string"&&e.rootPath.length>0&&typeof e.projectHash=="string"&&e.projectHash.length>0&&typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.startedAt=="number"&&Number.isFinite(e.startedAt)&&e.startedAt>=0}function eo(t){if(!existsSync(t))return {entries:[],needsRepair:false};try{let e=JSON.parse(readFileSync$1(t,"utf8"));if(!Array.isArray(e))return {entries:[],needsRepair:!0};let n=e.filter(Cs);return {entries:n,needsRepair:n.length!==e.length}}catch{return {entries:[],needsRepair:true}}}function to(t,e){mkdirSync$1(dirname$1(t),{recursive:true});let n=`${t}.${process.pid}.${Date.now()}.${Zn++}.tmp`,o;try{o=openSync$1(n,"wx"),writeFileSync$1(o,JSON.stringify(e,null,2)),closeSync$1(o),o=void 0,renameSync(n,t);}finally{try{o!==void 0&&closeSync$1(o);}finally{rmSync$1(n,{force:true});}}}function no(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function oo(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)&&typeof e.token=="string"&&e.token.length>0}function Kn(t,e){try{return readFileSync$1(t,"utf8")!==e?!1:(rmSync$1(t),!0)}catch(n){return n.code==="ENOENT"}}function Ds(t){try{let e=readFileSync$1(t,"utf8"),n;try{let r=JSON.parse(e);oo(r)&&(n=r);}catch{}return n?no(n.pid)?!1:Kn(t,e):Date.now()-statSync(t).mtimeMs>Ts&&Kn(t,e)}catch(e){return e.code==="ENOENT"}}function Ms(t){mkdirSync$1(dirname$1(t),{recursive:true});let e=`${t}.lock`,n=Date.now()+Es;for(;;){let o=`${process.pid}:${Date.now()}:${Zn++}`,r;try{return r=openSync$1(e,"wx"),writeFileSync$1(r,JSON.stringify({pid:process.pid,createdAt:Date.now(),token:o})),closeSync$1(r),r=void 0,{path:e,token:o}}catch(i){if(r!==void 0)try{closeSync$1(r);}finally{rmSync$1(e,{force:true});}if(i.code!=="EEXIST")throw i}if(!Ds(e)){if(Date.now()>=n)throw new Error(`Timed out acquiring daemon registry lock: ${e}`);Atomics.wait(As,0,0,xs);}}}function Os(t){try{let e=readFileSync$1(t.path,"utf8"),n=JSON.parse(e);oo(n)&&n.token===t.token&&rmSync$1(t.path);}catch(e){if(e.code!=="ENOENT")throw e}}function ro(t){let e=getDaemonRegistryPath(),n=Ms(e);try{return t(e)}finally{Os(n);}}function io(t,e){ro(n=>{let o=eo(n).entries.filter(r=>r.rootPath!==t&&no(r.pid));o.push({rootPath:t,projectHash:getProjectHash(t),pid:e,startedAt:Date.now()}),to(n,o);});}function so(t,e){ro(n=>{let o=eo(n).entries.filter(r=>r.rootPath!==t||e!==void 0&&r.pid!==e);to(n,o);});}async function ge(t){let e=!t.memory,n=t.memory??new MemoryGate(t.projectRoot),o=0,r=0;try{await n.forceWarmUp(),t.trigger==="session_end"&&(o=await n.releasePendingDistillLeases(t.sessionId)),r=n.getPendingEventCount(t.sessionId,t.trigger!=="session_end");}finally{e&&n.close();}let i=Date.now(),s=t.trigger==="session_end"&&t.sessionId?`distill:session_end:${createHash("sha256").update(`${t.projectRoot}\0${t.sessionId}`).digest("hex").slice(0,24)}`:`distill:${i}:${Math.random().toString(36).slice(2,10)}`,a={id:s,pendingEvents:r,releasedLeases:o,trigger:t.trigger,sessionId:t.sessionId,details:t.details};try{let c=openGlobalDevFlowDatabase();try{c.recordMemoryDistillCheckpoint({id:s,projectRoot:t.projectRoot,sessionId:t.sessionId,trigger:t.trigger,pendingEvents:r,releasedLeases:o,details:t.details,createdAt:i}),c.insertEvent({kind:"memory_distill_requested",timestamp:i,success:!0,metadata:{...a,projectRoot:t.projectRoot}});}finally{c.close();}}catch(c){if(t.strictPersistence)throw c}return a}function ao(t){if(t.pendingEvents===0)return "";let e=t.sessionId?`\uFF0CsessionId=${t.sessionId}`:"";return `Memory distill checkpoint: ${t.pendingEvents} \u4E2A\u4E8B\u4EF6\u5F85\u63D0\u70BC${e}\u3002\u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210\u540E\uFF0C\u8C03\u7528 mcp__devflow__memory_request_distill\uFF1B\u6309\u8FD4\u56DE\u7684 nextPage \u5206\u9875\u8BFB\u53D6\u5168\u90E8\u4E8B\u4EF6\uFF0C\u63D0\u70BC observations\uFF0C\u518D\u8C03\u7528 mcp__devflow__memory_save_distilled \u5E76\u786E\u8BA4\u4FDD\u5B58\u7ED3\u679C\u3002`}function mo(t){return Buffer.from(t,"utf8").toString("base64url")}function Ns(t,e,n){let o=e?.trim();if(o){let r=/^[a-zA-Z0-9:._-]{1,192}$/.test(o)?o:`tool-${createHash$1("sha256").update(o.slice(0,1024)).digest("hex").slice(0,32)}`;return `${t}:${r}`}return `${t}:legacy-${n}-${randomUUID().slice(0,8)}`}function vo(t){return `${t}:legacy-journal`}var q=class{constructor(e){this.projectRoot=e;this.sessions=new Map;this.sessionsDir=join$1(P(e),"hook-sessions");}registerSession(e){let n=e.trim();if(!n)throw new Error("session_id_required");let o=this.get(n);if(o)return o.lastActivityAt=Date.now(),this.persist(o),o;let r=Date.now(),i={sessionId:n,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:r,lastActivityAt:r};return this.sessions.set(n,i),this.persist(i),i}startExecution(e,n,o){let r=this.registerSession(e);return (!r.executionId||r.skillName!==n)&&(r.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),r.skillName=n,r.requiredMcpTools=[...new Set(o)],r.lastActivityAt=Date.now(),this.persist(r),r}bindTaskIdentity(e,n){let o=this.registerSession(e);return o.activeTurnId=n.turnId,o.activeRequestId=n.requestId,o.intentArtifactHash=n.intentArtifactHash,o.lastActivityAt=Date.now(),this.persist(o),o}get(e){let n=e.trim();if(!n)return null;let o=this.sessions.get(n);if(o)return this.replayEvidenceJournal(o),o;let r=this.snapshotPath(n);if(!existsSync$1(r))return null;try{let i=JSON.parse(readFileSync(r,"utf8"));return i.sessionId!==n||i.projectRoot!==this.projectRoot?null:(i.requiredMcpTools=Array.isArray(i.requiredMcpTools)?i.requiredMcpTools:[],i.evidenceObligations=po(i.evidenceObligations),i.evidenceDegradations=fo(i.evidenceDegradations),i.evidenceOutcomes=go(i.evidenceOutcomes),this.replayEvidenceJournal(i),this.sessions.set(n,i),i)}catch{return null}}completeExecution(e){let n=this.get(e);if(!n)return null;let o=structuredClone(n);return delete n.executionId,delete n.skillName,n.requiredMcpTools=[],n.lastActivityAt=Date.now(),this.persist(n),o}addEvidenceObligation(e,n,o=Date.now(),r){let i=this.registerSession(e),a=(r?void 0:i.evidenceObligations.find(d=>d.contractId===n.id))?.obligationId??Ns(n.id,r,o);this.appendEvidenceEvent(e,{kind:"add",obligationId:a,contractId:n.id,at:o,contract:n},`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(n=>structuredClone(n))}markEvidenceCorrection(e,n,o,r,i=Date.now()){let s=this.get(e),a=s?.evidenceObligations.find(u=>u.obligationId===n);if(!s||!a)return null;let c=/^[a-f0-9]{64}$/.test(r)?r:"";if(!c)return null;this.appendEvidenceEvent(e,{kind:"correction",obligationId:n,contractId:a.contractId,at:i,fingerprint:c,violations:o.slice(0,16).map(u=>u.slice(0,240))},`correction\0${n}\0${c}`),this.replayEvidenceJournal(s),s.lastActivityAt=i,this.persist(s);let d=s.evidenceObligations.find(u=>u.obligationId===n);return d?structuredClone(d):null}resolveEvidenceObligation(e,n){let o=this.get(e);if(!o)return false;let r=o.evidenceObligations.find(s=>s.obligationId===n);if(!r)return false;let i=Date.now();return this.appendEvidenceEvent(e,{kind:"resolve",obligationId:n,contractId:r.contractId,at:i},`resolve\0${n}`),this.replayEvidenceJournal(o),o.lastActivityAt=i,this.persist(o),true}resolveDegradedEvidence(e,n){let o=this.get(e),r=o?.evidenceDegradations.find(s=>s.obligationId===n);if(!o||!r)return false;let i=Date.now();return this.appendEvidenceEvent(e,{kind:"resolve",obligationId:n,contractId:r.contractId,at:i},`resolve-degraded\0${n}\0${i}`),this.replayEvidenceJournal(o),o.lastActivityAt=i,this.persist(o),true}degradeEvidenceObligation(e,n,o,r=Date.now()){let i=this.get(e),s=i?.evidenceObligations.find(c=>c.obligationId===n);if(!i||!s)return false;let a=o.slice(0,240);return this.appendEvidenceEvent(e,{kind:"degrade",obligationId:n,contractId:s.contractId,at:r,reason:a},`degrade\0${n}\0${a}`),this.replayEvidenceJournal(i),i.lastActivityAt=r,this.persist(i),true}removeSession(e){let n=e.trim();n&&(this.sessions.delete(n),rmSync(this.snapshotPath(n),{force:true}),rmSync(this.evidenceJournalDir(n),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(e){return join$1(this.sessionsDir,`${mo(e)}.json`)}evidenceJournalDir(e){return join$1(this.sessionsDir,"evidence-journal",mo(e))}appendEvidenceEvent(e,n,o){let r=this.evidenceJournalDir(e);mkdirSync(r,{recursive:true,mode:448});let i=createHash$1("sha256").update(o).digest("hex"),s=join$1(r,`${n.kind}-${i}.json`);if(existsSync$1(s))return;let a=join$1(r,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync(a,JSON.stringify(n),{mode:384});try{linkSync(a,s);}catch(c){if(c.code!=="EEXIST")throw c}finally{rmSync(a,{force:true});}}replayEvidenceJournal(e){e.evidenceObligations=po(e.evidenceObligations),e.evidenceDegradations=fo(e.evidenceDegradations),e.evidenceOutcomes=go(e.evidenceOutcomes);let n=this.evidenceJournalDir(e.sessionId);if(!existsSync$1(n))return;let o;try{o=readdirSync(n).filter(i=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(i)).slice(0,4096);}catch{return}let r=o.flatMap(i=>{try{let s=readFileSync(join$1(n,i),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=qs(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||ho(i.kind)-ho(s.kind));for(let i of r)this.applyEvidenceEvent(e,i);e.evidenceObligations=e.evidenceObligations.slice(-8),e.evidenceDegradations=e.evidenceDegradations.slice(-20),e.evidenceOutcomes=e.evidenceOutcomes.slice(-20);}applyEvidenceEvent(e,n){let o=e.evidenceOutcomes.find(s=>s.obligationId===n.obligationId);if(n.kind==="add"){if(o)return;let s=e.evidenceObligations.find(a=>a.obligationId===n.obligationId);s?(s.contract=n.contract,s.promptedAt=Math.min(s.promptedAt,n.at)):e.evidenceObligations.push({obligationId:n.obligationId,contractId:n.contractId,contract:n.contract,promptedAt:n.at,attempt:0,correctionRequested:false,violations:[]});return}let r=e.evidenceObligations.find(s=>s.obligationId===n.obligationId);if(n.kind==="correction"){if(!r||o||r.correctionFingerprint===n.fingerprint)return;r.attempt+=1,r.correctionRequested=true,r.correctionRequestedAt=n.at,r.correctionFingerprint=n.fingerprint,r.violations=n.violations;return}let i=r?.attempt??o?.attempt??0;if(n.kind==="resolve"&&o?.status==="degraded")e.evidenceOutcomes=e.evidenceOutcomes.filter(s=>s.obligationId!==n.obligationId),e.evidenceDegradations=e.evidenceDegradations.filter(s=>s.obligationId!==n.obligationId);else if(o)return;n.kind==="degrade"?(e.evidenceObligations=e.evidenceObligations.filter(s=>s.obligationId!==n.obligationId),e.evidenceDegradations.push({obligationId:n.obligationId,contractId:n.contractId,reason:n.reason,degradedAt:n.at,attempt:i,contract:r?.contract})):e.evidenceObligations=e.evidenceObligations.filter(s=>s.obligationId!==n.obligationId),e.evidenceOutcomes.push({obligationId:n.obligationId,contractId:n.contractId,status:n.kind==="resolve"?"resolved":"degraded",completedAt:n.at,attempt:i,...n.kind==="degrade"?{reason:n.reason}:{}});}persist(e){mkdirSync(this.sessionsDir,{recursive:true,mode:448});let n=this.snapshotPath(e.sessionId),o=`${n}.${process.pid}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(e),{mode:384}),renameSync$1(o,n);}};function po(t){return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!="object")return [];let n=e;if(typeof n.contractId!="string"||n.contractId.length===0||n.contractId.length>128||typeof n.promptedAt!="number"||typeof n.attempt!="number"||typeof n.correctionRequested!="boolean"||!Array.isArray(n.violations)||!_o(n.contract))return [];let o=typeof n.obligationId=="string"&&n.obligationId.length>0&&n.obligationId.length<=384?n.obligationId:vo(n.contractId),r=typeof n.correctionTranscriptHash=="string"?n.correctionTranscriptHash:void 0,i=n.correctionFingerprint??r;return i!==void 0&&!/^[a-f0-9]{64}$/.test(i)?[]:[{...n,obligationId:o,correctionFingerprint:i}]}).slice(-8):[]}function fo(t){return Array.isArray(t)?t.filter(e=>{if(!e||typeof e!="object")return false;let n=e;return typeof n.obligationId=="string"&&typeof n.contractId=="string"&&typeof n.reason=="string"&&typeof n.degradedAt=="number"&&typeof n.attempt=="number"}).slice(-20):[]}function go(t){return Array.isArray(t)?t.filter(e=>{if(!e||typeof e!="object")return false;let n=e;return typeof n.obligationId=="string"&&typeof n.contractId=="string"&&(n.status==="resolved"||n.status==="degraded")&&typeof n.completedAt=="number"&&typeof n.attempt=="number"&&(n.reason===void 0||typeof n.reason=="string")}).slice(-20):[]}function qs(t){if(!t||typeof t!="object")return null;let e=t,n=e.kind;if(n!=="add"&&n!=="correction"&&n!=="resolve"&&n!=="degrade"||typeof e.contractId!="string"||e.contractId.length>128||typeof e.at!="number")return null;let r={obligationId:typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:vo(e.contractId),contractId:e.contractId,at:e.at};if(n==="add")return _o(e.contract)?{kind:n,...r,contract:e.contract}:null;if(n==="correction"){let i=typeof e.fingerprint=="string"?e.fingerprint:e.transcriptHash;return typeof i=="string"&&/^[a-f0-9]{64}$/.test(i)&&Array.isArray(e.violations)&&e.violations.every(s=>typeof s=="string"&&s.length<=240)?{kind:n,...r,fingerprint:i,violations:e.violations}:null}return n==="resolve"?{kind:n,...r}:typeof e.reason=="string"&&e.reason.length<=240?{kind:n,...r,reason:e.reason}:null}function ho(t){return t==="add"?0:t==="correction"?1:2}function _o(t){if(!t||typeof t!="object")return false;let e=t,n=e.requiredSections,o=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(n)&&n.length===3&&n[0]==="\u5DE5\u5177\u53D1\u73B0"&&n[1]==="\u6A21\u578B\u5047\u8BBE"&&n[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(o)&&o.length<=16&&o.every(r=>typeof r=="string"&&r.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 ko(t,e){let n=xo(t);mkdirSync$1(n,{recursive:true,mode:448});let o=join(n,`${e.receiptId}.json`);if(existsSync(o))return e.receiptId;let r=`${o}.${process.pid}.tmp`;writeFileSync$1(r,JSON.stringify(e),{mode:384});try{renameSync(r,o);}catch(i){try{unlinkSync$1(r);}catch{}if(!existsSync(o))throw i}return e.receiptId}function bo(t){let e=xo(t);mkdirSync$1(e,{recursive:true,mode:448});let n=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(e,n),r=/\.json\.claim-\d+$/u.test(n),i=r?o:`${o}.claim-${process.pid}`;if(!r)try{renameSync(o,i);}catch{return null}try{let s=JSON.parse(readFileSync$1(i,"utf8"));if(typeof s.receiptId!="string"||typeof s.inputJson!="string"||typeof s.sessionId!="string"||typeof s.cleanupSharedState!="boolean")throw unlinkSync$1(i),new Error("session_finalize_spool_payload_invalid");return {receiptId:basename(n).replace(/\.json(?:\.claim-\d+)?$/u,""),payload:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function Ro(t){unlinkSync$1(t.path);}function So(t){try{renameSync(t.path,t.path.replace(/\.claim-\d+$/u,""));}catch{}}function xo(t){return join(P(t),"session-finalize-pending")}function C(t){let{projectRoot:e,...n}=t;try{return new St(e).dispatchBoundary(n).snapshot??null}catch(o){return y({event:"hook.runtime.degraded",identity:{projectRoot:e,sessionId:t.sessionId,...t.turnId?{turnId:t.turnId}:{},...t.requestId?{requestId:t.requestId}:{},...t.executionId?{executionId:t.executionId}:{}},level:"error",timestamp:Date.now(),data:{stage:t.kind,reason:o instanceof Error?o.message:String(o),tool:t.producer}}),null}}var St=class{constructor(e){this.projectRoot=e;}dispatchBoundary(e){let n=Ys(e.kind,e.payload??{});if(!n)return {handled:false};let o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let r=Gs(o,{projectRoot:this.projectRoot,sessionId:e.sessionId,...e.turnId?{turnId:e.turnId}:{},...e.requestId?{requestId:e.requestId}:{},...e.executionId?{executionId:e.executionId}:{}});return r?{handled:!0,snapshot:new TaskKernel(new TaskEventStore(o),new SemanticRuntimeEventProjector).dispatch({definition:r.definition,kind:n.kind,payload:n.payload,idempotencyKey:`host:${r.definition.definitionHash}:${e.dedupeKey}`,producer:e.producer}).snapshot}:{handled:!1}}finally{o.close();}}};function Gs(t,e){let n=e.executionId?t.getActiveContextReceipt(e.projectRoot,e.sessionId,e.executionId):null,o=e.turnId??n?.canonicalAction?.binding.turnId,r=e.requestId??n?.requestId;if(!o&&!r)return null;let i=t.listLatestTaskIntentArtifacts(e.projectRoot,e.sessionId).find(c=>o?c.turnId===o:c.requestId===r);if(!i)return null;let s=t.getTaskAggregateSnapshot(e.projectRoot,e.sessionId,i.turnId,i.version);if(!s)return null;let a=t.getTaskDefinitionV2(s.taskDefinitionHash);return !a||a.revision!==i.version?null:{definition:a,snapshot:s}}function Ys(t,e){switch(t){case "action.lease.issued":return {kind:"action_lease_issued",payload:e};case "action.succeeded":return {kind:"action_completed",payload:e};case "action.failed":return {kind:"action_failed",payload:e};case "verification.succeeded":return {kind:"verification_completed",payload:e};case "verification.failed":return {kind:"verification_failed",payload:e};case "memory.committed":return {kind:"memory_episode_persisted",payload:e};case "memory.skipped":return {kind:"memory_decision_completed",payload:e};case "memory.pending":return {kind:"memory_extraction_queued",payload:e};case "memory.failed":return {kind:"memory_extraction_failed",payload:e};case "durable_work.owned":return {kind:"durable_work_leased",payload:{...e,fencingToken:Number.isSafeInteger(e.fencingToken)?e.fencingToken:0}};case "durable_work.completed":return {kind:"durable_work_completed",payload:e};case "durable_work.dead_lettered":return {kind:"durable_work_dead_lettered",payload:e};default:return null}}var oa=256*1024,ra=48*1024,ia=512*1024,sa=500,aa=5,he=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function ca(t){return t==="react_audit_performance"||t.endsWith("__react_audit_performance")}function da(t){let e=ye(t,0,new Set);return e?Ia(e.contract,e.canonicalReport):null}function Co(t){if(!t.sessionId||!ca(t.toolName))return null;let e=da(t.toolResponse);if(!e)return null;let n=Date.now(),o=t.runtimeStore.addEvidenceObligation(t.sessionId,e,n,t.toolUseId),r=t.runtimeStore.get(t.sessionId);if(o&&r){let i=openGlobalDevFlowDatabase();try{i.upsertSessionObligation({obligationId:`evidence:${o.obligationId}`,projectRoot:r.projectRoot,sessionId:t.sessionId,executionId:r.executionId,kind:"evidence_contract",state:"open",payload:{contract:e,runtimeObligationId:o.obligationId},createdAt:n,updatedAt:n});}finally{i.close();}y({event:"verification.completed",identity:{projectRoot:r.projectRoot,sessionId:t.sessionId,executionId:r.executionId},level:"info",timestamp:n,data:{stage:"performance_detector_coverage",status:"obligation_opened",contractId:e.id,obligationId:o.obligationId,detectorCoverage:ze(t.toolResponse),runtimeProfilingOccurred:e.runtimeProfilingOccurred,samplingEvidenceOccurred:e.samplingEvidenceOccurred,toolUseId:t.toolUseId}});}return la(e)}function la(t){return [`DevFlow performance evidence contract ${t.id} is active.`,`The final performance answer MUST contain these three sections exactly: ${t.requiredSections.join(" / ")}.`,t.runtimeProfilingOccurred?"Only claims directly supported by the returned runtime measurements may be stated as measured facts.":"No runtime profiling occurred. Treat every finding as a static candidate: do not assign P0/high-risk severity, claim a confirmed bottleneck/jank/frame drop/CPU hotspot, quantify performance or benefit, or recommend requestAnimationFrame as generic throttling without sampling evidence.",`samplingEvidenceOccurred=${t.samplingEvidenceOccurred}. RAF recommendations are permitted only when this structured contract field is true; answer text cannot self-declare sampling evidence.`,"Use the canonical report below directly or preserve its evidence boundaries. Stop will request one correction for unsupported claims, then fail open with degradation telemetry.",t.canonicalReport].join(`
5
5
 
6
- `)}function Do(t){let e=t.runtimeStore??new q(t.projectRoot),n=e.listEvidenceObligations(t.sessionId);if(n.length===0)return la(t,e),null;let o=Et(t.transcriptPath,n);if(!o.answer){let s=o.degradationReason??"transcript_answer_unavailable";for(let a of n)e.degradeEvidenceObligation(t.sessionId,a.obligationId,s);return null}let r=o.fingerprint;if(!r){for(let s of n)e.degradeEvidenceObligation(t.sessionId,s.obligationId,"transcript_identity_unavailable");return null}let i=[];for(let s of n){let a=Mo(o.answer,[s]);if(a.length===0){e.resolveEvidenceObligation(t.sessionId,s.obligationId),Ue(t,s,"satisfied",r);continue}if(!s.correctionFingerprint){e.markEvidenceCorrection(t.sessionId,s.obligationId,a,r),i.push({obligation:s,violations:a}),Ue(t,s,"correction_requested",r,a);continue}if(s.correctionFingerprint===r){i.push({obligation:s,violations:a});continue}e.degradeEvidenceObligation(t.sessionId,s.obligationId,"evidence_contract_unresolved"),Ue(t,s,"degraded",r,a);}return i.length===0?null:ua(i)}function la(t,e){let n=(e.get(t.sessionId)?.evidenceDegradations??[]).filter(i=>i.contract).slice(-8);if(n.length===0)return;let o=n.map(i=>({obligationId:i.obligationId,contractId:i.contractId,contract:i.contract,promptedAt:i.degradedAt,attempt:i.attempt,correctionRequested:true,violations:[]})),r=Et(t.transcriptPath,o);if(!(!r.answer||!r.fingerprint))for(let i of o)Mo(r.answer,[i]).length>0||e.resolveDegradedEvidence(t.sessionId,i.obligationId)&&Ue(t,i,"satisfied",r.fingerprint);}function Ue(t,e,n,o,r=[]){n!=="correction_requested"&&C({projectRoot:t.projectRoot,sessionId:t.sessionId,kind:n==="satisfied"?"verification.succeeded":"verification.failed",payload:{receiptId:e.obligationId,reasonCode:n==="satisfied"?"performance_evidence_satisfied":"performance_evidence_unresolved"},dedupeKey:`${e.obligationId}:${n}:${e.attempt}`,producer:"devflow-evidence-contract"}),y({event:"verification.completed",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId},level:n==="satisfied"?"info":n==="degraded"?"error":"warn",timestamp:Date.now(),data:{stage:"performance_evidence_transition",status:n,contractId:e.contractId,obligationId:e.obligationId,attempt:e.attempt,answerFingerprint:o,violations:r,supersedesDegradation:n==="satisfied"&&e.attempt>0}});}function ze(t,e=0){if(e>6||t==null)return [];if(typeof t=="string")try{return ze(JSON.parse(t),e+1)}catch{return []}if(Array.isArray(t)){for(let o of t){let r=ze(o,e+1);if(r.length>0)return r}return []}if(typeof t!="object")return [];let n=t;if(Array.isArray(n.detectorCoverage))return n.detectorCoverage.filter(o=>typeof o=="string").slice(0,32);for(let o of Object.values(n)){let r=ze(o,e+1);if(r.length>0)return r}return []}function ua(t){let e=[...new Set(t.flatMap(o=>o.violations))],n=[...new Map(t.map(o=>[o.obligation.contractId,o.obligation.contract.canonicalReport])).values()];return {decision:"block",reason:["DevFlow evidence contract violation. Correct the final performance answer once before stopping.",`Violations: ${e.join("; ")}`,"Use this canonical report (you may add clearly labeled hypotheses or runtime verification steps, but no unsupported measured claims):",n.join(`
6
+ `)}function Do(t){let e=t.runtimeStore??new q(t.projectRoot),n=e.listEvidenceObligations(t.sessionId);if(n.length===0)return ua(t,e),null;let o=Et(t.transcriptPath,n);if(!o.answer){let s=o.degradationReason??"transcript_answer_unavailable";for(let a of n)e.degradeEvidenceObligation(t.sessionId,a.obligationId,s);return null}let r=o.fingerprint;if(!r){for(let s of n)e.degradeEvidenceObligation(t.sessionId,s.obligationId,"transcript_identity_unavailable");return null}let i=[];for(let s of n){let a=Mo(o.answer,[s]);if(a.length===0){e.resolveEvidenceObligation(t.sessionId,s.obligationId),Ue(t,s,"satisfied",r);continue}if(!s.correctionFingerprint){e.markEvidenceCorrection(t.sessionId,s.obligationId,a,r),i.push({obligation:s,violations:a}),Ue(t,s,"correction_requested",r,a);continue}if(s.correctionFingerprint===r){i.push({obligation:s,violations:a});continue}e.degradeEvidenceObligation(t.sessionId,s.obligationId,"evidence_contract_unresolved"),Ue(t,s,"degraded",r,a);}return i.length===0?null:ma(i)}function ua(t,e){let n=(e.get(t.sessionId)?.evidenceDegradations??[]).filter(i=>i.contract).slice(-8);if(n.length===0)return;let o=n.map(i=>({obligationId:i.obligationId,contractId:i.contractId,contract:i.contract,promptedAt:i.degradedAt,attempt:i.attempt,correctionRequested:true,violations:[]})),r=Et(t.transcriptPath,o);if(!(!r.answer||!r.fingerprint))for(let i of o)Mo(r.answer,[i]).length>0||e.resolveDegradedEvidence(t.sessionId,i.obligationId)&&Ue(t,i,"satisfied",r.fingerprint);}function Ue(t,e,n,o,r=[]){n!=="correction_requested"&&C({projectRoot:t.projectRoot,sessionId:t.sessionId,kind:n==="satisfied"?"verification.succeeded":"verification.failed",payload:{receiptId:e.obligationId,reasonCode:n==="satisfied"?"performance_evidence_satisfied":"performance_evidence_unresolved"},dedupeKey:`${e.obligationId}:${n}:${e.attempt}`,producer:"devflow-evidence-contract"}),y({event:"verification.completed",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId},level:n==="satisfied"?"info":n==="degraded"?"error":"warn",timestamp:Date.now(),data:{stage:"performance_evidence_transition",status:n,contractId:e.contractId,obligationId:e.obligationId,attempt:e.attempt,answerFingerprint:o,violations:r,supersedesDegradation:n==="satisfied"&&e.attempt>0}});}function ze(t,e=0){if(e>6||t==null)return [];if(typeof t=="string")try{return ze(JSON.parse(t),e+1)}catch{return []}if(Array.isArray(t)){for(let o of t){let r=ze(o,e+1);if(r.length>0)return r}return []}if(typeof t!="object")return [];let n=t;if(Array.isArray(n.detectorCoverage))return n.detectorCoverage.filter(o=>typeof o=="string").slice(0,32);for(let o of Object.values(n)){let r=ze(o,e+1);if(r.length>0)return r}return []}function ma(t){let e=[...new Set(t.flatMap(o=>o.violations))],n=[...new Map(t.map(o=>[o.obligation.contractId,o.obligation.contract.canonicalReport])).values()];return {decision:"block",reason:["DevFlow evidence contract violation. Correct the final performance answer once before stopping.",`Violations: ${e.join("; ")}`,"Use this canonical report (you may add clearly labeled hypotheses or runtime verification steps, but no unsupported measured claims):",n.join(`
7
7
 
8
8
  ---
9
9
 
10
10
  `)].join(`
11
11
 
12
- `)}}function Mo(t,e){let n=new Set,o=new Set(e.flatMap(c=>c.contract.requiredSections)),r=Oo(t.split(/\r?\n/)),i=Po(r.headingLines);for(let c of o)i.found.has(c)||n.add(`missing_section:${c}`);if(e.every(c=>c.contract.runtimeProfilingOccurred))return [...n];let a=e.every(c=>c.contract.samplingEvidenceOccurred);for(let c=0;c<r.claimLines.length;c++){let d=r.claimLines[c].trim();if(!d||pa(d))continue;let u=i.byLine.get(c);for(let l of va(d))ga(l,u,a,n);}return [...n]}function Oo(t){let e=false,n=[],o=[];for(let r of t){if(/^\s*```/.test(r)){e=!e,n.push(""),o.push(r.replace(/^\s*```+[^\s`]*/,"").replace(/```+\s*$/,"").trim());continue}n.push(e?"":r.replace(/`[^`]*`/g,"").trim()),o.push(r.replace(/`([^`]*)`/g,(i,s)=>ma(s)?"":s).trim());}return {headingLines:n,claimLines:o}}function ma(t){let e=t.trim().slice(0,256);return !e||/\s/.test(e)||t.trim().length>256?false:/^[A-Za-z_$][\w$.-]*$/.test(e)||/^(['"])[^'"`]*\1$/.test(e)}function pa(t){if(t.length>2048)return false;let e=t.replace(/^\s*(?:[-*+]|\d+[.)])\s+/,"").trim();return e?fa(e)||/^(?:\/\/|\/\*|\*\/|\*\s|#!)/.test(e)||/^(?:import|export|const|let|var|function|class|type|interface|enum|namespace|declare)\b/.test(e)||/^(?:async\s+)?(?:function\s+)?[A-Za-z_$][\w$]*\s*=\s*/.test(e)||/^[A-Za-z_$][\w$.[\]'"-]*\s*(?:=|\+=|-=|\*=|\/=|\?\?=|&&=|\|\|=)\s*/.test(e)||/^[A-Za-z_$'"-][\w$.'"-]*\s*:\s*[^:]+[,}]?$/.test(e)||/=>/.test(e)||/^(?:await\s+|return\s+|throw\s+|new\s+)?[A-Za-z_$][\w$.]*\s*\([^)]*\)\s*;?$/.test(e)||/^(['"])[\s\S]*\1[;,]?$/.test(e)?true:/[{}()[\]=<>]\s*;?$/.test(e)&&/(?:;|=>|\b(?:return|new|await)\b)/.test(e):false}function fa(t){if(t.length>1024)return false;let e="(?:--[A-Za-z0-9_-]+|(?:-webkit-|-moz-|-ms-)?(?:animation(?:-[a-z-]+)?|transition(?:-[a-z-]+)?|opacity|transform|will-change|contain|content-visibility|display|position|top|right|bottom|left|width|height|min-(?:width|height)|max-(?:width|height)|margin(?:-[a-z]+)?|padding(?:-[a-z]+)?|color|background(?:-[a-z-]+)?|border(?:-[a-z-]+)?|font(?:-[a-z-]+)?|line-height|z-index|overflow(?:-[xy])?))";return new RegExp(`^${e}\\s*:\\s*\\S[^;]{0,960};$`,"i").test(t)}function ga(t,e,n,o){let r=/\bP0\b/gi;for(let g of t.matchAll(r))Ao(t,g.index??0,g[0],"p0")||o.add("unsupported_p0_severity");let i=/(?:中高|高)(?:风险|优先级)|严重(?:问题|风险)|\bhigh[- ](?:risk|severity|priority)\b/gi;for(let g of t.matchAll(i))Ao(t,g.index??0,g[0],"high")||o.add("unsupported_high_severity");let s=/(?:性能)?瓶颈|卡顿|掉帧|CPU\s*(?:热点|尖峰)|\bbottleneck\b|\bjank\b|\bdropped frames?\b|\bCPU hotspot\b/gi;for(let g of t.matchAll(s))ya(t,g.index??0,g[0])||(/(?:瓶颈|bottleneck)/i.test(g[0])?o.add("unsupported_confirmed_bottleneck"):o.add("unsupported_runtime_effect"));let a=/\b\d{1,3}(?:\.\d+)?\s*%/.test(t),c=/(?:预计|预期|估计|提升|降低|减少|节省|改善|收益|加速|improve|reduce|faster|gain|benefit|speedup|expected|estimated)/i.test(t),d=/\b\d+(?:\.\d+)?\s*[x×]\b/i.test(t);(a||d)&&c&&o.add(a?"unsupported_benefit_percentage":"unsupported_performance_number");let u=/\b\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:ms|fps|hz)\b/i.test(t)||/\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:毫秒|次\s*\/\s*秒|帧)/.test(t),l=e==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&/(?:采集|记录|测量|收集|collect|measure|record)/i.test(t)&&!/(?:预计|预期|估计|约|大约|通常|平均|每(?:隔)?|达到|提升|降低|减少|节省|改善|improve|reduce|faster|expected|estimated|average|typically|every)/i.test(t);a&&!c&&!l&&o.add("unsupported_benefit_percentage"),u&&!l&&o.add("unsupported_performance_number");let m=/(?:requestAnimationFrame|\bRAF\b)/i.test(t),f=/(?:建议|应该|应当|使用|添加|采用|切换|包裹|优化|节流|\buse\b|\badopt\b|\brecommend\b|\bswitch\b|\bwrap\b|\bthrottl(?:e|ing)\b)/i.test(t),p=/(?:不要|不得|不能|不应|避免|不建议|不推荐).{0,16}(?:使用|采用|添加|切换|包裹|节流)?.{0,8}(?:requestAnimationFrame|\bRAF\b)|\b(?:do\s+not|don't|never|avoid)\s+(?:use|adopt|recommend|switch|wrap|throttle)?.{0,8}(?:requestAnimationFrame|RAF)\b/i.test(t);m&&f&&!p&&!n&&o.add("raf_without_sampling_evidence");}function Ao(t,e,n,o){let r=t.slice(Math.max(0,e-64),e),i=t.slice(e+n.length,e+n.length+28),s=ha(r),a=/^(?:\s+)?(?:未发现|不存在|并不存在|未被发现)/.test(i)||/^(?:\s+)?(?:was\s+|is\s+)?not found\b/i.test(i);return s||a?true:o==="high"?/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?)\s*(?:任何|明确的)?\s*P0\s*(?:或|和|及|、)\s*$/i.test(r)||/\b(?:no evidence (?:of|for)|no)\s+P0\s+(?:or|and)\s+$/i.test(r):false}function ha(t){if(/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?|不是|并非|未被)\s*(?:任何|明确的)?\s*(?:(?:问题|发现|证据|项|内容)\s*)?(?:(?:属于|(?:被)?(?:评|判定|认定|标记|列|视|定|归(?:类)?)为)\s*)?$/i.test(t)||/\b(?:no evidence (?:of|for)|no|not|isn't|is\s+not)\s+(?:an?\s+)?(?:(?:issues?|findings?|evidence|items?)\s+)?(?:(?:classified|rated|marked|labelled|labeled)(?:\s+as)?\s+)?$/i.test(t))return true;let n=/(?:不得|不能|不应|不宜|不要)\s*(?:被\s*)?(?:(?:直接|轻易|简单|明确|正式|合理|据此|当前|目前)\s*){0,2}(?:(?:评|判定|认定|标记|列|视|定|归(?:类)?)为|属于)\s*$/i,o=/\b(?:cannot|can't|must not|should not|shouldn't|do not|don't)\s+(?:(?:reasonably|directly|formally|currently)\s+){0,2}(?:be\s+)?(?:classified|labeled|labelled|rated|marked)(?:\s+as)?\s+$/i;return n.test(t)||o.test(t)}function ya(t,e,n){let o=t.slice(Math.max(0,e-40),e),r=t.slice(e+n.length,e+n.length+32),i=/(?:是否|待验证|候选|可能|潜在|未观察到|没有观察到|未发现|不存在|无证据(?:表明)?|不能(?:据此)?确认|尚未(?:确认|证明)|验证(?:是否)?|测量(?:是否)?|采集|记录|收集).{0,16}$/i.test(o)||/\b(?:whether|measure|validate|candidate|potential|possible|may|might|no|no evidence(?: of| for)?|not observed|unobserved|collect|record).{0,18}$/i.test(o),s=/^(?:是否|有待验证|待验证|候选|可能|潜在|指标|需要(?:验证|测量)|需(?:验证|测量))/.test(r)||/^(?:\s+)?(?:candidate|potential|possible|metric|metrics|to (?:measure|validate)|needs? (?:measurement|validation)|is (?:a )?(?:candidate|potential))/i.test(r);return i||s}function va(t){return t.split(/(?:[。!?;;,,]|\b(?:but|however|yet|nevertheless|nonetheless)\b|但是|但|然而|却|不过|可是)/i).map(e=>e.trim()).filter(Boolean)}function ye(t,e,n){if(e>sa||t===null||t===void 0)return null;if(typeof t=="string"){if(Buffer.byteLength(t,"utf8")>na)return null;try{return ye(JSON.parse(t),e+1,n)}catch{return null}}if(typeof t!="object"||n.has(t))return null;if(n.add(t),Array.isArray(t)){for(let r of t.slice(0,16)){let i=ye(r,e+1,n);if(i)return i}return null}let o=t;if("evidenceContract"in o)return {contract:o.evidenceContract,canonicalReport:o.canonicalReport};for(let r of ["structuredContent","data","result"])if(r in o){let i=ye(o[r],e+1,n);if(i)return i}if(Array.isArray(o.content))for(let r of o.content.slice(0,16)){let i=r&&typeof r=="object"&&"text"in r?r.text:r,s=ye(i,e+1,n);if(s)return s}return null}function _a(t,e){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t;if(n.version!=="1.0"||typeof n.id!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(n.id)||typeof n.runtimeProfilingOccurred!="boolean"||typeof n.samplingEvidenceOccurred!="boolean"||!Array.isArray(n.requiredSections)||n.requiredSections.length!==he.length)return null;let o=n.requiredSections.filter(c=>typeof c=="string");if(o.length!==he.length||he.some((c,d)=>o[d]!==c)||!Array.isArray(n.prohibitedClaims)||n.prohibitedClaims.length>16)return null;let r=n.prohibitedClaims.filter(c=>typeof c=="string"&&c.length<=128);if(r.length!==n.prohibitedClaims.length)return null;let i=n.correctionPolicy;if(!i||typeof i!="object"||Array.isArray(i))return null;let s=i;if(s.maxAttempts!==1||s.repeatedViolation!=="fail_open")return null;let a=typeof n.canonicalReport=="string"?n.canonicalReport:e;return typeof a!="string"||Buffer.byteLength(a,"utf8")>oa||he.some(c=>!a.includes(c))?null:{version:"1.0",id:n.id,runtimeProfilingOccurred:n.runtimeProfilingOccurred,samplingEvidenceOccurred:n.samplingEvidenceOccurred,requiredSections:o,prohibitedClaims:r,correctionPolicy:{maxAttempts:1,repeatedViolation:"fail_open"},canonicalReport:a}}function Et(t,e){if(!t||t.length>4096)return {degradationReason:"transcript_path_missing"};let n;try{let o=lstatSync$1(t);if(!o.isFile()||o.isSymbolicLink())return {degradationReason:"transcript_path_unsafe"};n=openSync$1(t,constants.O_RDONLY|(constants.O_NOFOLLOW??0));let r=fstatSync$1(n);if(!r.isFile()||r.dev!==o.dev||r.ino!==o.ino)return {degradationReason:"transcript_path_changed"};let i=Math.min(r.size,ra),s=Buffer.alloc(i),a=0;for(;a<i;){let p=readSync(n,s,a,i-a,r.size-i+a);if(p===0)break;a+=p;}let c=s.subarray(0,a).toString("utf8");r.size>i&&(c=c.slice(Math.max(0,c.indexOf(`
13
- `)+1)));let d=c.split(/\r?\n/).slice(-ia),u=e.length>0?Math.min(...e.map(p=>p.promptedAt)):0,l=wa(d,u),f=[...l].reverse().find(p=>Ia(p.text,e))??l.at(-1);return f?.text?{answer:f.text,fingerprint:f.fingerprint}:{degradationReason:"transcript_answer_unavailable"}}catch{return {degradationReason:"transcript_unreadable"}}finally{n!==void 0&&closeSync$1(n);}}function Ia(t,e){let n=new Set(e.flatMap(r=>r.contract.requiredSections)),o=Po(Oo(t.split(/\r?\n/u)).headingLines);return [...n].every(r=>o.found.has(r))}function Be(t){return Et(t,[]).answer}function wa(t,e){let n=[];for(let o=0;o<t.length;o++){let r=t[o];if(r.trim())try{let i=JSON.parse(r),s=i.message;if(!s||typeof s!="object"||s.role!=="assistant")continue;let a=s,c=ka(i.timestamp);if(c>0&&c+5e3<e)continue;let d=s.content,u=typeof d=="string"?d:Array.isArray(d)?d.filter(l=>l&&typeof l=="object"&&l.type==="text").map(l=>l.text).filter(l=>typeof l=="string").join(`
14
- `):"";if(u.trim()){let l=u.trim(),m=typeof a.id=="string"&&a.id?`message:${a.id}`:typeof i.uuid=="string"&&i.uuid?`uuid:${i.uuid}`:`record:${String(i.timestamp??"")}:${o}:${createHash("sha256").update(r).digest("hex")}`,f=createHash("sha256").update(l).digest("hex"),p=createHash("sha256").update(`${m}\0${f}`).digest("hex");n.push({text:l,timestamp:c,fingerprint:p});}}catch{continue}}return n}function ka(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?e:0}function Po(t){let e=new Set,n=new Map,o;for(let r=0;r<t.length;r++){let i=t[r].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=he.find(a=>i===a);s&&(o=s,e.add(s)),n.set(r,o);}return {found:e,byLine:n}}function Fo(t){let e;try{if(Aa(t.toolResponse))return null;e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let n=e.getActiveContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!n)return null;let o=Sa(t.toolInput);if(o.length===0)return null;let r=t.toolName==="Read"?xa(t.toolInput):void 0,i=r?n.selectedFiles?.find(u=>Ea(t.projectRoot,u,r)):void 0,s=Ta(t.toolName),a=i?"code":n.canonicalNextAction===s?"action":null,c=i&&o.includes(i)?i:a==="action"&&o.includes(s)?s:void 0;if(a&&c){let u=[n.contextHash,n.requestId??"",a,c,t.toolUseId??`${t.sessionId}:${t.executionId??n.executionId}`].join("\0");e.recordContextSelectionEvent({id:`ctxsel:${createHash("sha256").update(u).digest("hex").slice(0,32)}`,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId,selectionType:a,candidateId:c,toolName:t.toolName,toolUseId:t.toolUseId,selectedAt:Date.now()});}let d=e.listRetrievalLedgerEvents({projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId}).filter(u=>u.stage==="selected"&&o.includes(u.sourceId));for(let u of d)e.appendRetrievalLedgerEvent({...u,id:retrievalLedgerTransitionId(u.id,"consumed",t.toolUseId??t.toolName),stage:"consumed",toolEvidence:[t.toolUseId??t.toolName],evidenceIds:o,actor:t.toolName,reasonCode:"structural_evidence_ref",payload:{...u.payload,consumedByTool:t.toolName},createdAt:Date.now()});return d.length>0&&ve({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId,contextReceipt:n.contextHash},level:"info",timestamp:Date.now(),data:{stage:"consumed",actor:t.toolName,consumedCount:d.length,evidenceRefCount:o.length}}),a}catch(n){throw ve({event:"hook.runtime.degraded",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:"warn",timestamp:Date.now(),data:{stage:"retrieval_attribution",actor:t.toolName,reason:n instanceof Error?n.message:String(n)}}),n}finally{try{e?.close();}catch{}}}function Ho(t){let e=openGlobalDevFlowDatabase();try{let n=e.listRetrievalLedgerEvents(t),o=new Map(n.filter(l=>l.stage==="selected").map(l=>[jo(l),l])),r=new Map(n.filter(l=>l.stage==="consumed").map(l=>[jo(l),l])),i=0,s=0,a=0;for(let[l,m]of o){let f=r.get(l);f&&t.verificationReceipt&&e.appendRetrievalLedgerEvent({...f,id:retrievalLedgerTransitionId(f.id,"verified",t.verificationReceipt),stage:"verified",verificationReceipt:t.verificationReceipt,reasonCode:"same_task_verification_receipt",createdAt:t.finishedAt??Date.now()});let p=f&&t.verificationReceipt&&t.outcome!=="unknown"?t.outcome:"unknown",g=p==="positive"?"positive_outcome":p==="negative"?"negative_outcome":"unknown_outcome";e.appendRetrievalLedgerEvent({...m,id:retrievalLedgerTransitionId(m.id,g,t.verificationReceipt??t.sessionId),stage:g,reason:f?t.outcomeReason:"selected_not_consumed",toolEvidence:f?.toolEvidence??[],verificationReceipt:p==="unknown"?void 0:t.verificationReceipt,payload:{...m.payload,consumed:!!f},createdAt:t.finishedAt??Date.now()}),g==="positive_outcome"?i+=1:g==="negative_outcome"?s+=1:a+=1;}let c=t.requiredChannels.map(l=>{let m=[...o.values()].filter(p=>p.sourceType===l).length,f=[...r.values()].filter(p=>p.sourceType===l).length;return {channel:l,selected:m,consumed:f,verified:t.verificationReceipt?f:0}}),d={status:c.length>0&&c.every(l=>l.selected>0&&l.consumed===l.selected&&l.verified===l.selected)?"complete":"unavailable",channels:c},u={consumed:r.size,positive:i,negative:s,unknown:a,consumedSources:[...r.values()].map(l=>({sourceType:l.sourceType,sourceId:l.sourceId})),proof:d};return t.verificationReceipt&&r.size>0&&ve({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:"info",timestamp:t.finishedAt??Date.now(),data:{stage:"verified",verifiedCount:r.size}}),ve({event:"task.proof.completed",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:d.status==="complete"?"info":"warn",timestamp:t.finishedAt??Date.now(),data:d}),ve({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:a>0?"warn":"info",timestamp:t.finishedAt??Date.now(),data:{stage:"session_outcome",selectedCount:o.size,consumedCount:r.size,verifiedCount:t.verificationReceipt?r.size:0,positiveCount:i,negativeCount:s,unknownCount:a}}),u}finally{e.close();}}function Sa(...t){let e=new Set,n=(o,r=0)=>{if(!(r>6||o==null)){if(typeof o=="string"){try{n(JSON.parse(o),r+1);}catch{}return}if(Array.isArray(o)){for(let i of o)n(i,r+1);return}if(typeof o=="object")for(let[i,s]of Object.entries(o))if((i==="evidenceRefs"||i==="_devflow_evidence_refs")&&Array.isArray(s))for(let a of s)typeof a=="string"&&a.trim()&&e.add(a.trim());else n(s,r+1);}};for(let o of t)n(o);return [...e]}function xa(t){for(let e of ["file_path","path"]){let n=t[e];if(typeof n=="string"&&n.trim())return n.trim()}}function Ea(t,e,n){let o=resolve(t,e),r=isAbsolute(n)?resolve(n):resolve(t,n);return o===r}function Ta(t){return t.startsWith("mcp__")?t.split("__").at(-1)??t:t}function Aa(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.ok===false||e.success===false||e.isError===true||!!e.error||["failed","rejected","unavailable"].includes(String(e.status??""))}function jo(t){return [t.requestId,t.contextReceipt,t.sourceType,t.sourceId].join("\0")}function ve(t){try{y(t);}catch{}}var Fa=8*1024*1024;function qo(t){if(!t.transcriptPath||!existsSync(t.transcriptPath))return {status:"unavailable",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:"transcript_path_unavailable"};let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=e.getLatestTranscriptCheckpoint({projectRoot:t.projectRoot,hostId:"claude-code",sessionId:t.sessionId,sourcePath:t.transcriptPath}),o=statSync(t.transcriptPath).size,r=Math.min(n?.byteOffset??0,o),i=Math.min(Fa,o-r);if(i<=0)return {status:"completed",eventsRead:0,failuresFound:0,failuresRecorded:0,checkpointId:n?.id};let s=Buffer.alloc(i),a=openSync$1(t.transcriptPath,"r");try{readSync(a,s,0,i,r);}finally{closeSync$1(a);}let c=s.toString("utf8").split(/\r?\n/u).filter(Boolean),d=e.listLatestTaskIntentArtifacts(t.projectRoot,t.sessionId),u=new Map,l=new Set,m=0,f=0;for(let k of c){let b;try{b=JSON.parse(k);}catch{continue}for(let R of Ct(b,u)){let I=claudeCodeRuntimeAdapter.normalizeToolResult(R,{projectRoot:t.projectRoot});if(I.success||!I.error)continue;let F=I.toolUseId??I.sourceHash;if(l.has(F))continue;l.add(F),m++;let T=I.toolUseId?e.getToolCallEventByToolUseId(t.sessionId,I.toolUseId):null,M=No(T?.input,"_devflow_turn_id"),L=No(T?.input,"_devflow_request_id"),S=M?d.find(E=>E.turnId===M):[...d].reverse().find(E=>(!T?.executionId||E.executionId===T.executionId)&&E.createdAt<=(T?.timestamp??I.timestamp))??d.at(-1),A=`host-failure:${I.sourceHash}`;e.insertEvent({kind:"host_transcript_tool_failure",timestamp:I.timestamp,success:!1,toolName:I.canonicalName??I.requestedName,metadata:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:M??S?.turnId,requestId:L??S?.requestId,sourceId:A,toolUseId:I.toolUseId,correlatedEventId:T?.eventId,requestedName:I.requestedName,canonicalName:I.canonicalName,failureCategory:I.failureCategory,error:I.error.slice(0,1e3)}}),y({event:"host.tool.result.reconciled",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:M??S?.turnId,requestId:L??S?.requestId,executionId:T?.executionId},level:"warn",timestamp:Date.now(),data:{toolUseId:I.toolUseId,toolName:I.canonicalName??I.requestedName,failureCategory:I.failureCategory,correlation:T?"tool_use_id":"timestamp_fallback"}}),f++;}}let p=createHash("sha256").update(s).digest("hex"),g=`transcript:${createHash("sha256").update(`${t.projectRoot}\0${t.sessionId}\0${t.transcriptPath}\0${r+i}\0${p}`).digest("hex").slice(0,24)}`;return e.appendTranscriptCheckpoint({id:g,projectRoot:t.projectRoot,hostId:"claude-code",sessionId:t.sessionId,sourcePath:t.transcriptPath,sourceHash:p,byteOffset:r+i,eventCount:c.length,createdAt:Date.now()}),y({event:"session.reconciled",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId},level:m>0?"warn":"info",timestamp:Date.now(),data:{stage:"transcript",eventsRead:c.length,failuresFound:m,failuresRecorded:f,checkpointId:g}}),{status:"completed",eventsRead:c.length,failuresFound:m,failuresRecorded:f,checkpointId:g}}catch(n){return {status:"degraded",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:n instanceof Error?n.message:String(n)}}finally{e.close();}}function No(t,e){let n=t?.[e];return typeof n=="string"&&n.trim()?n.trim():void 0}function Ct(t,e,n=0){if(n>7||t===null||t===void 0)return [];if(Array.isArray(t))return t.flatMap(s=>Ct(s,e,n+1));if(typeof t!="object")return [];let o=t,r=typeof o.type=="string"?o.type:"";r==="tool_use"&&typeof o.id=="string"&&typeof o.name=="string"&&e.set(o.id,o.name);let i=[];if(r==="tool_result"){let s=typeof o.tool_use_id=="string"?o.tool_use_id:void 0;i.push({tool_name:s?e.get(s)??"unknown":"unknown",tool_use_id:s,tool_response:o.content,is_error:o.is_error===true,...o.is_error===true?{error:Dt(o.content)||"host tool result failed"}:{},timestamp:o.timestamp});}else (o.tool_name||o.toolName)&&(o.tool_response!==void 0||o.output!==void 0||o.error!==void 0)&&i.push(o);for(let[s,a]of Object.entries(o))s==="content"&&r==="tool_result"||i.push(...Ct(a,e,n+1));return i}function Dt(t){if(typeof t=="string")return t.slice(0,4e3);if(Array.isArray(t))return t.map(Dt).filter(Boolean).join(`
12
+ `)}}function Mo(t,e){let n=new Set,o=new Set(e.flatMap(c=>c.contract.requiredSections)),r=Oo(t.split(/\r?\n/)),i=Po(r.headingLines);for(let c of o)i.found.has(c)||n.add(`missing_section:${c}`);if(e.every(c=>c.contract.runtimeProfilingOccurred))return [...n];let a=e.every(c=>c.contract.samplingEvidenceOccurred);for(let c=0;c<r.claimLines.length;c++){let d=r.claimLines[c].trim();if(!d||fa(d))continue;let u=i.byLine.get(c);for(let l of _a(d))ha(l,u,a,n);}return [...n]}function Oo(t){let e=false,n=[],o=[];for(let r of t){if(/^\s*```/.test(r)){e=!e,n.push(""),o.push(r.replace(/^\s*```+[^\s`]*/,"").replace(/```+\s*$/,"").trim());continue}n.push(e?"":r.replace(/`[^`]*`/g,"").trim()),o.push(r.replace(/`([^`]*)`/g,(i,s)=>pa(s)?"":s).trim());}return {headingLines:n,claimLines:o}}function pa(t){let e=t.trim().slice(0,256);return !e||/\s/.test(e)||t.trim().length>256?false:/^[A-Za-z_$][\w$.-]*$/.test(e)||/^(['"])[^'"`]*\1$/.test(e)}function fa(t){if(t.length>2048)return false;let e=t.replace(/^\s*(?:[-*+]|\d+[.)])\s+/,"").trim();return e?ga(e)||/^(?:\/\/|\/\*|\*\/|\*\s|#!)/.test(e)||/^(?:import|export|const|let|var|function|class|type|interface|enum|namespace|declare)\b/.test(e)||/^(?:async\s+)?(?:function\s+)?[A-Za-z_$][\w$]*\s*=\s*/.test(e)||/^[A-Za-z_$][\w$.[\]'"-]*\s*(?:=|\+=|-=|\*=|\/=|\?\?=|&&=|\|\|=)\s*/.test(e)||/^[A-Za-z_$'"-][\w$.'"-]*\s*:\s*[^:]+[,}]?$/.test(e)||/=>/.test(e)||/^(?:await\s+|return\s+|throw\s+|new\s+)?[A-Za-z_$][\w$.]*\s*\([^)]*\)\s*;?$/.test(e)||/^(['"])[\s\S]*\1[;,]?$/.test(e)?true:/[{}()[\]=<>]\s*;?$/.test(e)&&/(?:;|=>|\b(?:return|new|await)\b)/.test(e):false}function ga(t){if(t.length>1024)return false;let e="(?:--[A-Za-z0-9_-]+|(?:-webkit-|-moz-|-ms-)?(?:animation(?:-[a-z-]+)?|transition(?:-[a-z-]+)?|opacity|transform|will-change|contain|content-visibility|display|position|top|right|bottom|left|width|height|min-(?:width|height)|max-(?:width|height)|margin(?:-[a-z]+)?|padding(?:-[a-z]+)?|color|background(?:-[a-z-]+)?|border(?:-[a-z-]+)?|font(?:-[a-z-]+)?|line-height|z-index|overflow(?:-[xy])?))";return new RegExp(`^${e}\\s*:\\s*\\S[^;]{0,960};$`,"i").test(t)}function ha(t,e,n,o){let r=/\bP0\b/gi;for(let g of t.matchAll(r))Ao(t,g.index??0,g[0],"p0")||o.add("unsupported_p0_severity");let i=/(?:中高|高)(?:风险|优先级)|严重(?:问题|风险)|\bhigh[- ](?:risk|severity|priority)\b/gi;for(let g of t.matchAll(i))Ao(t,g.index??0,g[0],"high")||o.add("unsupported_high_severity");let s=/(?:性能)?瓶颈|卡顿|掉帧|CPU\s*(?:热点|尖峰)|\bbottleneck\b|\bjank\b|\bdropped frames?\b|\bCPU hotspot\b/gi;for(let g of t.matchAll(s))va(t,g.index??0,g[0])||(/(?:瓶颈|bottleneck)/i.test(g[0])?o.add("unsupported_confirmed_bottleneck"):o.add("unsupported_runtime_effect"));let a=/\b\d{1,3}(?:\.\d+)?\s*%/.test(t),c=/(?:预计|预期|估计|提升|降低|减少|节省|改善|收益|加速|improve|reduce|faster|gain|benefit|speedup|expected|estimated)/i.test(t),d=/\b\d+(?:\.\d+)?\s*[x×]\b/i.test(t);(a||d)&&c&&o.add(a?"unsupported_benefit_percentage":"unsupported_performance_number");let u=/\b\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:ms|fps|hz)\b/i.test(t)||/\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:毫秒|次\s*\/\s*秒|帧)/.test(t),l=e==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&/(?:采集|记录|测量|收集|collect|measure|record)/i.test(t)&&!/(?:预计|预期|估计|约|大约|通常|平均|每(?:隔)?|达到|提升|降低|减少|节省|改善|improve|reduce|faster|expected|estimated|average|typically|every)/i.test(t);a&&!c&&!l&&o.add("unsupported_benefit_percentage"),u&&!l&&o.add("unsupported_performance_number");let m=/(?:requestAnimationFrame|\bRAF\b)/i.test(t),f=/(?:建议|应该|应当|使用|添加|采用|切换|包裹|优化|节流|\buse\b|\badopt\b|\brecommend\b|\bswitch\b|\bwrap\b|\bthrottl(?:e|ing)\b)/i.test(t),p=/(?:不要|不得|不能|不应|避免|不建议|不推荐).{0,16}(?:使用|采用|添加|切换|包裹|节流)?.{0,8}(?:requestAnimationFrame|\bRAF\b)|\b(?:do\s+not|don't|never|avoid)\s+(?:use|adopt|recommend|switch|wrap|throttle)?.{0,8}(?:requestAnimationFrame|RAF)\b/i.test(t);m&&f&&!p&&!n&&o.add("raf_without_sampling_evidence");}function Ao(t,e,n,o){let r=t.slice(Math.max(0,e-64),e),i=t.slice(e+n.length,e+n.length+28),s=ya(r),a=/^(?:\s+)?(?:未发现|不存在|并不存在|未被发现)/.test(i)||/^(?:\s+)?(?:was\s+|is\s+)?not found\b/i.test(i);return s||a?true:o==="high"?/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?)\s*(?:任何|明确的)?\s*P0\s*(?:或|和|及|、)\s*$/i.test(r)||/\b(?:no evidence (?:of|for)|no)\s+P0\s+(?:or|and)\s+$/i.test(r):false}function ya(t){if(/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?|不是|并非|未被)\s*(?:任何|明确的)?\s*(?:(?:问题|发现|证据|项|内容)\s*)?(?:(?:属于|(?:被)?(?:评|判定|认定|标记|列|视|定|归(?:类)?)为)\s*)?$/i.test(t)||/\b(?:no evidence (?:of|for)|no|not|isn't|is\s+not)\s+(?:an?\s+)?(?:(?:issues?|findings?|evidence|items?)\s+)?(?:(?:classified|rated|marked|labelled|labeled)(?:\s+as)?\s+)?$/i.test(t))return true;let n=/(?:不得|不能|不应|不宜|不要)\s*(?:被\s*)?(?:(?:直接|轻易|简单|明确|正式|合理|据此|当前|目前)\s*){0,2}(?:(?:评|判定|认定|标记|列|视|定|归(?:类)?)为|属于)\s*$/i,o=/\b(?:cannot|can't|must not|should not|shouldn't|do not|don't)\s+(?:(?:reasonably|directly|formally|currently)\s+){0,2}(?:be\s+)?(?:classified|labeled|labelled|rated|marked)(?:\s+as)?\s+$/i;return n.test(t)||o.test(t)}function va(t,e,n){let o=t.slice(Math.max(0,e-40),e),r=t.slice(e+n.length,e+n.length+32),i=/(?:是否|待验证|候选|可能|潜在|未观察到|没有观察到|未发现|不存在|无证据(?:表明)?|不能(?:据此)?确认|尚未(?:确认|证明)|验证(?:是否)?|测量(?:是否)?|采集|记录|收集).{0,16}$/i.test(o)||/\b(?:whether|measure|validate|candidate|potential|possible|may|might|no|no evidence(?: of| for)?|not observed|unobserved|collect|record).{0,18}$/i.test(o),s=/^(?:是否|有待验证|待验证|候选|可能|潜在|指标|需要(?:验证|测量)|需(?:验证|测量))/.test(r)||/^(?:\s+)?(?:candidate|potential|possible|metric|metrics|to (?:measure|validate)|needs? (?:measurement|validation)|is (?:a )?(?:candidate|potential))/i.test(r);return i||s}function _a(t){return t.split(/(?:[。!?;;,,]|\b(?:but|however|yet|nevertheless|nonetheless)\b|但是|但|然而|却|不过|可是)/i).map(e=>e.trim()).filter(Boolean)}function ye(t,e,n){if(e>aa||t===null||t===void 0)return null;if(typeof t=="string"){if(Buffer.byteLength(t,"utf8")>oa)return null;try{return ye(JSON.parse(t),e+1,n)}catch{return null}}if(typeof t!="object"||n.has(t))return null;if(n.add(t),Array.isArray(t)){for(let r of t.slice(0,16)){let i=ye(r,e+1,n);if(i)return i}return null}let o=t;if("evidenceContract"in o)return {contract:o.evidenceContract,canonicalReport:o.canonicalReport};for(let r of ["structuredContent","data","result"])if(r in o){let i=ye(o[r],e+1,n);if(i)return i}if(Array.isArray(o.content))for(let r of o.content.slice(0,16)){let i=r&&typeof r=="object"&&"text"in r?r.text:r,s=ye(i,e+1,n);if(s)return s}return null}function Ia(t,e){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t;if(n.version!=="1.0"||typeof n.id!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(n.id)||typeof n.runtimeProfilingOccurred!="boolean"||typeof n.samplingEvidenceOccurred!="boolean"||!Array.isArray(n.requiredSections)||n.requiredSections.length!==he.length)return null;let o=n.requiredSections.filter(c=>typeof c=="string");if(o.length!==he.length||he.some((c,d)=>o[d]!==c)||!Array.isArray(n.prohibitedClaims)||n.prohibitedClaims.length>16)return null;let r=n.prohibitedClaims.filter(c=>typeof c=="string"&&c.length<=128);if(r.length!==n.prohibitedClaims.length)return null;let i=n.correctionPolicy;if(!i||typeof i!="object"||Array.isArray(i))return null;let s=i;if(s.maxAttempts!==1||s.repeatedViolation!=="fail_open")return null;let a=typeof n.canonicalReport=="string"?n.canonicalReport:e;return typeof a!="string"||Buffer.byteLength(a,"utf8")>ra||he.some(c=>!a.includes(c))?null:{version:"1.0",id:n.id,runtimeProfilingOccurred:n.runtimeProfilingOccurred,samplingEvidenceOccurred:n.samplingEvidenceOccurred,requiredSections:o,prohibitedClaims:r,correctionPolicy:{maxAttempts:1,repeatedViolation:"fail_open"},canonicalReport:a}}function Et(t,e){if(!t||t.length>4096)return {degradationReason:"transcript_path_missing"};let n;try{let o=lstatSync$1(t);if(!o.isFile()||o.isSymbolicLink())return {degradationReason:"transcript_path_unsafe"};n=openSync$1(t,constants.O_RDONLY|(constants.O_NOFOLLOW??0));let r=fstatSync$1(n);if(!r.isFile()||r.dev!==o.dev||r.ino!==o.ino)return {degradationReason:"transcript_path_changed"};let i=Math.min(r.size,ia),s=Buffer.alloc(i),a=0;for(;a<i;){let p=readSync(n,s,a,i-a,r.size-i+a);if(p===0)break;a+=p;}let c=s.subarray(0,a).toString("utf8");r.size>i&&(c=c.slice(Math.max(0,c.indexOf(`
13
+ `)+1)));let d=c.split(/\r?\n/).slice(-sa),u=e.length>0?Math.min(...e.map(p=>p.promptedAt)):0,l=ka(d,u),f=[...l].reverse().find(p=>wa(p.text,e))??l.at(-1);return f?.text?{answer:f.text,fingerprint:f.fingerprint}:{degradationReason:"transcript_answer_unavailable"}}catch{return {degradationReason:"transcript_unreadable"}}finally{n!==void 0&&closeSync$1(n);}}function wa(t,e){let n=new Set(e.flatMap(r=>r.contract.requiredSections)),o=Po(Oo(t.split(/\r?\n/u)).headingLines);return [...n].every(r=>o.found.has(r))}function Be(t){return Et(t,[]).answer}function ka(t,e){let n=[];for(let o=0;o<t.length;o++){let r=t[o];if(r.trim())try{let i=JSON.parse(r),s=i.message;if(!s||typeof s!="object"||s.role!=="assistant")continue;let a=s,c=ba(i.timestamp);if(c>0&&c+5e3<e)continue;let d=s.content,u=typeof d=="string"?d:Array.isArray(d)?d.filter(l=>l&&typeof l=="object"&&l.type==="text").map(l=>l.text).filter(l=>typeof l=="string").join(`
14
+ `):"";if(u.trim()){let l=u.trim(),m=typeof a.id=="string"&&a.id?`message:${a.id}`:typeof i.uuid=="string"&&i.uuid?`uuid:${i.uuid}`:`record:${String(i.timestamp??"")}:${o}:${createHash("sha256").update(r).digest("hex")}`,f=createHash("sha256").update(l).digest("hex"),p=createHash("sha256").update(`${m}\0${f}`).digest("hex");n.push({text:l,timestamp:c,fingerprint:p});}}catch{continue}}return n}function ba(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?e:0}function Po(t){let e=new Set,n=new Map,o;for(let r=0;r<t.length;r++){let i=t[r].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=he.find(a=>i===a);s&&(o=s,e.add(s)),n.set(r,o);}return {found:e,byLine:n}}function Fo(t){let e;try{if(Ca(t.toolResponse))return null;e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let n=e.getActiveContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!n)return null;let o=xa(t.toolInput);if(o.length===0)return null;let r=t.toolName==="Read"?Ea(t.toolInput):void 0,i=r?n.selectedFiles?.find(u=>Ta(t.projectRoot,u,r)):void 0,s=Aa(t.toolName),a=i?"code":n.canonicalNextAction===s?"action":null,c=i&&o.includes(i)?i:a==="action"&&o.includes(s)?s:void 0;if(a&&c){let u=[n.contextHash,n.requestId??"",a,c,t.toolUseId??`${t.sessionId}:${t.executionId??n.executionId}`].join("\0");e.recordContextSelectionEvent({id:`ctxsel:${createHash("sha256").update(u).digest("hex").slice(0,32)}`,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId,selectionType:a,candidateId:c,toolName:t.toolName,toolUseId:t.toolUseId,selectedAt:Date.now()});}let d=e.listRetrievalLedgerEvents({projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId}).filter(u=>u.stage==="selected"&&o.includes(u.sourceId));for(let u of d)e.appendRetrievalLedgerEvent({...u,id:retrievalLedgerTransitionId(u.id,"consumed",t.toolUseId??t.toolName),stage:"consumed",toolEvidence:[t.toolUseId??t.toolName],evidenceIds:o,actor:t.toolName,reasonCode:"structural_evidence_ref",payload:{...u.payload,consumedByTool:t.toolName},createdAt:Date.now()});return d.length>0&&ve({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId,contextReceipt:n.contextHash},level:"info",timestamp:Date.now(),data:{stage:"consumed",actor:t.toolName,consumedCount:d.length,evidenceRefCount:o.length}}),a}catch(n){throw ve({event:"hook.runtime.degraded",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:"warn",timestamp:Date.now(),data:{stage:"retrieval_attribution",actor:t.toolName,reason:n instanceof Error?n.message:String(n)}}),n}finally{try{e?.close();}catch{}}}function Ho(t){let e=openGlobalDevFlowDatabase();try{let n=e.listRetrievalLedgerEvents(t),o=new Map(n.filter(l=>l.stage==="selected").map(l=>[jo(l),l])),r=new Map(n.filter(l=>l.stage==="consumed").map(l=>[jo(l),l])),i=0,s=0,a=0;for(let[l,m]of o){let f=r.get(l);f&&t.verificationReceipt&&e.appendRetrievalLedgerEvent({...f,id:retrievalLedgerTransitionId(f.id,"verified",t.verificationReceipt),stage:"verified",verificationReceipt:t.verificationReceipt,reasonCode:"same_task_verification_receipt",createdAt:t.finishedAt??Date.now()});let p=f&&t.verificationReceipt&&t.outcome!=="unknown"?t.outcome:"unknown",g=p==="positive"?"positive_outcome":p==="negative"?"negative_outcome":"unknown_outcome";e.appendRetrievalLedgerEvent({...m,id:retrievalLedgerTransitionId(m.id,g,t.verificationReceipt??t.sessionId),stage:g,reason:f?t.outcomeReason:"selected_not_consumed",toolEvidence:f?.toolEvidence??[],verificationReceipt:p==="unknown"?void 0:t.verificationReceipt,payload:{...m.payload,consumed:!!f},createdAt:t.finishedAt??Date.now()}),g==="positive_outcome"?i+=1:g==="negative_outcome"?s+=1:a+=1;}let c=t.requiredChannels.map(l=>{let m=[...o.values()].filter(p=>p.sourceType===l).length,f=[...r.values()].filter(p=>p.sourceType===l).length;return {channel:l,selected:m,consumed:f,verified:t.verificationReceipt?f:0}}),d={status:c.length>0&&c.every(l=>l.selected>0&&l.consumed===l.selected&&l.verified===l.selected)?"complete":"unavailable",channels:c},u={consumed:r.size,positive:i,negative:s,unknown:a,consumedSources:[...r.values()].map(l=>({sourceType:l.sourceType,sourceId:l.sourceId})),proof:d};return t.verificationReceipt&&r.size>0&&ve({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:"info",timestamp:t.finishedAt??Date.now(),data:{stage:"verified",verifiedCount:r.size}}),ve({event:"task.proof.completed",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:d.status==="complete"?"info":"warn",timestamp:t.finishedAt??Date.now(),data:d}),ve({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:a>0?"warn":"info",timestamp:t.finishedAt??Date.now(),data:{stage:"session_outcome",selectedCount:o.size,consumedCount:r.size,verifiedCount:t.verificationReceipt?r.size:0,positiveCount:i,negativeCount:s,unknownCount:a}}),u}finally{e.close();}}function xa(...t){let e=new Set,n=(o,r=0)=>{if(!(r>6||o==null)){if(typeof o=="string"){try{n(JSON.parse(o),r+1);}catch{}return}if(Array.isArray(o)){for(let i of o)n(i,r+1);return}if(typeof o=="object")for(let[i,s]of Object.entries(o))if((i==="evidenceRefs"||i==="_devflow_evidence_refs")&&Array.isArray(s))for(let a of s)typeof a=="string"&&a.trim()&&e.add(a.trim());else n(s,r+1);}};for(let o of t)n(o);return [...e]}function Ea(t){for(let e of ["file_path","path"]){let n=t[e];if(typeof n=="string"&&n.trim())return n.trim()}}function Ta(t,e,n){let o=resolve(t,e),r=isAbsolute(n)?resolve(n):resolve(t,n);return o===r}function Aa(t){return t.startsWith("mcp__")?t.split("__").at(-1)??t:t}function Ca(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.ok===false||e.success===false||e.isError===true||!!e.error||["failed","rejected","unavailable"].includes(String(e.status??""))}function jo(t){return [t.requestId,t.contextReceipt,t.sourceType,t.sourceId].join("\0")}function ve(t){try{y(t);}catch{}}var Ha=8*1024*1024;function qo(t){if(!t.transcriptPath||!existsSync(t.transcriptPath))return {status:"unavailable",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:"transcript_path_unavailable"};let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=e.getLatestTranscriptCheckpoint({projectRoot:t.projectRoot,hostId:"claude-code",sessionId:t.sessionId,sourcePath:t.transcriptPath}),o=statSync(t.transcriptPath).size,r=Math.min(n?.byteOffset??0,o),i=Math.min(Ha,o-r);if(i<=0)return {status:"completed",eventsRead:0,failuresFound:0,failuresRecorded:0,checkpointId:n?.id};let s=Buffer.alloc(i),a=openSync$1(t.transcriptPath,"r");try{readSync(a,s,0,i,r);}finally{closeSync$1(a);}let c=s.toString("utf8").split(/\r?\n/u).filter(Boolean),d=e.listLatestTaskIntentArtifacts(t.projectRoot,t.sessionId),u=new Map,l=new Set,m=0,f=0;for(let k of c){let b;try{b=JSON.parse(k);}catch{continue}for(let R of Ct(b,u)){let I=claudeCodeRuntimeAdapter.normalizeToolResult(R,{projectRoot:t.projectRoot});if(I.success||!I.error)continue;let F=I.toolUseId??I.sourceHash;if(l.has(F))continue;l.add(F),m++;let T=I.toolUseId?e.getToolCallEventByToolUseId(t.sessionId,I.toolUseId):null,M=No(T?.input,"_devflow_turn_id"),L=No(T?.input,"_devflow_request_id"),S=M?d.find(E=>E.turnId===M):[...d].reverse().find(E=>(!T?.executionId||E.executionId===T.executionId)&&E.createdAt<=(T?.timestamp??I.timestamp))??d.at(-1),A=`host-failure:${I.sourceHash}`;e.insertEvent({kind:"host_transcript_tool_failure",timestamp:I.timestamp,success:!1,toolName:I.canonicalName??I.requestedName,metadata:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:M??S?.turnId,requestId:L??S?.requestId,sourceId:A,toolUseId:I.toolUseId,correlatedEventId:T?.eventId,requestedName:I.requestedName,canonicalName:I.canonicalName,failureCategory:I.failureCategory,error:I.error.slice(0,1e3)}}),y({event:"host.tool.result.reconciled",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:M??S?.turnId,requestId:L??S?.requestId,executionId:T?.executionId},level:"warn",timestamp:Date.now(),data:{toolUseId:I.toolUseId,toolName:I.canonicalName??I.requestedName,failureCategory:I.failureCategory,correlation:T?"tool_use_id":"timestamp_fallback"}}),f++;}}let p=createHash("sha256").update(s).digest("hex"),g=`transcript:${createHash("sha256").update(`${t.projectRoot}\0${t.sessionId}\0${t.transcriptPath}\0${r+i}\0${p}`).digest("hex").slice(0,24)}`;return e.appendTranscriptCheckpoint({id:g,projectRoot:t.projectRoot,hostId:"claude-code",sessionId:t.sessionId,sourcePath:t.transcriptPath,sourceHash:p,byteOffset:r+i,eventCount:c.length,createdAt:Date.now()}),y({event:"session.reconciled",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId},level:m>0?"warn":"info",timestamp:Date.now(),data:{stage:"transcript",eventsRead:c.length,failuresFound:m,failuresRecorded:f,checkpointId:g}}),{status:"completed",eventsRead:c.length,failuresFound:m,failuresRecorded:f,checkpointId:g}}catch(n){return {status:"degraded",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:n instanceof Error?n.message:String(n)}}finally{e.close();}}function No(t,e){let n=t?.[e];return typeof n=="string"&&n.trim()?n.trim():void 0}function Ct(t,e,n=0){if(n>7||t===null||t===void 0)return [];if(Array.isArray(t))return t.flatMap(s=>Ct(s,e,n+1));if(typeof t!="object")return [];let o=t,r=typeof o.type=="string"?o.type:"";r==="tool_use"&&typeof o.id=="string"&&typeof o.name=="string"&&e.set(o.id,o.name);let i=[];if(r==="tool_result"){let s=typeof o.tool_use_id=="string"?o.tool_use_id:void 0;i.push({tool_name:s?e.get(s)??"unknown":"unknown",tool_use_id:s,tool_response:o.content,is_error:o.is_error===true,...o.is_error===true?{error:Dt(o.content)||"host tool result failed"}:{},timestamp:o.timestamp});}else (o.tool_name||o.toolName)&&(o.tool_response!==void 0||o.output!==void 0||o.error!==void 0)&&i.push(o);for(let[s,a]of Object.entries(o))s==="content"&&r==="tool_result"||i.push(...Ct(a,e,n+1));return i}function Dt(t){if(typeof t=="string")return t.slice(0,4e3);if(Array.isArray(t))return t.map(Dt).filter(Boolean).join(`
15
15
  `).slice(0,4e3);if(!t||typeof t!="object")return "";let e=t;return [e.text,e.content,e.message].map(Dt).filter(Boolean).join(`
16
- `).slice(0,4e3)}var Na={open:["intent_bound"],intent_bound:["context_ready","context_degraded"],context_ready:["action_required","action_not_required"],context_degraded:["action_required","action_not_required"],action_required:["action_satisfied","action_degraded","action_failed"],action_not_required:["memory_decided","memory_quarantined"],action_satisfied:["memory_decided","memory_quarantined"],action_degraded:["memory_decided","memory_quarantined"],action_failed:["action_satisfied","action_degraded"],memory_decided:["closed","closed_with_degradation","closed_with_retry_work"],memory_quarantined:["closed_with_degradation","closed_with_retry_work"],closed:[],closed_with_degradation:[],closed_with_retry_work:[]};function Wo(t){return qa(t)}function qa(t){let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=Ba(e,t.artifact);if(Ja(n.toState))return n;let o=e.getContextReceiptForRequest(t.artifact.projectRoot,t.artifact.sessionId,t.artifact.requestId),r=e.getMemoryTurn(t.artifact.turnId),i=t.artifact.intent==="memory"||r?.source==="explicit_intent";if(!o&&!i)return n;let s=o?Wa(t.artifact,o):"context_ready";n.toState==="intent_bound"&&(n=j(e,n,t,s,i?"task_context_not_required":s==="context_ready"?"canonical_context_receipt_ready":"canonical_context_receipt_degraded"));let a=o?Ua(t.artifact,o):"action_not_required";if((n.toState==="context_ready"||n.toState==="context_degraded")&&(a==="action_not_required"?n=j(e,n,t,"action_not_required","task_action_not_required"):n=j(e,n,t,"action_required","canonical_action_obligation_present")),n.toState==="action_required"){if(a==="action_required")return n;if(a==="action_failed")return j(e,n,t,"action_failed","canonical_action_attempt_failed");a==="action_degraded"?n=j(e,n,t,"action_degraded","canonical_action_unavailable_or_degraded"):a==="action_satisfied"&&(n=j(e,n,t,"action_satisfied","canonical_action_succeeded"));}if(n.toState==="action_failed")if(a==="action_satisfied")n=j(e,n,t,"action_satisfied","canonical_action_retry_succeeded");else if(a==="action_degraded")n=j(e,n,t,"action_degraded","canonical_action_retry_degraded");else return n;let c=s==="context_degraded"||a==="action_degraded";return ["action_not_required","action_satisfied","action_degraded"].includes(n.toState)&&(n=j(e,n,t,t.memoryStatus==="pending"?"memory_quarantined":"memory_decided",t.memoryStatus==="pending"?t.reason:`canonical_memory_${t.memoryStatus}`)),n.toState==="memory_decided"?j(e,n,t,c?"closed_with_degradation":"closed",t.reason):n.toState==="memory_quarantined"?j(e,n,t,t.retryOwned?"closed_with_retry_work":"closed_with_degradation",t.retryOwned?"durable_retry_owner_confirmed":"terminal_obligation_unowned"):n}finally{e.close();}}function Wa(t,e){return t.intent==="memory"||t.intent==="knowledge"||(e.selectedFiles?.length??0)>0?"context_ready":"context_degraded"}function Ua(t,e){let n=e.canonicalAction,r=(n?(e.actionAttempts??[]).filter(i=>i.tool===n.tool):[]).at(-1);return e.actionSatisfiedAt||r?.status==="succeeded"?"action_satisfied":r&&["failed","timeout","unavailable"].includes(r.status)?"action_failed":e.actionDegradation||n?.status==="degraded"||n?.status==="unsupported"?"action_degraded":n?.required||za(t)?"action_required":"action_not_required"}function za(t){return ["create","modify","debug","test","format"].includes(t.action)||["feature","refactor","performance"].includes(t.intent)}function Ba(t,e){let n=t.getLatestTerminalTransition(e.projectRoot,e.sessionId,e.turnId);if(!n)throw new Error(`TERMINAL_INTENT_STATE_MISSING:${e.turnId}`);return n}function j(t,e,n,o,r){if(!Na[e.toState]?.includes(o))throw new Error(`TERMINAL_PATH_UNAVAILABLE:${e.toState}->${o}`);let i=e.sequence+1,s=`terminal:${createHash("sha256").update(`${n.artifact.artifactHash}\0${i}\0${o}`).digest("hex").slice(0,24)}`,a=t.appendTerminalTransition({projectRoot:n.artifact.projectRoot,projectId:n.artifact.projectId,hostId:n.artifact.hostId,sessionId:n.artifact.sessionId,turnId:n.artifact.turnId,requestId:n.artifact.requestId,executionId:n.artifact.executionId,sequence:i,fromState:e.toState,toState:o,receiptId:s,sourceReceiptId:n.memoryReceiptId??e.receiptId,reason:r,payload:{memoryStatus:n.memoryStatus,retryOwned:n.retryOwned??false,sourceIntentHash:n.artifact.artifactHash},createdAt:Date.now()});return y({event:"terminal.state.transitioned",identity:{projectRoot:n.artifact.projectRoot,projectId:n.artifact.projectId,hostId:n.artifact.hostId,sessionId:n.artifact.sessionId,turnId:n.artifact.turnId,requestId:n.artifact.requestId,...n.artifact.executionId?{executionId:n.artifact.executionId}:{}},level:o==="closed"?"info":o.includes("degradation")||o.includes("retry")||o==="action_failed"?"warn":"info",timestamp:Date.now(),data:{fromState:e.toState,nextState:o,receiptId:s,reason:r}}),a}function Ja(t){return t==="closed"||t==="closed_with_degradation"||t==="closed_with_retry_work"}function Mt(t){let e={committed:0,skipped:0,pending:0},n=[];for(let o of t)e[o.status]+=1,o.receiptId&&n.push(o.receiptId);return {memoryReceiptIds:[...new Set(n)],missingMemoryDecisionCount:e.pending,memoryTurnOutcomes:e}}function $(t){return (t instanceof Error?t.message:String(t)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var K=class extends Error{constructor(e,n){super(`session_finalize_${e}:${n}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${e}`;}};function _e(t){let e;try{e=openGlobalDevFlowDatabase();let n=(t.executionId?e.getSkillExecution(t.executionId):null)??e.getLatestSkillExecutionForSession(t.sessionId),o={stage:t.stage,reason:t.reason,degradedAt:Date.now()};n&&e.mergeSkillExecutionMetadata(n.executionId,{...t.metadata,sessionFinalizationDegradations:[o]}),e.insertEvent({kind:"session_finalize_degraded",timestamp:o.degradedAt,success:!1,metadata:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n?.executionId,...o}}),y({event:"hook.session_end.degraded",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n?.executionId},level:"warn",timestamp:o.degradedAt,data:{stage:t.stage,reason:t.reason}});}catch{}finally{e?.close();}}function Je(t,e=Me(),n=true,o,r=true){let i;try{i=JSON.parse(t);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${e}\0${s}`).digest("hex").slice(0,24)}`,c={inputJson:t,sessionId:s,cleanupSharedState:n,executionId:o},d;try{d=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let u=d.requestSessionClosure({receiptId:a,projectRoot:e,sessionId:s,payload:c}),l=d.getWorkByIdempotencyKey(a),m={status:u.state==="closed"||u.state==="closed_with_pending_work"?"completed":"accepted",receiptId:a,workState:l?.state??"pending",closureState:u.state,pendingWorkCount:u.pendingWorkCount,...l?.id?{workItemId:l.id}:{}};return y({event:"hook.session_end.completed",identity:{projectRoot:e,sessionId:s,executionId:o,terminalReceipt:a},level:m.status==="completed"?"info":"debug",timestamp:Date.now(),data:{stage:"enqueue",...m}}),m}catch(u){if(!r)throw u;return ko(e,{receiptId:a,...c}),y({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:s,executionId:o,terminalReceipt:a},level:"warn",timestamp:Date.now(),data:{stage:"enqueue",reason:$(u),fallback:"durable_spool"}}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{d?.close();}}async function zo(t,e=Me(),n=true,o){let r;try{r=JSON.parse(t);}catch{return}let i=r.session_id?.trim();if(!i)return;let s=new q(e),a=s.get(i),c=qo({projectRoot:e,sessionId:i,transcriptPath:r.transcript_path}),d={evidenceDegradations:a?.evidenceDegradations??[],evidenceContractOutcomes:a?.evidenceOutcomes??[],pendingEvidenceContractIds:a?.evidenceObligations.map(p=>p.contractId)??[],transcriptReconciliation:c},u=o?.telemetry??new Z,l=!o?.telemetry,m=false,f;try{try{await u.flushAndAggregate();}catch{}let p=Date.now(),g=o?.executionId??a?.executionId,k;try{let _=openGlobalDevFlowDatabase();try{k=_.listSessionMemoryTurnsForReconciliation(e,i);for(let h of k){let w=`memory:${h.turnId}`,v=_.getSessionObligation(e,i,w);v?v.state==="open"&&h.status!=="pending"&&_.resolveSessionObligation({projectRoot:e,sessionId:i,obligationId:w,state:"satisfied",receiptId:h.receiptId,reason:h.reason,resolvedAt:h.decidedAt}):_.upsertSessionObligation({obligationId:w,projectRoot:e,sessionId:i,turnId:h.turnId,kind:"memory_decision",state:h.status==="pending"?"open":"satisfied",payload:{eventId:h.eventId,promptHash:h.promptHash},receiptId:h.receiptId,reason:h.reason,createdAt:h.createdAt,updatedAt:h.decidedAt??h.createdAt,resolvedAt:h.decidedAt});}}finally{_.close();}}catch(_){let h=$(_),w={...d,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:h,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw _e({projectRoot:e,sessionId:i,executionId:g,stage:"turn_load",reason:h,metadata:w}),new K("turn_load",h)}let b=Mt(k),R=o?.memory??(f=new MemoryGate(e)),I={status:"completed"};try{I=typeof R.reconcileTurnObservationLineage=="function"?{status:"completed",...await R.reconcileTurnObservationLineage(k)}:{status:"unsupported_adapter",committed:0,skipped:0,quarantined:0,unlinked:0};}catch(_){let h=$(_);throw I={status:"degraded",reason:h},_e({projectRoot:e,sessionId:i,executionId:g,stage:"memory_lineage",reason:h,metadata:{...b,...d,memoryLineageReconciliation:I}}),new K("memory_lineage",h)}let F={status:"unknown",selected:0,consumed:0,unknown:0,positive:0,negative:0};try{let _=Be(r.transcript_path),h=openGlobalDevFlowDatabase(),w="unknown",v="no_terminal_host_action_evidence",de,H,N,Y=[],lt=[];try{let z=h.listHostActionsForSession(e,i,g),bn=z.filter(D=>D.state==="verified"),ut=z.filter(D=>["failed","cancelled","degraded"].includes(D.state));ut.length>0?(w="negative",v=`terminal_host_action_${ut[0].state}`):bn.length>0&&(w="positive",v="host_action_verified");let Ae=ut[0]??bn.at(-1);if(de=Ae?.runId,H=Ae?.contextReceipt,N=Ae?.evidenceHash,lt=z.flatMap(D=>{let X=D.report.toolUseIds;return Array.isArray(X)?X.filter(le=>typeof le=="string"):[]}),!Ae&&g){let D=h.getSkillExecution(g),X=D?.metadata&&typeof D.metadata=="object"&&Array.isArray(D.metadata.policyVerificationOutcomes)?D.metadata.policyVerificationOutcomes:[],le=X.find(B=>B.status==="failed"),mt=X.filter(B=>B.status==="passed");le?(w="negative",v="policy_verification_failed",N=typeof le.receiptId=="string"?le.receiptId:void 0):mt.length>0&&(w="positive",v="policy_verification_passed",N=typeof mt.at(-1)?.receiptId=="string"?String(mt.at(-1).receiptId):void 0),H=h.getActiveContextReceipt(e,i,g)?.contextHash,lt=X.map(B=>B.command).filter(B=>typeof B=="string");}H&&(Y=h.getSemanticExecutionContextByHash(H)?.dispositions.filter(D=>D.requirement==="required").map(D=>D.channel)??[]);}finally{h.close();}let kn=Ho({projectRoot:e,sessionId:i,executionId:g,outcome:w,outcomeReason:v,verificationReceipt:N,requiredChannels:Y,finishedAt:p}),gi=await R.attributeRetrievalBenefits({sessionId:i,executionId:g,outcome:w,outcomeReason:v,workflowRunId:de,contextReceipt:H,toolEvidence:lt,verificationReceipt:N,consumedSourceIds:kn.consumedSources.filter(z=>z.sourceType==="memory").map(z=>z.sourceId)});F={status:_?"evaluated":"unknown",...gi,retrievalLedger:kn};}catch(_){F={...F,status:"degraded",reason:$(_)};}let T;try{T=await R.reconcileDecidedTurnEventWindows(i,k,p);}catch(_){let h=$(_),w={...b,...d,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:h,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw _e({projectRoot:e,sessionId:i,executionId:g,stage:"event_reconciliation",reason:h,metadata:w}),new K("event_reconciliation",h)}let M;try{M=await ge({projectRoot:e,sessionId:i,trigger:"session_end",memory:R,details:{eventReconciliation:T},strictPersistence:!0});}catch(_){let h=$(_),w={...b,...d,memoryEventReconciliation:{status:"completed",...T,checkpointPending:null},memoryCheckpointDegradation:h};throw _e({projectRoot:e,sessionId:i,executionId:g,stage:"checkpoint",reason:h,metadata:w}),new K("checkpoint",h)}let L={memoryLineageReconciliation:I,memoryBenefitAttribution:F,memoryEventReconciliation:{status:"completed",...T,checkpointPending:M.pendingEvents},memoryDistillCheckpoint:M};try{let _=openGlobalDevFlowDatabase();try{let h=`session-finalize:${i}:events`,w=Math.max(Number(M.pendingEvents??0),Number(T.remainingUndecided??0)),v=_.getSessionObligation(e,i,h);w>0?_.upsertSessionObligation({obligationId:h,projectRoot:e,sessionId:i,executionId:g,kind:"session_finalize",state:"open",payload:{pendingEvents:w,reconciliation:T,checkpointId:M.id},reason:"active_unprocessed_session_events",createdAt:v?.createdAt??p,updatedAt:p}):v?.state==="open"&&_.resolveSessionObligation({projectRoot:e,sessionId:i,obligationId:h,state:"satisfied",reason:"session_events_reconciled",resolvedAt:p});}finally{_.close();}}catch(_){y({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"obligation_persistence",reason:$(_)}});}try{await R.closeSession(i),f&&(f.close(),f=void 0);}catch(_){let h=$(_),w={...b,...d,...L,memorySessionCloseDegradation:h};throw _e({projectRoot:e,sessionId:i,executionId:g,stage:"memory_close",reason:h,metadata:w}),new K("memory_close",h)}let S={...b,...d,...L},A=[];try{let _=openGlobalDevFlowDatabase();try{let h=new Map(_.listLatestTaskIntentArtifacts(e,i).map(w=>[w.turnId,w]));for(let w of k){let v=h.get(w.turnId);if(!v)continue;let H=[_.getWorkByIdempotencyKey(`memory-turn:capture_prompt:${w.turnId}`),_.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${w.turnId}`)].filter(Boolean).some(Y=>Y.state==="pending"||Y.state==="leased"||Y.state==="failed"),N=Wo({artifact:v,memoryStatus:w.status,memoryReceiptId:w.receiptId,retryOwned:H,reason:w.status==="pending"?"session_end_memory_pending":"session_end_reconciled"});A.push({turnId:w.turnId,state:N.toState,receiptId:N.receiptId});}}finally{_.close();}}catch(_){A.push({state:"terminal_integrity_failure",reason:$(_)});}S.terminalOutcomes=A,m=!0;let E;try{E=openGlobalDevFlowDatabase();let _=g;if(_)try{E.reconcileSkillExecution(_,"completed",p,S);let v=E.getSkillExecution(_);await J("/api/telemetry/skill-execution/complete",{executionId:_,finishedAt:p,status:"completed",summary:{totalToolCalls:v?.totalToolCalls??0,mcpToolCalls:v?.mcpToolCalls??0,directToolCalls:v?.directToolCalls??0,subagentCount:v?.subagentCount??0,totalDuration:v?.totalDuration??0,mcpComplianceRate:v?.mcpComplianceRate??0,missedTools:v?.missedMcpTools??[],actualFailureCount:v?.failedToolCalls??0,fallbackCount:v?.fallbackCount??0,fallbackReasons:v?.fallbackReasons??[]},metadata:S},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let h=E.reconcileRunningSkillExecutionsForSession(i,p,{closureReason:"session_finalize",...S});for(let v of h)await J("/api/telemetry/skill-execution/complete",{executionId:v.executionId,finishedAt:v.finishedAt,status:v.status,summary:{totalToolCalls:v.totalToolCalls??0,mcpToolCalls:v.mcpToolCalls??0,directToolCalls:v.directToolCalls??0,subagentCount:v.subagentCount??0,totalDuration:v.totalDuration??0,mcpComplianceRate:v.mcpComplianceRate??0,missedTools:v.missedMcpTools??[],actualFailureCount:v.failedToolCalls??0,fallbackCount:v.fallbackCount??0,fallbackReasons:v.fallbackReasons??[]},metadata:S},{fallbackReason:"skill_execution_already_reconciled_locally"});let w=E.getLatestSkillExecutionForSession(i);if(w&&!h.some(v=>v.executionId===w.executionId)&&E.mergeSkillExecutionMetadata(w.executionId,S),n){E.deleteHookReceipt(e);let v=P(e),de=createHash("sha256").update(e).digest("hex").slice(0,12);for(let H of [`session-id-${de}`,"current-execution-id","current-skill.json","event-map.json"])rmSync$1(join(v,H),{force:!0});}E.deleteContextReceipt(e,i);}catch(_){y({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"lifecycle_telemetry",reason:$(_),fallback:"fail_open"}});}finally{E?.close();}try{await u.endSession(i),await u.flushAndAggregate();}catch(_){y({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"telemetry_flush",reason:$(_),fallback:"local_state_authoritative"}});}}finally{if(f)try{f.close();}catch{}l&&u.close(),m&&s.removeSession(i),y({event:m?"hook.session_end.completed":"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:o?.executionId??a?.executionId},level:m?"info":"warn",timestamp:Date.now(),data:{stage:"finalize",criticalStagesCompleted:m,transcriptStatus:c.status}});}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let t=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",n=>{e+=n;}),process.stdin.on("end",async()=>{let n=Je(e.trim()||process.argv[2]||"");n&&t(JSON.stringify(n)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var tc=/^\/(?:devflow:)?[\w-]+\b\s*/iu,nc=/\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,oc=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,rc=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function Ie(t){let e=t.trim().replace(tc,"").trim();return !e||nc.test(e)?null:(rc.exec(e)??oc.exec(e))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}function ic(t){return join(getProjectStateDir(t),"memory-intents.jsonl")}function sc(t){try{return readFileSync$1(t,"utf8").split(`
17
- `).filter(Boolean).flatMap(e=>{try{let n=JSON.parse(e);return typeof n.content=="string"&&typeof n.createdAt=="number"?[n]:[]}catch{return []}})}catch{return []}}function Go(t){let e=ic(t),n=`${e}.claim-`,o=`${basename(e)}.claim-`,r=(()=>{try{return readdirSync$1(dirname$1(e)).filter(a=>a.startsWith(o)&&!a.includes(".tmp-")).sort()[0]}catch{return}})(),i=r?join(dirname$1(e),r):`${n}${Date.now()}-${process.pid}`;if(!r)try{renameSync(e,i);}catch{return null}let s=sc(i);if(s.length===0){try{unlinkSync$1(i);}catch{}return null}return {path:i,intents:s}}function Ot(t){if(t.intents.shift(),t.intents.length===0){try{unlinkSync$1(t.path);}catch{}return}let e=`${t.path}.tmp-${process.pid}`;writeFileSync$1(e,t.intents.map(n=>JSON.stringify(n)).join(`
16
+ `).slice(0,4e3)}var qa={open:["intent_bound"],intent_bound:["context_ready","context_degraded"],context_ready:["action_required","action_not_required"],context_degraded:["action_required","action_not_required"],action_required:["action_satisfied","action_degraded","action_failed"],action_not_required:["memory_decided","memory_quarantined"],action_satisfied:["memory_decided","memory_quarantined"],action_degraded:["memory_decided","memory_quarantined"],action_failed:["action_satisfied","action_degraded"],memory_decided:["closed","closed_with_degradation","closed_with_retry_work"],memory_quarantined:["closed_with_degradation","closed_with_retry_work"],closed:[],closed_with_degradation:[],closed_with_retry_work:[]};function Wo(t){return Wa(t)}function Wa(t){let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=Ja(e,t.artifact);if(Va(n.toState))return n;let o=e.getContextReceiptForRequest(t.artifact.projectRoot,t.artifact.sessionId,t.artifact.requestId),r=e.getMemoryTurn(t.artifact.turnId),i=t.artifact.intent==="memory"||r?.source==="explicit_intent";if(!o&&!i)return n;let s=o?Ua(t.artifact,o):"context_ready";n.toState==="intent_bound"&&(n=j(e,n,t,s,i?"task_context_not_required":s==="context_ready"?"canonical_context_receipt_ready":"canonical_context_receipt_degraded"));let a=o?za(t.artifact,o):"action_not_required";if((n.toState==="context_ready"||n.toState==="context_degraded")&&(a==="action_not_required"?n=j(e,n,t,"action_not_required","task_action_not_required"):n=j(e,n,t,"action_required","canonical_action_obligation_present")),n.toState==="action_required"){if(a==="action_required")return n;if(a==="action_failed")return j(e,n,t,"action_failed","canonical_action_attempt_failed");a==="action_degraded"?n=j(e,n,t,"action_degraded","canonical_action_unavailable_or_degraded"):a==="action_satisfied"&&(n=j(e,n,t,"action_satisfied","canonical_action_succeeded"));}if(n.toState==="action_failed")if(a==="action_satisfied")n=j(e,n,t,"action_satisfied","canonical_action_retry_succeeded");else if(a==="action_degraded")n=j(e,n,t,"action_degraded","canonical_action_retry_degraded");else return n;let c=s==="context_degraded"||a==="action_degraded";return ["action_not_required","action_satisfied","action_degraded"].includes(n.toState)&&(n=j(e,n,t,t.memoryStatus==="pending"?"memory_quarantined":"memory_decided",t.memoryStatus==="pending"?t.reason:`canonical_memory_${t.memoryStatus}`)),n.toState==="memory_decided"?j(e,n,t,c?"closed_with_degradation":"closed",t.reason):n.toState==="memory_quarantined"?j(e,n,t,t.retryOwned?"closed_with_retry_work":"closed_with_degradation",t.retryOwned?"durable_retry_owner_confirmed":"terminal_obligation_unowned"):n}finally{e.close();}}function Ua(t,e){return t.intent==="memory"||t.intent==="knowledge"||(e.selectedFiles?.length??0)>0?"context_ready":"context_degraded"}function za(t,e){let n=e.canonicalAction,r=(n?(e.actionAttempts??[]).filter(i=>i.tool===n.tool):[]).at(-1);return e.actionSatisfiedAt||r?.status==="succeeded"?"action_satisfied":r&&["failed","timeout","unavailable"].includes(r.status)?"action_failed":e.actionDegradation||n?.status==="degraded"||n?.status==="unsupported"?"action_degraded":n?.required||Ba(t)?"action_required":"action_not_required"}function Ba(t){return ["create","modify","debug","test","format"].includes(t.action)||["feature","refactor","performance"].includes(t.intent)}function Ja(t,e){let n=t.getLatestTerminalTransition(e.projectRoot,e.sessionId,e.turnId);if(!n)throw new Error(`TERMINAL_INTENT_STATE_MISSING:${e.turnId}`);return n}function j(t,e,n,o,r){if(!qa[e.toState]?.includes(o))throw new Error(`TERMINAL_PATH_UNAVAILABLE:${e.toState}->${o}`);let i=e.sequence+1,s=`terminal:${createHash("sha256").update(`${n.artifact.artifactHash}\0${i}\0${o}`).digest("hex").slice(0,24)}`,a=t.appendTerminalTransition({projectRoot:n.artifact.projectRoot,projectId:n.artifact.projectId,hostId:n.artifact.hostId,sessionId:n.artifact.sessionId,turnId:n.artifact.turnId,requestId:n.artifact.requestId,executionId:n.artifact.executionId,sequence:i,fromState:e.toState,toState:o,receiptId:s,sourceReceiptId:n.memoryReceiptId??e.receiptId,reason:r,payload:{memoryStatus:n.memoryStatus,retryOwned:n.retryOwned??false,sourceIntentHash:n.artifact.artifactHash},createdAt:Date.now()});return y({event:"terminal.state.transitioned",identity:{projectRoot:n.artifact.projectRoot,projectId:n.artifact.projectId,hostId:n.artifact.hostId,sessionId:n.artifact.sessionId,turnId:n.artifact.turnId,requestId:n.artifact.requestId,...n.artifact.executionId?{executionId:n.artifact.executionId}:{}},level:o==="closed"?"info":o.includes("degradation")||o.includes("retry")||o==="action_failed"?"warn":"info",timestamp:Date.now(),data:{fromState:e.toState,nextState:o,receiptId:s,reason:r}}),a}function Va(t){return t==="closed"||t==="closed_with_degradation"||t==="closed_with_retry_work"}function Mt(t){let e={committed:0,skipped:0,pending:0},n=[];for(let o of t)e[o.status]+=1,o.receiptId&&n.push(o.receiptId);return {memoryReceiptIds:[...new Set(n)],missingMemoryDecisionCount:e.pending,memoryTurnOutcomes:e}}function $(t){return (t instanceof Error?t.message:String(t)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var K=class extends Error{constructor(e,n){super(`session_finalize_${e}:${n}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${e}`;}};function _e(t){let e;try{e=openGlobalDevFlowDatabase();let n=(t.executionId?e.getSkillExecution(t.executionId):null)??e.getLatestSkillExecutionForSession(t.sessionId),o={stage:t.stage,reason:t.reason,degradedAt:Date.now()};n&&e.mergeSkillExecutionMetadata(n.executionId,{...t.metadata,sessionFinalizationDegradations:[o]}),e.insertEvent({kind:"session_finalize_degraded",timestamp:o.degradedAt,success:!1,metadata:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n?.executionId,...o}}),y({event:"hook.session_end.degraded",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n?.executionId},level:"warn",timestamp:o.degradedAt,data:{stage:t.stage,reason:t.reason}});}catch{}finally{e?.close();}}function Je(t,e=Me(),n=true,o,r=true){let i;try{i=JSON.parse(t);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${e}\0${s}`).digest("hex").slice(0,24)}`,c={inputJson:t,sessionId:s,cleanupSharedState:n,executionId:o},d;try{d=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let u=d.requestSessionClosure({receiptId:a,projectRoot:e,sessionId:s,payload:c}),l=d.getWorkByIdempotencyKey(a),m={status:u.state==="closed"||u.state==="closed_with_pending_work"?"completed":"accepted",receiptId:a,workState:l?.state??"pending",closureState:u.state,pendingWorkCount:u.pendingWorkCount,...l?.id?{workItemId:l.id}:{}};return y({event:"hook.session_end.completed",identity:{projectRoot:e,sessionId:s,executionId:o,terminalReceipt:a},level:m.status==="completed"?"info":"debug",timestamp:Date.now(),data:{stage:"enqueue",...m}}),m}catch(u){if(!r)throw u;return ko(e,{receiptId:a,...c}),y({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:s,executionId:o,terminalReceipt:a},level:"warn",timestamp:Date.now(),data:{stage:"enqueue",reason:$(u),fallback:"durable_spool"}}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{d?.close();}}async function zo(t,e=Me(),n=true,o){let r;try{r=JSON.parse(t);}catch{return}let i=r.session_id?.trim();if(!i)return;let s=new q(e),a=s.get(i),c=qo({projectRoot:e,sessionId:i,transcriptPath:r.transcript_path}),d={evidenceDegradations:a?.evidenceDegradations??[],evidenceContractOutcomes:a?.evidenceOutcomes??[],pendingEvidenceContractIds:a?.evidenceObligations.map(p=>p.contractId)??[],transcriptReconciliation:c},u=o?.telemetry??new Z,l=!o?.telemetry,m=false,f;try{try{await u.flushAndAggregate();}catch{}let p=Date.now(),g=o?.executionId??a?.executionId,k;try{let _=openGlobalDevFlowDatabase();try{k=_.listSessionMemoryTurnsForReconciliation(e,i);for(let h of k){let w=`memory:${h.turnId}`,v=_.getSessionObligation(e,i,w);v?v.state==="open"&&h.status!=="pending"&&_.resolveSessionObligation({projectRoot:e,sessionId:i,obligationId:w,state:"satisfied",receiptId:h.receiptId,reason:h.reason,resolvedAt:h.decidedAt}):_.upsertSessionObligation({obligationId:w,projectRoot:e,sessionId:i,turnId:h.turnId,kind:"memory_decision",state:h.status==="pending"?"open":"satisfied",payload:{eventId:h.eventId,promptHash:h.promptHash},receiptId:h.receiptId,reason:h.reason,createdAt:h.createdAt,updatedAt:h.decidedAt??h.createdAt,resolvedAt:h.decidedAt});}}finally{_.close();}}catch(_){let h=$(_),w={...d,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:h,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw _e({projectRoot:e,sessionId:i,executionId:g,stage:"turn_load",reason:h,metadata:w}),new K("turn_load",h)}let b=Mt(k),R=o?.memory??(f=new MemoryGate(e)),I={status:"completed"};try{I=typeof R.reconcileTurnObservationLineage=="function"?{status:"completed",...await R.reconcileTurnObservationLineage(k)}:{status:"unsupported_adapter",committed:0,skipped:0,quarantined:0,unlinked:0};}catch(_){let h=$(_);throw I={status:"degraded",reason:h},_e({projectRoot:e,sessionId:i,executionId:g,stage:"memory_lineage",reason:h,metadata:{...b,...d,memoryLineageReconciliation:I}}),new K("memory_lineage",h)}let F={status:"unknown",selected:0,consumed:0,unknown:0,positive:0,negative:0};try{let _=Be(r.transcript_path),h=openGlobalDevFlowDatabase(),w="unknown",v="no_terminal_host_action_evidence",de,H,N,Y=[],lt=[];try{let z=h.listHostActionsForSession(e,i,g),bn=z.filter(D=>D.state==="verified"),ut=z.filter(D=>["failed","cancelled","degraded"].includes(D.state));ut.length>0?(w="negative",v=`terminal_host_action_${ut[0].state}`):bn.length>0&&(w="positive",v="host_action_verified");let Ae=ut[0]??bn.at(-1);if(de=Ae?.runId,H=Ae?.contextReceipt,N=Ae?.evidenceHash,lt=z.flatMap(D=>{let X=D.report.toolUseIds;return Array.isArray(X)?X.filter(le=>typeof le=="string"):[]}),!Ae&&g){let D=h.getSkillExecution(g),X=D?.metadata&&typeof D.metadata=="object"&&Array.isArray(D.metadata.policyVerificationOutcomes)?D.metadata.policyVerificationOutcomes:[],le=X.find(B=>B.status==="failed"),mt=X.filter(B=>B.status==="passed");le?(w="negative",v="policy_verification_failed",N=typeof le.receiptId=="string"?le.receiptId:void 0):mt.length>0&&(w="positive",v="policy_verification_passed",N=typeof mt.at(-1)?.receiptId=="string"?String(mt.at(-1).receiptId):void 0),H=h.getActiveContextReceipt(e,i,g)?.contextHash,lt=X.map(B=>B.command).filter(B=>typeof B=="string");}H&&(Y=h.getSemanticExecutionContextByHash(H)?.dispositions.filter(D=>D.requirement==="required").map(D=>D.channel)??[]);}finally{h.close();}let kn=Ho({projectRoot:e,sessionId:i,executionId:g,outcome:w,outcomeReason:v,verificationReceipt:N,requiredChannels:Y,finishedAt:p}),gi=await R.attributeRetrievalBenefits({sessionId:i,executionId:g,outcome:w,outcomeReason:v,workflowRunId:de,contextReceipt:H,toolEvidence:lt,verificationReceipt:N,consumedSourceIds:kn.consumedSources.filter(z=>z.sourceType==="memory").map(z=>z.sourceId)});F={status:_?"evaluated":"unknown",...gi,retrievalLedger:kn};}catch(_){F={...F,status:"degraded",reason:$(_)};}let T;try{T=await R.reconcileDecidedTurnEventWindows(i,k,p);}catch(_){let h=$(_),w={...b,...d,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:h,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw _e({projectRoot:e,sessionId:i,executionId:g,stage:"event_reconciliation",reason:h,metadata:w}),new K("event_reconciliation",h)}let M;try{M=await ge({projectRoot:e,sessionId:i,trigger:"session_end",memory:R,details:{eventReconciliation:T},strictPersistence:!0});}catch(_){let h=$(_),w={...b,...d,memoryEventReconciliation:{status:"completed",...T,checkpointPending:null},memoryCheckpointDegradation:h};throw _e({projectRoot:e,sessionId:i,executionId:g,stage:"checkpoint",reason:h,metadata:w}),new K("checkpoint",h)}let L={memoryLineageReconciliation:I,memoryBenefitAttribution:F,memoryEventReconciliation:{status:"completed",...T,checkpointPending:M.pendingEvents},memoryDistillCheckpoint:M};try{let _=openGlobalDevFlowDatabase();try{let h=`session-finalize:${i}:events`,w=Math.max(Number(M.pendingEvents??0),Number(T.remainingUndecided??0)),v=_.getSessionObligation(e,i,h);w>0?_.upsertSessionObligation({obligationId:h,projectRoot:e,sessionId:i,executionId:g,kind:"session_finalize",state:"open",payload:{pendingEvents:w,reconciliation:T,checkpointId:M.id},reason:"active_unprocessed_session_events",createdAt:v?.createdAt??p,updatedAt:p}):v?.state==="open"&&_.resolveSessionObligation({projectRoot:e,sessionId:i,obligationId:h,state:"satisfied",reason:"session_events_reconciled",resolvedAt:p});}finally{_.close();}}catch(_){y({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"obligation_persistence",reason:$(_)}});}try{await R.closeSession(i),f&&(f.close(),f=void 0);}catch(_){let h=$(_),w={...b,...d,...L,memorySessionCloseDegradation:h};throw _e({projectRoot:e,sessionId:i,executionId:g,stage:"memory_close",reason:h,metadata:w}),new K("memory_close",h)}let S={...b,...d,...L},A=[];try{let _=openGlobalDevFlowDatabase();try{let h=new Map(_.listLatestTaskIntentArtifacts(e,i).map(w=>[w.turnId,w]));for(let w of k){let v=h.get(w.turnId);if(!v)continue;let H=[_.getWorkByIdempotencyKey(`memory-turn:capture_prompt:${w.turnId}`),_.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${w.turnId}`)].filter(Boolean).some(Y=>Y.state==="pending"||Y.state==="leased"||Y.state==="failed"),N=Wo({artifact:v,memoryStatus:w.status,memoryReceiptId:w.receiptId,retryOwned:H,reason:w.status==="pending"?"session_end_memory_pending":"session_end_reconciled"});A.push({turnId:w.turnId,state:N.toState,receiptId:N.receiptId});}}finally{_.close();}}catch(_){A.push({state:"terminal_integrity_failure",reason:$(_)});}S.terminalOutcomes=A,m=!0;let E;try{E=openGlobalDevFlowDatabase();let _=g;if(_)try{E.reconcileSkillExecution(_,"completed",p,S);let v=E.getSkillExecution(_);await J("/api/telemetry/skill-execution/complete",{executionId:_,finishedAt:p,status:"completed",summary:{totalToolCalls:v?.totalToolCalls??0,mcpToolCalls:v?.mcpToolCalls??0,directToolCalls:v?.directToolCalls??0,subagentCount:v?.subagentCount??0,totalDuration:v?.totalDuration??0,mcpComplianceRate:v?.mcpComplianceRate??0,missedTools:v?.missedMcpTools??[],actualFailureCount:v?.failedToolCalls??0,fallbackCount:v?.fallbackCount??0,fallbackReasons:v?.fallbackReasons??[]},metadata:S},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let h=E.reconcileRunningSkillExecutionsForSession(i,p,{closureReason:"session_finalize",...S});for(let v of h)await J("/api/telemetry/skill-execution/complete",{executionId:v.executionId,finishedAt:v.finishedAt,status:v.status,summary:{totalToolCalls:v.totalToolCalls??0,mcpToolCalls:v.mcpToolCalls??0,directToolCalls:v.directToolCalls??0,subagentCount:v.subagentCount??0,totalDuration:v.totalDuration??0,mcpComplianceRate:v.mcpComplianceRate??0,missedTools:v.missedMcpTools??[],actualFailureCount:v.failedToolCalls??0,fallbackCount:v.fallbackCount??0,fallbackReasons:v.fallbackReasons??[]},metadata:S},{fallbackReason:"skill_execution_already_reconciled_locally"});let w=E.getLatestSkillExecutionForSession(i);if(w&&!h.some(v=>v.executionId===w.executionId)&&E.mergeSkillExecutionMetadata(w.executionId,S),n){E.deleteHookReceipt(e);let v=P(e),de=createHash("sha256").update(e).digest("hex").slice(0,12);for(let H of [`session-id-${de}`,"current-execution-id","current-skill.json","event-map.json"])rmSync$1(join(v,H),{force:!0});}E.deleteContextReceipt(e,i);}catch(_){y({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"lifecycle_telemetry",reason:$(_),fallback:"fail_open"}});}finally{E?.close();}try{await u.endSession(i),await u.flushAndAggregate();}catch(_){y({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"telemetry_flush",reason:$(_),fallback:"local_state_authoritative"}});}}finally{if(f)try{f.close();}catch{}l&&u.close(),m&&s.removeSession(i),y({event:m?"hook.session_end.completed":"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:o?.executionId??a?.executionId},level:m?"info":"warn",timestamp:Date.now(),data:{stage:"finalize",criticalStagesCompleted:m,transcriptStatus:c.status}});}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let t=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",n=>{e+=n;}),process.stdin.on("end",async()=>{let n=Je(e.trim()||process.argv[2]||"");n&&t(JSON.stringify(n)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var nc=/^\/(?:devflow:)?[\w-]+\b\s*/iu,oc=/\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,rc=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,ic=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function Ie(t){let e=t.trim().replace(nc,"").trim();return !e||oc.test(e)?null:(ic.exec(e)??rc.exec(e))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}function sc(t){return join(getProjectStateDir(t),"memory-intents.jsonl")}function ac(t){try{return readFileSync$1(t,"utf8").split(`
17
+ `).filter(Boolean).flatMap(e=>{try{let n=JSON.parse(e);return typeof n.content=="string"&&typeof n.createdAt=="number"?[n]:[]}catch{return []}})}catch{return []}}function Go(t){let e=sc(t),n=`${e}.claim-`,o=`${basename(e)}.claim-`,r=(()=>{try{return readdirSync$1(dirname$1(e)).filter(a=>a.startsWith(o)&&!a.includes(".tmp-")).sort()[0]}catch{return}})(),i=r?join(dirname$1(e),r):`${n}${Date.now()}-${process.pid}`;if(!r)try{renameSync(e,i);}catch{return null}let s=ac(i);if(s.length===0){try{unlinkSync$1(i);}catch{}return null}return {path:i,intents:s}}function Ot(t){if(t.intents.shift(),t.intents.length===0){try{unlinkSync$1(t.path);}catch{}return}let e=`${t.path}.tmp-${process.pid}`;writeFileSync$1(e,t.intents.map(n=>JSON.stringify(n)).join(`
18
18
  `)+`
19
- `,{mode:384}),renameSync(e,t.path);}function Ve(t){let e=t.trim().replace(/^\//,"");if(!e.startsWith("devflow:"))return null;let n=e.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(n)?`devflow:${n.toLowerCase()}`:null}function Yo(t){let e=t.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!e)return null;let n=Ve(e[1]);return n?{rawName:e[1],skillName:n}:null}function we(t,e){return e?`evt_tool_${createHash$1("sha256").update(`${t}\0${e}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var be=1,Nt="memory-snapshot-v1.json",cr=512*1024,dr=256*1024,lr=2e3,fc=500,gc=10,hc=240,yc=300*1e3,vc=720*60*60*1e3,ur=2147483647,_c=100,er=250,Ic=3e4,wc=10,Ke=new Map;function mr(t){return t.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:t.ownerUid===t.currentUid,modeSafe:(t.mode&18)===0}}function G(t){return resolve(t)}function re(t){return createHash("sha256").update(G(t)).digest("hex").slice(0,16)}function qt(t,e={}){let n=re(t),o=e.stateRoot?join(e.stateRoot,n):getProjectStateDir(G(t));return join(o,Nt)}function Ye(t,e){let o=(t instanceof Error?t.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return o?`${e}:${o}`:e}function Wt(t,e){return Array.isArray(t)&&t.length<=e&&t.every(n=>typeof n=="string"&&n.length>0&&n.length<=512)}function kc(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;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)&&Wt(e.memoryIds,100)&&(e.status==="withheld"||e.status==="resolved")&&(e.summary===void 0||typeof e.summary=="string"&&e.summary.length<=2e3)}function bc(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return typeof e.reason=="string"&&e.reason.length>0&&e.reason.length<=512&&(e.stale===void 0||typeof e.stale=="boolean")}function Ut(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))return null;let o=t,r=G(e),i=re(r),s=o.generation===void 0?0:o.generation;return o.version!==be||o.projectRoot!==r||o.projectHash!==i||typeof o.markdown!="string"||Buffer.byteLength(o.markdown,"utf8")>dr||!Wt(o.memoryIds,lr)||!Array.isArray(o.conflicts)||o.conflicts.length>fc||!o.conflicts.every(kc)||typeof o.generatedAt!="number"||!Number.isFinite(o.generatedAt)||o.generatedAt<0||o.generatedAt>n+yc||!Number.isInteger(s)||s<0||s>ur||!["ready","pending","degraded","disabled"].includes(String(o.status))||o.degradation!==void 0&&!bc(o.degradation)?null:{...o,generation:s}}function zt(t,e,n,o,r=0){let i=G(t);return {version:be,projectRoot:i,projectHash:re(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:o,generation:r,status:e,degradation:{reason:n}}}function ne(t,e={}){let n=e.now??Date.now(),o=qt(t,e),r;try{r=openSync$1(o,constants.O_RDONLY|constants.O_NOFOLLOW);let i=fstatSync$1(r);if(!i.isFile()||i.size<=0||i.size>cr)throw new Error("cache_size_invalid");let s=mr({...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$1(r,"utf8")),c=Ut(a,t,n);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&n-c.generatedAt>vc?{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:zt(t,a?"pending":"degraded",a?"cache_missing":Ye(i,"cache_invalid"),n),source:"none",valid:false,stale:false}}finally{if(r!==void 0)try{closeSync$1(r);}catch{}}}function tr(t){if(!Number.isInteger(t)||t<0||t>=ur)throw new Error("memory_snapshot_generation_exhausted");return t+1}function Rc(t){let e=dirname$1(t);mkdirSync$1(e,{recursive:true,mode:448}),chmodSync(e,448);}function Sc(t){Rc(t);let e=`${t}.lock`,n={pid:process.pid,createdAt:Date.now(),token:randomUUID$1()},o=JSON.stringify(n),r;try{return r=openSync$1(e,"wx",384),writeFileSync$1(r,o),fsyncSync(r),{fd:r,path:e,contents:o}}catch(i){if(r!==void 0){try{closeSync$1(r);}catch{}try{unlinkSync$1(e);}catch{}}if(i.code==="EEXIST")return null;throw i}}function xc(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;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 Ec(t){try{return process.kill(t,0),!1}catch(e){return e.code==="ESRCH"}}function Tc(t){return !t.canonicalCachePath||!t.directoryIsSafe||!t.lockIsRegularFile||!t.metadataValid||!t.contentsUnchanged||!t.ownerDead&&!t.stale?false:t.currentUid!==void 0?t.directoryUid===t.currentUid&&t.lockUid===t.currentUid:true}function Ac(t){return isAbsolute(t)&&resolve(t)===t&&basename(t)===Nt&&/^[a-f0-9]{16}$/u.test(basename(dirname$1(t)))}function Cc(t,e){let n=`${t}.lock`;try{let o=lstatSync$1(dirname$1(t)),r=lstatSync$1(n),i=readFileSync$1(n,"utf8"),s=null;try{let f=JSON.parse(i);xc(f)&&(s=f);}catch{}let a=s?.createdAt??r.mtimeMs,c=Date.now()-a>e,d=s?Ec(s.pid):!1,u=readFileSync$1(n,"utf8")===i,l=typeof process.getuid=="function"?process.getuid():void 0,m=mr({...l!==void 0?{currentUid:l}:{},ownerUid:o.uid,mode:o.mode});return Tc({canonicalCachePath:Ac(t),directoryIsSafe:o.isDirectory()&&!o.isSymbolicLink()&&m.modeSafe,lockIsRegularFile:r.isFile()&&!r.isSymbolicLink(),metadataValid:s!==null,ownerDead:d,stale:c,contentsUnchanged:u,...l!==void 0?{currentUid:l}:{},directoryUid:o.uid,lockUid:r.uid})?(unlinkSync$1(n),!0):!1}catch{return false}}function Dc(t){try{closeSync$1(t.fd);}catch{}try{readFileSync$1(t.path,"utf8")===t.contents&&unlinkSync$1(t.path);}catch{}}function Mc(t){return new Promise(e=>setTimeout(e,t))}function Pt(t,e,n,o){let r=Number.isFinite(t)?Math.floor(t):e;return Math.min(o,Math.max(n,r))}async function Oc(t,e){let n=Pt(e.lockTimeoutMs,_c,0,er),o=Pt(e.lockRetryMs,wc,1,er),r=Pt(e.lockStaleMs,Ic,0,Number.MAX_SAFE_INTEGER),i=Date.now()+n;for(;;){let s=Sc(t);if(s)return s;if(Cc(t,r))continue;let a=i-Date.now();if(a<=0)throw new Error("memory_snapshot_cache_lock_timeout");await Mc(Math.min(o,a));}}async function nr(t,e,n){let o=await Oc(t,e);try{return await n()}finally{Dc(o);}}function or(t,e,n,o){let r=o.now??Date.now(),i=G(t),s={version:be,projectRoot:i,projectHash:re(i),markdown:e.markdown,memoryIds:e.memoryIds??[],conflicts:e.conflicts??[],generatedAt:r,generation:n,status:e.status??"ready",...e.degradation?{degradation:e.degradation}:{}};if(!Ut(s,t,r))throw new Error("memory_snapshot_payload_invalid");let a=JSON.stringify(s);if(Buffer.byteLength(a,"utf8")>cr)throw new Error("memory_snapshot_cache_too_large");let c=qt(t,o),d=dirname$1(c);mkdirSync$1(d,{recursive:true,mode:448}),chmodSync(d,448);let u=join(d,`.${Nt}.${process.pid}.${randomUUID$1()}.tmp`),l;try{l=openSync$1(u,"wx",384),writeFileSync$1(l,a),fsyncSync(l),closeSync$1(l),l=void 0,chmodSync(u,384),renameSync(u,c),chmodSync(c,384);let m;try{m=openSync$1(d,"r");try{fsyncSync(m);}catch{}}finally{m!==void 0&&closeSync$1(m);}return s}finally{if(l!==void 0)try{closeSync$1(l);}catch{}rmSync$1(u,{force:true});}}function Pc(t,e){let o=(Ke.get(t)??Promise.resolve()).catch(()=>{}).then(e),r=o.then(()=>{},()=>{});return Ke.set(t,r),o.finally(()=>{Ke.get(t)===r&&Ke.delete(t);})}function jt(t,e,n,o,r){return t.valid?t.snapshot.generation>r?{...t,persisted:false}:{...t,snapshot:{...t.snapshot,status:"degraded",degradation:{reason:n,stale:t.stale||void 0}},persisted:false}:{snapshot:zt(e,"degraded",n,o,r),source:"none",valid:false,stale:false,persisted:false}}async function Bt(t){let e=qt(t.projectRoot,t.cacheOptions);return Pc(e,async()=>{let n=ne(t.projectRoot,t.cacheOptions),o=n.valid?n.snapshot.generation:0,r;try{r=await t.load();}catch(i){let s=Ye(i,`refresh_failed:${t.reason}`);try{return await nr(e,t.cacheOptions??{},()=>{let a=ne(t.projectRoot,t.cacheOptions);if(a.valid)return jt(a,t.projectRoot,s,t.cacheOptions?.now??Date.now(),o);let c=tr(o),d=zt(t.projectRoot,"degraded",s,t.cacheOptions?.now??Date.now(),c);return {snapshot:or(t.projectRoot,d,c,t.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(a){let c=ne(t.projectRoot,t.cacheOptions);return jt(c,t.projectRoot,Ye(a,s),t.cacheOptions?.now??Date.now(),o)}}try{return await nr(e,t.cacheOptions??{},()=>{let i=ne(t.projectRoot,t.cacheOptions);if(i.valid&&i.snapshot.generation>o)return {...i,persisted:!1};let s=tr(Math.max(o,i.valid?i.snapshot.generation:0));return {snapshot:or(t.projectRoot,r,s,t.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(i){let s=ne(t.projectRoot,t.cacheOptions);return jt(s,t.projectRoot,Ye(i,`refresh_commit_failed:${t.reason}`),t.cacheOptions?.now??Date.now(),o)}})}async function Ze(t){return Bt({projectRoot:t.projectRoot,reason:t.reason,cacheOptions:t.cacheOptions,load:async()=>{if(t.injectConfig===false)return {status:"disabled",markdown:"",memoryIds:[],conflicts:[]};let e=typeof t.injectConfig=="object"?t.injectConfig:{},n=Number.isFinite(e.topN)?Math.max(0,Math.floor(e.topN)):4,o=Number.isFinite(e.budgetTokens)?Math.max(1,Math.floor(e.budgetTokens)):400,r=await t.memory.getAll({purpose:"session_bootstrap",budgetTokens:o,limit:n}),s=Number.isInteger(r.truncatedCount)&&r.truncatedCount>=0?r.truncatedCount:null,a=r.memories.length===0&&s!==0,c=s!==null&&s>0?"snapshot_results_truncated":"snapshot_truncation_unknown",d=(r.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
19
+ `,{mode:384}),renameSync(e,t.path);}function Ve(t){let e=t.trim().replace(/^\//,"");if(!e.startsWith("devflow:"))return null;let n=e.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(n)?`devflow:${n.toLowerCase()}`:null}function Yo(t){let e=t.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!e)return null;let n=Ve(e[1]);return n?{rawName:e[1],skillName:n}:null}function we(t,e){return e?`evt_tool_${createHash$1("sha256").update(`${t}\0${e}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var be=1,Nt="memory-snapshot-v1.json",cr=512*1024,dr=256*1024,lr=2e3,gc=500,hc=10,yc=240,vc=300*1e3,_c=720*60*60*1e3,ur=2147483647,Ic=100,er=250,wc=3e4,kc=10,Ke=new Map;function mr(t){return t.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:t.ownerUid===t.currentUid,modeSafe:(t.mode&18)===0}}function G(t){return resolve(t)}function re(t){return createHash("sha256").update(G(t)).digest("hex").slice(0,16)}function qt(t,e={}){let n=re(t),o=e.stateRoot?join(e.stateRoot,n):getProjectStateDir(G(t));return join(o,Nt)}function Ye(t,e){let o=(t instanceof Error?t.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return o?`${e}:${o}`:e}function Wt(t,e){return Array.isArray(t)&&t.length<=e&&t.every(n=>typeof n=="string"&&n.length>0&&n.length<=512)}function bc(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;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)&&Wt(e.memoryIds,100)&&(e.status==="withheld"||e.status==="resolved")&&(e.summary===void 0||typeof e.summary=="string"&&e.summary.length<=2e3)}function Rc(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return typeof e.reason=="string"&&e.reason.length>0&&e.reason.length<=512&&(e.stale===void 0||typeof e.stale=="boolean")}function Ut(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))return null;let o=t,r=G(e),i=re(r),s=o.generation===void 0?0:o.generation;return o.version!==be||o.projectRoot!==r||o.projectHash!==i||typeof o.markdown!="string"||Buffer.byteLength(o.markdown,"utf8")>dr||!Wt(o.memoryIds,lr)||!Array.isArray(o.conflicts)||o.conflicts.length>gc||!o.conflicts.every(bc)||typeof o.generatedAt!="number"||!Number.isFinite(o.generatedAt)||o.generatedAt<0||o.generatedAt>n+vc||!Number.isInteger(s)||s<0||s>ur||!["ready","pending","degraded","disabled"].includes(String(o.status))||o.degradation!==void 0&&!Rc(o.degradation)?null:{...o,generation:s}}function zt(t,e,n,o,r=0){let i=G(t);return {version:be,projectRoot:i,projectHash:re(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:o,generation:r,status:e,degradation:{reason:n}}}function ne(t,e={}){let n=e.now??Date.now(),o=qt(t,e),r;try{r=openSync$1(o,constants.O_RDONLY|constants.O_NOFOLLOW);let i=fstatSync$1(r);if(!i.isFile()||i.size<=0||i.size>cr)throw new Error("cache_size_invalid");let s=mr({...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$1(r,"utf8")),c=Ut(a,t,n);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&n-c.generatedAt>_c?{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:zt(t,a?"pending":"degraded",a?"cache_missing":Ye(i,"cache_invalid"),n),source:"none",valid:false,stale:false}}finally{if(r!==void 0)try{closeSync$1(r);}catch{}}}function tr(t){if(!Number.isInteger(t)||t<0||t>=ur)throw new Error("memory_snapshot_generation_exhausted");return t+1}function Sc(t){let e=dirname$1(t);mkdirSync$1(e,{recursive:true,mode:448}),chmodSync(e,448);}function xc(t){Sc(t);let e=`${t}.lock`,n={pid:process.pid,createdAt:Date.now(),token:randomUUID$1()},o=JSON.stringify(n),r;try{return r=openSync$1(e,"wx",384),writeFileSync$1(r,o),fsyncSync(r),{fd:r,path:e,contents:o}}catch(i){if(r!==void 0){try{closeSync$1(r);}catch{}try{unlinkSync$1(e);}catch{}}if(i.code==="EEXIST")return null;throw i}}function Ec(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;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 Tc(t){try{return process.kill(t,0),!1}catch(e){return e.code==="ESRCH"}}function Ac(t){return !t.canonicalCachePath||!t.directoryIsSafe||!t.lockIsRegularFile||!t.metadataValid||!t.contentsUnchanged||!t.ownerDead&&!t.stale?false:t.currentUid!==void 0?t.directoryUid===t.currentUid&&t.lockUid===t.currentUid:true}function Cc(t){return isAbsolute(t)&&resolve(t)===t&&basename(t)===Nt&&/^[a-f0-9]{16}$/u.test(basename(dirname$1(t)))}function Dc(t,e){let n=`${t}.lock`;try{let o=lstatSync$1(dirname$1(t)),r=lstatSync$1(n),i=readFileSync$1(n,"utf8"),s=null;try{let f=JSON.parse(i);Ec(f)&&(s=f);}catch{}let a=s?.createdAt??r.mtimeMs,c=Date.now()-a>e,d=s?Tc(s.pid):!1,u=readFileSync$1(n,"utf8")===i,l=typeof process.getuid=="function"?process.getuid():void 0,m=mr({...l!==void 0?{currentUid:l}:{},ownerUid:o.uid,mode:o.mode});return Ac({canonicalCachePath:Cc(t),directoryIsSafe:o.isDirectory()&&!o.isSymbolicLink()&&m.modeSafe,lockIsRegularFile:r.isFile()&&!r.isSymbolicLink(),metadataValid:s!==null,ownerDead:d,stale:c,contentsUnchanged:u,...l!==void 0?{currentUid:l}:{},directoryUid:o.uid,lockUid:r.uid})?(unlinkSync$1(n),!0):!1}catch{return false}}function Mc(t){try{closeSync$1(t.fd);}catch{}try{readFileSync$1(t.path,"utf8")===t.contents&&unlinkSync$1(t.path);}catch{}}function Oc(t){return new Promise(e=>setTimeout(e,t))}function Pt(t,e,n,o){let r=Number.isFinite(t)?Math.floor(t):e;return Math.min(o,Math.max(n,r))}async function Pc(t,e){let n=Pt(e.lockTimeoutMs,Ic,0,er),o=Pt(e.lockRetryMs,kc,1,er),r=Pt(e.lockStaleMs,wc,0,Number.MAX_SAFE_INTEGER),i=Date.now()+n;for(;;){let s=xc(t);if(s)return s;if(Dc(t,r))continue;let a=i-Date.now();if(a<=0)throw new Error("memory_snapshot_cache_lock_timeout");await Oc(Math.min(o,a));}}async function nr(t,e,n){let o=await Pc(t,e);try{return await n()}finally{Mc(o);}}function or(t,e,n,o){let r=o.now??Date.now(),i=G(t),s={version:be,projectRoot:i,projectHash:re(i),markdown:e.markdown,memoryIds:e.memoryIds??[],conflicts:e.conflicts??[],generatedAt:r,generation:n,status:e.status??"ready",...e.degradation?{degradation:e.degradation}:{}};if(!Ut(s,t,r))throw new Error("memory_snapshot_payload_invalid");let a=JSON.stringify(s);if(Buffer.byteLength(a,"utf8")>cr)throw new Error("memory_snapshot_cache_too_large");let c=qt(t,o),d=dirname$1(c);mkdirSync$1(d,{recursive:true,mode:448}),chmodSync(d,448);let u=join(d,`.${Nt}.${process.pid}.${randomUUID$1()}.tmp`),l;try{l=openSync$1(u,"wx",384),writeFileSync$1(l,a),fsyncSync(l),closeSync$1(l),l=void 0,chmodSync(u,384),renameSync(u,c),chmodSync(c,384);let m;try{m=openSync$1(d,"r");try{fsyncSync(m);}catch{}}finally{m!==void 0&&closeSync$1(m);}return s}finally{if(l!==void 0)try{closeSync$1(l);}catch{}rmSync$1(u,{force:true});}}function jc(t,e){let o=(Ke.get(t)??Promise.resolve()).catch(()=>{}).then(e),r=o.then(()=>{},()=>{});return Ke.set(t,r),o.finally(()=>{Ke.get(t)===r&&Ke.delete(t);})}function jt(t,e,n,o,r){return t.valid?t.snapshot.generation>r?{...t,persisted:false}:{...t,snapshot:{...t.snapshot,status:"degraded",degradation:{reason:n,stale:t.stale||void 0}},persisted:false}:{snapshot:zt(e,"degraded",n,o,r),source:"none",valid:false,stale:false,persisted:false}}async function Bt(t){let e=qt(t.projectRoot,t.cacheOptions);return jc(e,async()=>{let n=ne(t.projectRoot,t.cacheOptions),o=n.valid?n.snapshot.generation:0,r;try{r=await t.load();}catch(i){let s=Ye(i,`refresh_failed:${t.reason}`);try{return await nr(e,t.cacheOptions??{},()=>{let a=ne(t.projectRoot,t.cacheOptions);if(a.valid)return jt(a,t.projectRoot,s,t.cacheOptions?.now??Date.now(),o);let c=tr(o),d=zt(t.projectRoot,"degraded",s,t.cacheOptions?.now??Date.now(),c);return {snapshot:or(t.projectRoot,d,c,t.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(a){let c=ne(t.projectRoot,t.cacheOptions);return jt(c,t.projectRoot,Ye(a,s),t.cacheOptions?.now??Date.now(),o)}}try{return await nr(e,t.cacheOptions??{},()=>{let i=ne(t.projectRoot,t.cacheOptions);if(i.valid&&i.snapshot.generation>o)return {...i,persisted:!1};let s=tr(Math.max(o,i.valid?i.snapshot.generation:0));return {snapshot:or(t.projectRoot,r,s,t.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(i){let s=ne(t.projectRoot,t.cacheOptions);return jt(s,t.projectRoot,Ye(i,`refresh_commit_failed:${t.reason}`),t.cacheOptions?.now??Date.now(),o)}})}async function Ze(t){return Bt({projectRoot:t.projectRoot,reason:t.reason,cacheOptions:t.cacheOptions,load:async()=>{if(t.injectConfig===false)return {status:"disabled",markdown:"",memoryIds:[],conflicts:[]};let e=typeof t.injectConfig=="object"?t.injectConfig:{},n=Number.isFinite(e.topN)?Math.max(0,Math.floor(e.topN)):4,o=Number.isFinite(e.budgetTokens)?Math.max(1,Math.floor(e.budgetTokens)):400,r=await t.memory.getAll({purpose:"session_bootstrap",budgetTokens:o,limit:n}),s=Number.isInteger(r.truncatedCount)&&r.truncatedCount>=0?r.truncatedCount:null,a=r.memories.length===0&&s!==0,c=s!==null&&s>0?"snapshot_results_truncated":"snapshot_truncation_unknown",d=(r.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
20
20
  DevFlow memory snapshot=degraded; reason=${c}. Memory result completeness is not authoritative; do not conclude that the project has no memories.`:r.memories.length===0&&d.length>0?`## Project memory
21
21
  ${d.length} explicit preference conflict(s) are withheld from automatic guidance; an explicit choice is required.`:r.memories.length===0?`## Project memory
22
22
  \u672C\u9879\u76EE\u6682\u65E0\u8BB0\u5FC6`:`## Project memory (auto-injected, ${r.memories.length} items, ${r.tokenCount} tokens)
23
23
  ${r.memories.map(l=>`- **${l.title||l.type}**: ${l.content} (confidence ${l.confidence.toFixed(2)}, ${l.source})`).join(`
24
- `)}`;return {status:a?"degraded":"ready",markdown:u,memoryIds:r.memories.map(l=>l.id),conflicts:d,...a?{degradation:{reason:c}}:{}}}})}function jc(t){if(!t)return true;try{return JSON.parse(readFileSync$1(t,"utf8")).sessionStart?.injectMemories??!0}catch{return true}}function $c(t,e,n){if(!e.trim())return null;try{let o=JSON.parse(e);if(o.status!=="ok"&&o.status!=="degraded")return null;if(o.enabled===!1){let i=G(t);return {version:be,projectRoot:i,projectHash:re(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"disabled"}}let r=Ut(o.snapshot,t,n);if(r)return r;if(o.status==="ok"&&typeof o.markdown=="string"&&o.markdown.length>0&&Buffer.byteLength(o.markdown,"utf8")<=dr){let i=G(t);return {version:be,projectRoot:i,projectHash:re(i),markdown:o.markdown,memoryIds:Wt(o.memoryIds,lr)?o.memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"ready"}}}catch{}return null}function $t(t,e){return [...(t??e).replace(/[\r\n\t|]+/gu," ").trim()||e].slice(0,hc).join("")}function Fc(t){if(t.length===0)return "";let e=t.slice(0,gc),n=e.map(o=>{let r=$t(o.family,"unknown"),i=$t(o.entity,"unknown"),s=$t(o.summary,"Explicit choice required.");return `- family=${r}; entity=${i}; status=${o.status}; summary=${s}`});return t.length>e.length&&n.push(`- ${t.length-e.length} additional conflict(s) omitted from SessionStart output.`),`## Withheld preference conflicts (${t.length})
24
+ `)}`;return {status:a?"degraded":"ready",markdown:u,memoryIds:r.memories.map(l=>l.id),conflicts:d,...a?{degradation:{reason:c}}:{}}}})}function $c(t){if(!t)return true;try{return JSON.parse(readFileSync$1(t,"utf8")).sessionStart?.injectMemories??!0}catch{return true}}function Fc(t,e,n){if(!e.trim())return null;try{let o=JSON.parse(e);if(o.status!=="ok"&&o.status!=="degraded")return null;if(o.enabled===!1){let i=G(t);return {version:be,projectRoot:i,projectHash:re(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"disabled"}}let r=Ut(o.snapshot,t,n);if(r)return r;if(o.status==="ok"&&typeof o.markdown=="string"&&o.markdown.length>0&&Buffer.byteLength(o.markdown,"utf8")<=dr){let i=G(t);return {version:be,projectRoot:i,projectHash:re(i),markdown:o.markdown,memoryIds:Wt(o.memoryIds,lr)?o.memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"ready"}}}catch{}return null}function $t(t,e){return [...(t??e).replace(/[\r\n\t|]+/gu," ").trim()||e].slice(0,yc).join("")}function Hc(t){if(t.length===0)return "";let e=t.slice(0,hc),n=e.map(o=>{let r=$t(o.family,"unknown"),i=$t(o.entity,"unknown"),s=$t(o.summary,"Explicit choice required.");return `- family=${r}; entity=${i}; status=${o.status}; summary=${s}`});return t.length>e.length&&n.push(`- ${t.length-e.length} additional conflict(s) omitted from SessionStart output.`),`## Withheld preference conflicts (${t.length})
25
25
  ${n.join(`
26
- `)}`}function Hc(t){let e=t.now??Date.now();if(jc(t.configPath)===false)return "";let n=$c(t.projectRoot,t.daemonResponse??"",e),o=n?{snapshot:n,source:"daemon"}:ne(t.projectRoot,{...t.cacheOptions,now:e}),{snapshot:r}=o;if(r.status==="disabled")return `## Project memory
27
- DevFlow memory snapshot=pending; source=${o.source}; reason=previous_snapshot_disabled. Memory availability is not yet known; do not conclude that the project has no memories.`;let i=new Date(r.generatedAt).toISOString(),s=r.degradation?.reason?`; reason=${r.degradation.reason}`:"",a=`DevFlow memory snapshot=${r.status}; source=${o.source}; generatedAt=${i}${s}.`,c=Fc(r.conflicts);return r.markdown?[r.markdown,c,a].filter(Boolean).join(`
26
+ `)}`}function Lc(t){let e=t.now??Date.now();if($c(t.configPath)===false)return "";let n=Fc(t.projectRoot,t.daemonResponse??"",e),o=n?{snapshot:n,source:"daemon"}:ne(t.projectRoot,{...t.cacheOptions,now:e}),{snapshot:r}=o;if(r.status==="disabled")return `## Project memory
27
+ DevFlow memory snapshot=pending; source=${o.source}; reason=previous_snapshot_disabled. Memory availability is not yet known; do not conclude that the project has no memories.`;let i=new Date(r.generatedAt).toISOString(),s=r.degradation?.reason?`; reason=${r.degradation.reason}`:"",a=`DevFlow memory snapshot=${r.status}; source=${o.source}; generatedAt=${i}${s}.`,c=Hc(r.conflicts);return r.markdown?[r.markdown,c,a].filter(Boolean).join(`
28
28
  `):["## Project memory",c,`${a} Memory availability is not yet known; do not conclude that the project has no memories.`].filter(Boolean).join(`
29
- `)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,t,e,n]=process.argv;t!=="session-start"||!e?process.exitCode=2:process.stdout.write(Hc({projectRoot:e,configPath:n,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var Nc=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu,qc=/(?:记住|记下|保存|持久化|跨会话|以后|始终|永远|统一使用|项目约定|团队约定|偏好|决定采用|保留可复用|提炼结论|沉淀|记录(?:下来|为|成)?(?:架构|规则|约定|知识|结论))|\b(?:remember|memorize|persist|across sessions|from now on|always|project convention|team convention|preference|we use|adopt|retain reusable|distill)\b/iu,Wc=/(?:分析|审查|检查|评估|性能|生成|创建|新建|添加|编写|实现|开发|设计|撰写|总结|修改|重构|修复|调试|解释|查看)|\b(?:analy[sz]e|review|inspect|audit|performance|generate|create|add|build|implement|develop|design|write|summarize|modify|refactor|fix|debug|explain)\b/iu,Uc=/(?:召回|查询|检索|查找|定位|询问|什么|如何|是否|哪里|哪个)|\b(?:recall|query|search|find|locate|ask|what|how|whether|where|which)\b/iu;function zc(t){let e=t.trim();return e.length>0&&!Nc.test(e)}function Bc(t){let e=t.normalize("NFKC").trim(),n=Uc.test(e);return e.length>=4&&(Wc.test(e)||n)&&(!qc.test(e)||n)&&Ie(e)===null}function Jc(t,e,n=Date.now()){let o=createHash("sha256").update(e.trim()).digest("hex"),r=createHash("sha256").update(`${t}\0${n}\0${o}`).digest("hex").slice(0,24);return {turnId:`turn:${r}`,eventId:`memory-turn:${r}`,promptHash:o,createdAt:n}}function xe(t,e,n=[]){return `memory-receipt:${createHash("sha256").update(`${t}\0${e}\0${[...n].sort().join("\0")}`).digest("hex").slice(0,24)}`}function et(t){return `DevFlow memory decision required for ${t.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, copy exact evidenceSpans from this user prompt, preserve package names, flags, versions, paths, and identifiers, and provide subject, predicate, value, polarity, and entities when known. To replace or retire an existing fact, provide operation=supersede or operation=retire plus referencedFactIds from the canonical memory receipt; aliases and entity names are not fact identity. 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 Re(t){let e=t.memoryIds.length>0?t.memoryIds.join(","):"none",n=t.status==="committed"?"accepted":t.status,o=t.status==="committed"?"; indexStatus=pending":"",r=t.memoryIds.some(a=>a.startsWith("raw-memory:")),i=t.status==="committed"&&t.source==="explicit_intent"&&!r?"; memoryOnlyCompleted=true; skipProjectContext=true; hostRefinementRequired=true":t.status==="committed"&&t.source==="explicit_intent"?"; asyncReadiness=queued; hostRefinementRequired=true":"",s=t.status==="committed"&&t.source==="explicit_intent"?` The deterministic explicit-memory save is complete and remains authoritative if refinement fails. Before the final response, call mcp__devflow__memory_commit_turn once with turnId=${t.turnId} and semantic candidates. Split every distinct reusable fact into a durable_memory candidate, classify instructions that apply only to this turn as turn_constraint, and include evidenceSpans copied verbatim from the user prompt for every candidate. Preserve exact flags, package names, versions, paths, and identifiers. Keep narrative and value in the user prompt language; do not translate evidence into a different surface form. The tool refines the existing receipt idempotently; it must not create native Claude memory. If refinement is unavailable, return the existing canonical receipt without claiming refinement.`:"";return `DevFlow canonical memory receipt: status=${n}; receiptId=${t.receiptId??"missing"}; turnId=${t.turnId}; memoryIds=${e}; source=${t.source??"unknown"}${o}${i}.`+s}function Jt(t){if(!zc(t.prompt))return null;let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let n=t.prompt.trim().slice(0,4e3),o=createHash("sha256").update(n).digest("hex"),r=e.listMemoryTurns(t.projectRoot,t.sessionId,5).find(l=>l.promptHash===o&&Date.now()-l.createdAt<1e4),i=r?{turnId:r.turnId,eventId:r.eventId,promptHash:r.promptHash,createdAt:r.createdAt}:t.identity??Jc(t.sessionId,n),s=r??e.beginMemoryTurn({...i,projectRoot:t.projectRoot,sessionId:t.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:Re(s),skipSkillRouting:s.source==="explicit_intent"};let c=(t.activation?.semantic??"degraded_structural")==="degraded_structural"?Ie(n)??void 0:void 0;if(!c&&Bc(n)){let l=xe(s.turnId,"skipped"),m=e.skipMemoryTurn({turnId:s.turnId,receiptId:l,source:"automatic_transient_skip",reason:"high_confidence_transient_task"});return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.skipped",payload:{receiptId:l,reasonCode:"high_confidence_transient_task"},dedupeKey:l,producer:"devflow-memory-turn"}),y({event:"memory.semantic.decided",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId},level:"info",timestamp:Date.now(),data:{status:"semantic_empty",operation:"none",reason:"high_confidence_transient_task"}}),{turn:m,additionalContext:Re(m),skipSkillRouting:!1}}let d=c?"commit_explicit":"capture_prompt",u=e.enqueueWork({idempotencyKey:`memory-turn:${d}:${s.turnId}`,kind:c?"memory.explicit_commit":"memory.turn_capture",projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,payload:{operation:d,turnId:s.turnId,eventId:s.eventId,sessionId:t.sessionId,prompt:n,explicitContent:c,createdAt:s.createdAt}});if(c){let l=`raw-memory:${createHash("sha256").update(`${t.projectRoot}\0${i.turnId}\0${c}`).digest("hex").slice(0,24)}`,m=xe(s.turnId,"committed",[l]),f=e.commitMemoryTurn({turnId:s.turnId,receiptId:m,memoryIds:[l],source:"explicit_intent",reason:"explicit_raw_queued",decidedAt:Date.now()});return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"durable_work.owned",payload:{workId:u.id,obligation:"memory"},dedupeKey:`${u.id}:owned`,producer:"devflow-memory-turn"}),C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.committed",payload:{receiptId:m,reasonCode:"explicit_raw_queued"},dedupeKey:m,producer:"devflow-memory-turn"}),y({event:"memory.write.completed",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,actionReceipt:m},level:"info",timestamp:Date.now(),data:{stage:"explicit_fast_ack",durable:!0,rawMemoryId:l,receiptLatencyMs:Date.now()-i.createdAt,asyncReadiness:"queued"}}),{turn:f,explicitContent:c,additionalContext:Re(f),skipSkillRouting:!0}}return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.pending",payload:{reasonCode:"semantic_decision_queued"},dedupeKey:`${s.turnId}:pending`,producer:"devflow-memory-turn"}),C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"durable_work.owned",payload:{workId:u.id,obligation:"memory"},dedupeKey:`${u.id}:owned`,producer:"devflow-memory-turn"}),{turn:s,explicitContent:c,additionalContext:et(s),skipSkillRouting:!1}}finally{e.close();}}async function Vt(t){let{payload:e,memory:n,projectRoot:o}=t,r=openGlobalDevFlowDatabase();try{let i=r.getMemoryTurn(e.turnId);if(!i)throw new Error(`Memory turn ${e.turnId} does not exist`);let s=e.operation==="commit_explicit"&&i.status==="committed"&&i.source==="explicit_intent"&&i.memoryIds.some(l=>l.startsWith("raw-memory:"));if(i.status!=="pending"&&!s){if(i.receiptId&&typeof n.reconcileTurnObservationLineage=="function")try{await n.reconcileTurnObservationLineage([i]);}catch{}return {turn:i,additionalContext:Re(i),skipSkillRouting:i.source==="explicit_intent"}}if(await n.recordUserMessage(e.prompt,e.sessionId,e.prompt.slice(0,200)),await n.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:et(i),skipSkillRouting:!1};let a=await n.saveExplicitMemoryIntent(e.explicitContent,{actorId:"actor:claude-code",sessionId:e.sessionId},e.eventId),c=[...new Set([a.id,...a.relatedMemoryIds??[]])];y({event:"memory.semantic.decided",identity:{projectRoot:o,sessionId:i.sessionId,turnId:i.turnId},level:a.semanticDecision?.status==="semantic_ready"?"info":"warn",timestamp:Date.now(),data:{status:a.semanticDecision?.status??"semantic_unavailable",operations:a.semanticDecision?.operations??["add"],memoryIds:c,rejectedCount:a.semanticDecision?.rejectedCount??0,durable:a.durable,lexicallyReady:a.lexicallyReady,policyReady:a.policyReady,vectorStatus:a.vectorStatus}});let d=i.receiptId??xe(i.turnId,"committed",c),u=s?r.updateCommittedMemoryTurnProjection({turnId:i.turnId,memoryIds:c,reason:"explicit_async_ready"}):r.commitMemoryTurn({turnId:i.turnId,receiptId:d,memoryIds:c,source:"explicit_intent",reason:"explicit_user_request"});C({projectRoot:o,sessionId:i.sessionId,turnId:i.turnId,kind:"memory.committed",payload:{receiptId:d,reasonCode:"explicit_async_ready"},dedupeKey:`${d}:async_ready`,producer:"devflow-memory-worker"}),y({event:"memory.write.completed",identity:{projectRoot:o,sessionId:i.sessionId,turnId:i.turnId,actionReceipt:d},level:"info",timestamp:Date.now(),data:{stage:"explicit_async_ready",durable:!0,memoryIds:c,receiptLatencyMs:Math.max(0,(i.decidedAt??Date.now())-i.createdAt),asyncReadinessMs:Math.max(0,Date.now()-i.createdAt),vectorStatus:a.vectorStatus}});try{typeof n.finalizeTurnDecision=="function"&&await n.finalizeTurnDecision({turnEventId:i.eventId,sessionId:i.sessionId,turnId:i.turnId,receiptId:d,status:"committed",memoryIds:c,reason:"explicit_user_request"});}catch(l){y({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"lineage_finalize",reason:l.message,fallback:"session_end_reconciliation"}});}try{await n.enrichExplicitMemoryObservation(a.id);}catch(l){y({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"explicit_enrichment",memoryId:a.id,reason:l.message,fallback:"durable_work_queue"}}),r.enqueueWork({idempotencyKey:`explicit-enrichment:${o}:${a.id}`,kind:"memory.explicit_enrichment",projectRoot:o,sessionId:e.sessionId,turnId:u.turnId,payload:{observationId:a.id},maxAttempts:20});}r.enqueueWork({idempotencyKey:`vector:${o}:${a.id}`,kind:"memory.vector_backfill",projectRoot:o,sessionId:e.sessionId,turnId:u.turnId,payload:{observationId:a.id},maxAttempts:20});try{await Ze({projectRoot:o,memory:n,injectConfig:loadConfig(o).sessionStart?.injectMemories,reason:"explicit_memory_commit"});}catch(l){y({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"snapshot_refresh",reason:l.message,fallback:"durable_memory_authoritative"}});}return {turn:u,explicitContent:e.explicitContent,additionalContext:Re(u),skipSkillRouting:!0}}finally{r.close();}}var Gc=new Set(["Write","Edit","NotebookEdit"]),fr="Claude native memory writes are disabled for this project. Use DevFlow explicit memory or mcp__devflow__memory_commit_turn so a canonical receipt is created.";function _r(t){if(!Gc.has(t.toolName))return null;let e=Yc(t.toolInput);if(!e)return null;let n=Xc(e,t.projectRoot),o=resolve(t.projectRoot,".claude");if(gr(n,o)&&basename(n).toLocaleUpperCase("en-US")==="MEMORY.MD")return fr;let r=resolve(t.home??homedir(),".claude","projects");return gr(n,r)&&relative(r,n).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?fr:null}function Yc(t){for(let e of ["file_path","notebook_path","path"]){let n=t[e];if(typeof n=="string"&&n.trim())return n.trim()}return null}function Xc(t,e){return resolve(isAbsolute(t)?t:resolve(e,t))}function gr(t,e){let n=relative(e,t);return n===""||!n.startsWith(`..${sep}`)&&n!==".."&&!isAbsolute(n)}var od=1024*1024;function kr(t){let e=join(getProjectStateDir(t),"session-start-pending");mkdirSync$1(e,{recursive:true,mode:448});let n=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(e,n),r=/\.json\.claim-\d+$/u.test(n),i=r?o:`${o}.claim-${process.pid}`;if(!r)try{renameSync(o,i);}catch{return null}try{let s=readFileSync$1(i,"utf8");if(Buffer.byteLength(s,"utf8")>od)throw unlinkSync$1(i),new Error("session_start_spool_input_too_large");return {receiptId:basename(n).replace(/\.json(?:\.claim-\d+)?$/u,""),input:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function br(t){unlinkSync$1(t.path);}function Rr(t){let e=t.path.replace(/\.claim-\d+$/u,"");try{renameSync(t.path,e);}catch{}}function xr(t,e){let n=Cr(t);mkdirSync$1(n,{recursive:true,mode:448});let o=`memory-turn-spool-${Date.now()}-${process.pid}-${randomUUID$1()}`,r=join(n,`${o}.json`),i=`${r}.tmp`;return writeFileSync$1(i,JSON.stringify({...e,prompt:e.prompt.trim().slice(0,4e3)}),{mode:384}),renameSync(i,r),o}function Er(t){let e=Cr(t);mkdirSync$1(e,{recursive:true,mode:448});let n=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(e,n),r=/\.json\.claim-\d+$/u.test(n),i=r?o:`${o}.claim-${process.pid}`;if(!r)try{renameSync(o,i);}catch{return null}try{let s=JSON.parse(readFileSync$1(i,"utf8"));if(typeof s.sessionId!="string"||typeof s.prompt!="string"||typeof s.createdAt!="number")throw unlinkSync$1(i),new Error("memory_turn_spool_payload_invalid");return {receiptId:basename(n).replace(/\.json(?:\.claim-\d+)?$/u,""),payload:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function Tr(t){unlinkSync$1(t.path);}function Ar(t){try{renameSync(t.path,t.path.replace(/\.claim-\d+$/u,""));}catch{}}function Cr(t){return join(P(t),"memory-turn-pending")}var x=class extends Error{constructor(e,n){super(n),this.name="PermanentWorkError",this.category=e;}},ud=1e3,md=3e4,pd=1,fd=5*6e4,nt=class{constructor(e){this.timer=null;this.draining=null;this.stopped=true;this.projectRoot=e.projectRoot,this.handlers=e.handlers,this.pollIntervalMs=Qt(e.pollIntervalMs,ud),this.leaseMs=Qt(e.leaseMs,md),this.batchSize=Qt(e.batchSize,pd),this.owner=e.owner??`hook-daemon:${process.pid}:${randomUUID$1()}`,this.now=e.now??Date.now,this.random=e.random??Math.random,this.openDatabase=e.openDatabase??(()=>openGlobalDevFlowDatabase()),this.afterComplete=e.afterComplete;}start(){this.stopped&&(this.stopped=false,this.schedule(0));}stop(){this.stopped=true,this.timer&&clearTimeout(this.timer),this.timer=null;}drainOnce(){return this.draining?this.draining:(this.draining=this.performDrain().finally(()=>{this.draining=null;}),this.draining)}async drainWorkItemOnce(e){return e.trim()?(this.draining&&await this.draining,this.draining=this.performDrain(void 0,new Set([e])).finally(()=>{this.draining=null;}),this.draining):0}schedule(e){this.stopped||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null,this.drainOnce().catch(n=>this.logDegradation("drain",n)).finally(()=>this.schedule(this.pollIntervalMs));},e),this.timer.unref());}async performDrain(e,n){let o=Object.keys(this.handlers).filter(i=>!e||e.has(i));if(o.length===0)return 0;let r=this.openDatabase();try{let i=this.now();r.recoverExpiredWork(this.projectRoot,i);let s=r.leaseWork({projectRoot:this.projectRoot,owner:this.owner,kinds:o,workItemIds:n?[...n]:void 0,limit:this.batchSize,leaseMs:this.leaseMs,now:i});for(let a of s)await this.processItem(r,a);return s.length}finally{r.close();}}async processItem(e,n){let o=this.handlers[n.kind];if(!o){e.deadLetterWork(n.id,this.owner,{category:"unsupported_work_kind",message:`No work handler is registered for ${n.kind}`}),this.logWorkTransition("dead_letter",n,{errorCategory:"unsupported_work_kind"},"error");return}let r=setInterval(()=>{e.heartbeatWork(n.id,this.owner,this.leaseMs,this.now())||this.logDegradation("lease_heartbeat",new Error("work_lease_heartbeat_rejected"),n);},Math.max(1e3,Math.floor(this.leaseMs/3)));r.unref();try{if(await o({item:n}),!e.completeWork(n.id,this.owner,this.now()))throw new Error(`Work lease was lost before completion: ${n.id}`);this.logWorkTransition("completed",n,{attempt:n.attempts});try{await this.afterComplete?.({item:n,database:e});}catch(i){this.logDegradation("completion_follow_up",i,n);}}catch(i){let s=gd(i);if(i instanceof x||s.permanent){e.deadLetterWork(n.id,this.owner,s),this.logWorkTransition("dead_letter",n,{attempt:n.attempts,errorCategory:s.category},"error");return}let a=this.now()+Math.max(hd(n.attempts,this.random()),s.retryAfterMs??0);if(s.retryWithoutAttempt){e.deferWork(n.id,this.owner,s,a),this.logWorkTransition("deferred",n,{attempt:n.attempts,nextAttemptAt:a,errorCategory:s.category},"warn");return}e.retryWork(n.id,this.owner,s,a),this.logWorkTransition("retry_wait",n,{attempt:n.attempts,nextAttemptAt:a,errorCategory:s.category},"warn");}finally{clearInterval(r);}}logDegradation(e,n,o){y({event:"hook.runtime.degraded",identity:{projectRoot:this.projectRoot,sessionId:o?.sessionId,turnId:o?.turnId,executionId:o?.executionId},level:"warn",timestamp:this.now(),data:{stage:`work_${e}`,workId:o?.id,workKind:o?.kind,reason:Dr(n)}});}logWorkTransition(e,n,o,r="info"){try{y({event:"durable.work.transitioned",identity:{projectRoot:this.projectRoot,sessionId:n.sessionId,turnId:n.turnId,executionId:n.executionId},level:r,timestamp:this.now(),data:{stage:e,workId:n.id,workKind:n.kind,...o}});}catch{}}};function Qt(t,e){return Number.isSafeInteger(t)&&t>0?t:e}function gd(t){if(t instanceof x)return {category:t.category,message:t.message};let e=t&&typeof t=="object"?t:null,n=typeof e?.category=="string"?e.category:"runtime_error";return {category:n,message:Dr(t),retryAfterMs:typeof e?.retryAfterMs=="number"&&Number.isFinite(e.retryAfterMs)?Math.max(0,e.retryAfterMs):void 0,retryWithoutAttempt:e?.retryWithoutAttempt===true,permanent:n==="policy_verification_failed"||n==="invalid_payload"}}function hd(t,e){let n=Math.min(fd,500*2**Math.max(0,t-1)),o=Math.floor(n*.2*Math.max(0,Math.min(1,e)));return n+o}function Dr(t){return t instanceof Error?t.message:String(t)}var wd=250;function Pr(t,e=process.env){let n=Or(join(getDevFlowStateRoot({env:e}),"config.json")),o=Or(join(t,".devflow","config.json")),r=Zt(e.DEVFLOW_HOOK_PROFILE)??Zt(o.profile)??Zt(n.profile)??"standard",i=Number(e.DEVFLOW_HOOK_ACK_BUDGET_MS??o.acknowledgementBudgetMs??n.acknowledgementBudgetMs),s=Number.isSafeInteger(i)&&i>0?Math.min(i,5e3):wd,a=new Set([...en(n.disabledHandlers),...en(o.disabledHandlers),...en(e.DEVFLOW_DISABLED_HOOK_HANDLERS?.split(","))].map(Sd).filter(c=>!!c));return {profile:r,acknowledgementBudgetMs:s,disabledHandlers:a}}async function jr(t,e,n,o,r=process.env.CLAUDE_PROJECT_DIR||process.cwd()){let i,s=new Promise(a=>{i=setTimeout(()=>{y({event:"hook.runtime.degraded",identity:{projectRoot:r},level:"warn",timestamp:Date.now(),data:{stage:"acknowledgement_budget",eventName:t,budgetMs:e,fallback:"timeout_result"}}),a(o());},e),i.unref();});try{return await Promise.race([Promise.resolve().then(n),s])}finally{i&&clearTimeout(i);}}async function $r(t,e=process.env){let n=e.DEVFLOW_HOST_ADAPTER??(e.CLAUDE_PROJECT_DIR||e.CLAUDE_PLUGIN_ROOT||e.CLAUDE_CODE_ENTRYPOINT?"claude-code":void 0),o=await selectHostAdapter({projectRoot:t,env:e,explicitHost:n});if(o.status==="failed")throw new Error(`host_adapter_selection_failed:${o.code}:${o.reason}`);let r=await o.adapter.capabilities({projectRoot:t,env:e,explicitHost:n});return {hostId:o.adapter.id,capabilities:new Map(r.map(i=>[i.capability,i])),profiles:new Set(o.adapter.hooks?.profileSupport??[])}}function tn(t,e,n){let o=Rd(t,e.profile);if(!n.profiles.has(e.profile))return {enabled:false,policy:"fail_open",reason:`hook_profile_${e.profile}_unsupported_by_${n.hostId}`,fallback:"host_event_continues_without_devflow_handler"};if(e.disabledHandlers.has(t))return {enabled:false,policy:"fail_open",reason:"hook_handler_disabled",fallback:"host_event_continues_without_devflow_handler"};if(e.profile==="minimal"&&!kd.has(t))return {enabled:false,policy:"fail_open",reason:"hook_handler_not_in_minimal_profile",fallback:"critical_receipts_only"};let r=bd[t];if(!r)return {enabled:true,policy:o};let i=n.capabilities.get(r);return !i||i.status!=="supported"?{enabled:false,policy:"fail_open",reason:i?.reason??`${r}_unsupported_by_${n.hostId}`,fallback:i?.fallback??"host_event_continues_without_native_hook_processing"}:{enabled:true,policy:o}}var kd=new Set(["session-start","user-prompt-submit","stop","session-end","memory-snapshot"]),bd={"session-start":"hooks.session_start","user-prompt-submit":"hooks.prompt_submit","pre-tool-use":"hooks.pre_tool_use","post-tool-use":"hooks.post_tool_use","post-tool-use-failure":"hooks.post_tool_use",stop:"hooks.stop","session-end":"hooks.session_end"};function Rd(t,e){return t==="user-prompt-submit"||t==="stop"||t==="session-end"?"enqueue_and_open":t==="pre-tool-use"&&e==="strict"?"fail_closed":"fail_open"}function Or(t){if(!existsSync(t))return {};try{let n=JSON.parse(readFileSync$1(t,"utf8")).hooks;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return {}}}function Zt(t){return t==="minimal"||t==="standard"||t==="strict"?t:void 0}function en(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Sd(t){let e=t.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase();return ({sessionstart:"session-start",userpromptsubmit:"user-prompt-submit",pretooluse:"pre-tool-use",posttooluse:"post-tool-use",posttoolusefailure:"post-tool-use-failure",sessionend:"session-end",precompact:"pre-compact",memorysnapshot:"memory-snapshot"}[e.replace(/-/g,"")]??e)||void 0}var ot=class{decode(e){let n;try{let d=JSON.parse(e.rawInput);if(!d||typeof d!="object"||Array.isArray(d))return null;n=d;}catch{return null}let o=Ed[e.requestType];if(typeof n.hook_event_name=="string"&&n.hook_event_name!==o)return null;let r=resolve(on(n.cwd)??e.projectRoot??process.cwd()),i=on(n.session_id),s=on(n.tool_use_id),a=e.receivedAt??Date.now(),c={requestType:e.requestType,projectRoot:r,sessionId:i??"",toolUseId:s??"",payloadHash:stableRuntimeHash(n)};return {schemaVersion:"normalized-hook-event.v1",eventId:`hook-event:${stableRuntimeHash(c).slice(0,32)}`,requestType:e.requestType,eventName:o,projectRoot:r,...i?{sessionId:i}:{},...s?{toolUseId:s}:{},retryKey:`${e.requestType}:${stableRuntimeHash(c).slice(0,24)}`,receivedAt:a,rawInput:e.rawInput,payload:n}}},Ed={"session-start":"SessionStart","user-prompt-submit":"UserPromptSubmit","pre-tool-use":"PreToolUse","post-tool-use":"PostToolUse","post-tool-use-failure":"PostToolUseFailure",stop:"Stop","session-end":"SessionEnd","pre-compact":"PreCompact","memory-snapshot":"MemorySnapshot"};function on(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function Fr(t){let e=Object.keys(t.handlers).map(n=>{let o=Ad[n];return [n,{requestType:n,eventName:o,capability:Cd[n],failurePolicy:t.failurePolicy(n),acknowledgeWithinBudget:Td.has(n),handler:t.handlers[n],timeoutResult:()=>Dd(n)}]});return new Map(e)}async function Hr(t){let e=t.registry.get(t.requestType);if(!e)return {status:"degraded",reason:"unknown_hook_handler",fallback:"host_event_continues"};let n=new ot().decode({requestType:t.requestType,rawInput:t.rawInput,projectRoot:t.projectRoot}),o=()=>Promise.resolve(e.handler(n?.rawInput??t.rawInput));return e.acknowledgeWithinBudget?jr(e.eventName,t.acknowledgementBudgetMs,o,e.timeoutResult,t.projectRoot):o()}var Td=new Set(["stop","session-end","user-prompt-submit"]),Ad={"session-start":"SessionStart","user-prompt-submit":"UserPromptSubmit","pre-tool-use":"PreToolUse","post-tool-use":"PostToolUse","post-tool-use-failure":"PostToolUseFailure",stop:"Stop","session-end":"SessionEnd","pre-compact":"PreCompact","memory-snapshot":"MemorySnapshot"},Cd={"session-start":"hooks.session_start","user-prompt-submit":"hooks.prompt_submit","pre-tool-use":"hooks.pre_tool_use","post-tool-use":"hooks.post_tool_use","post-tool-use-failure":"hooks.post_tool_use",stop:"hooks.stop","session-end":"hooks.session_end"};function Dd(t){return t==="user-prompt-submit"?{hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",additionalContext:"DevFlow background processing exceeded its acknowledgement budget; continue in degraded mode and do not claim unreceipted work completed."}}:{status:"degraded",reason:"hook_budget_exceeded",fallback:t==="session-end"?"durable_session_recovery":"background_processing"}}var it=class{constructor(e){this.records=new Map;this.path=join(P(e),"hook-handler-health.json"),this.load();}recordSuccess(e,n,o=Date.now()){let r={handler:e,host:n,status:"healthy",consecutiveFailures:0,lastSuccessAt:o,updatedAt:o};return this.records.set(rt(e,n),r),this.persist(),r}recordFailure(e,n,o,r,i=Date.now()){let s=this.records.get(rt(e,n)),a=(s?.consecutiveFailures??0)+1,c=Math.min(5*6e4,1e3*2**Math.min(8,a-1)),d={handler:e,host:n,status:"degraded",consecutiveFailures:a,lastFailureCategory:o,lastFailureReason:r.slice(0,500),retryAt:i+c,lastSuccessAt:s?.lastSuccessAt,updatedAt:i};return this.records.set(rt(e,n),d),this.persist(),d}list(){return [...this.records.values()].sort((e,n)=>e.handler.localeCompare(n.handler))}load(){try{let e=JSON.parse(readFileSync$1(this.path,"utf8"));for(let n of e)n?.handler&&n?.host&&this.records.set(rt(n.handler,n.host),n);}catch{}}persist(){try{mkdirSync$1(dirname$1(this.path),{recursive:!0,mode:448});let e=`${this.path}.${process.pid}.tmp`;writeFileSync$1(e,JSON.stringify(this.list(),null,2),{mode:384}),renameSync(e,this.path);}catch{}}};function rt(t,e){return `${e}\0${t}`}function Lr(t,e){return e||(t==="post-tool-use"||t==="post-tool-use-failure"?{status:"ok"}:{status:"ok"})}function Nr(t){let e=t instanceof Error?t.message:String(t??"hook_handler_failed");return {category:/timeout|budget|deadline/iu.test(e)?"timeout":/sqlite|database|locked|busy/iu.test(e)?"storage":/socket|connect|unreachable/iu.test(e)?"transport":/json|parse|schema|invalid/iu.test(e)?"protocol":"handler",reason:e}}function qr(t){let e=Do({projectRoot:t.projectRoot,sessionId:t.sessionId,transcriptPath:t.transcriptPath,runtimeStore:t.runtimeStore}),n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{Wd(t.runtimeStore,t.sessionId,n);let o=n.getPendingMemoryTurn(t.projectRoot,t.sessionId),r=o?n.markMemoryTurnStopPrompted(o.turnId):!1,i=[];e&&i.push(e.reason),o&&r&&i.push(et(o)),o&&!r&&Nd(n,o.turnId)&&qd(Be(t.transcriptPath))&&i.push(`DevFlow explicit memory ${o.turnId} still has no canonical receipt. Remove the memory-success claim and tell the user that the memory was not saved, or complete the pending turn.`);let a=n.listSessionObligations(t.projectRoot,t.sessionId,["open"]).map(c=>({obligationId:c.obligationId,kind:c.kind,action:c.kind==="memory_decision"?"Call mcp__devflow__memory_decide_turn using the canonical turn ID.":c.kind==="evidence_contract"?c.payload.subtype==="policy_verification"?`Complete the required project verification: ${String(c.payload.command??c.payload.verificationKind??"unknown command")}.`:"Return a final answer that satisfies the canonical evidence contract.":"Allow SessionEnd durable finalization to complete.",canonicalInput:c.kind==="memory_decision"&&c.turnId?{turnId:c.turnId}:void 0}));return i.length>0?{decision:"block_once",unresolved:a,additionalContext:["DevFlow has unresolved terminal obligations. Complete all actions below before stopping.",...i].join(`
29
+ `)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,t,e,n]=process.argv;t!=="session-start"||!e?process.exitCode=2:process.stdout.write(Lc({projectRoot:e,configPath:n,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var qc=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu,Wc=/(?:记住|记下|保存|持久化|跨会话|以后|始终|永远|统一使用|项目约定|团队约定|偏好|决定采用|保留可复用|提炼结论|沉淀|记录(?:下来|为|成)?(?:架构|规则|约定|知识|结论))|\b(?:remember|memorize|persist|across sessions|from now on|always|project convention|team convention|preference|we use|adopt|retain reusable|distill)\b/iu,Uc=/(?:分析|审查|检查|评估|性能|生成|创建|新建|添加|编写|实现|开发|设计|撰写|总结|修改|重构|修复|调试|解释|查看)|\b(?:analy[sz]e|review|inspect|audit|performance|generate|create|add|build|implement|develop|design|write|summarize|modify|refactor|fix|debug|explain)\b/iu,zc=/(?:召回|查询|检索|查找|定位|询问|什么|如何|是否|哪里|哪个)|\b(?:recall|query|search|find|locate|ask|what|how|whether|where|which)\b/iu;function Bc(t){let e=t.trim();return e.length>0&&!qc.test(e)}function Jc(t){let e=t.normalize("NFKC").trim(),n=zc.test(e);return e.length>=4&&(Uc.test(e)||n)&&(!Wc.test(e)||n)&&Ie(e)===null}function Vc(t,e,n=Date.now()){let o=createHash("sha256").update(e.trim()).digest("hex"),r=createHash("sha256").update(`${t}\0${n}\0${o}`).digest("hex").slice(0,24);return {turnId:`turn:${r}`,eventId:`memory-turn:${r}`,promptHash:o,createdAt:n}}function xe(t,e,n=[]){return `memory-receipt:${createHash("sha256").update(`${t}\0${e}\0${[...n].sort().join("\0")}`).digest("hex").slice(0,24)}`}function et(t){return `DevFlow memory decision required for ${t.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, copy exact evidenceSpans from this user prompt, preserve package names, flags, versions, paths, and identifiers, and provide subject, predicate, value, polarity, and entities when known. To replace or retire an existing fact, provide operation=supersede or operation=retire plus referencedFactIds from the canonical memory receipt; aliases and entity names are not fact identity. 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 Re(t){let e=t.memoryIds.length>0?t.memoryIds.join(","):"none",n=t.status==="committed"?"accepted":t.status,o=t.status==="committed"?"; indexStatus=pending":"",r=t.memoryIds.some(a=>a.startsWith("raw-memory:")),i=t.status==="committed"&&t.source==="explicit_intent"&&!r?"; memoryOnlyCompleted=true; skipProjectContext=true; hostRefinementRequired=true":t.status==="committed"&&t.source==="explicit_intent"?"; asyncReadiness=queued; hostRefinementRequired=true":"",s=t.status==="committed"&&t.source==="explicit_intent"?` The deterministic explicit-memory save is complete and remains authoritative if refinement fails. Before the final response, call mcp__devflow__memory_commit_turn once with turnId=${t.turnId} and semantic candidates. Split every distinct reusable fact into a durable_memory candidate, classify instructions that apply only to this turn as turn_constraint, and include evidenceSpans copied verbatim from the user prompt for every candidate. Preserve exact flags, package names, versions, paths, and identifiers. Keep narrative and value in the user prompt language; do not translate evidence into a different surface form. The tool refines the existing receipt idempotently; it must not create native Claude memory. If refinement is unavailable, return the existing canonical receipt without claiming refinement.`:"";return `DevFlow canonical memory receipt: status=${n}; receiptId=${t.receiptId??"missing"}; turnId=${t.turnId}; memoryIds=${e}; source=${t.source??"unknown"}${o}${i}.`+s}function Jt(t){if(!Bc(t.prompt))return null;let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let n=t.prompt.trim().slice(0,4e3),o=createHash("sha256").update(n).digest("hex"),r=e.listMemoryTurns(t.projectRoot,t.sessionId,5).find(l=>l.promptHash===o&&Date.now()-l.createdAt<1e4),i=r?{turnId:r.turnId,eventId:r.eventId,promptHash:r.promptHash,createdAt:r.createdAt}:t.identity??Vc(t.sessionId,n),s=r??e.beginMemoryTurn({...i,projectRoot:t.projectRoot,sessionId:t.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:Re(s),skipSkillRouting:s.source==="explicit_intent"};let c=(t.activation?.semantic??"degraded_structural")==="degraded_structural"?Ie(n)??void 0:void 0;if(!c&&Jc(n)){let l=xe(s.turnId,"skipped"),m=e.skipMemoryTurn({turnId:s.turnId,receiptId:l,source:"automatic_transient_skip",reason:"high_confidence_transient_task"});return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.skipped",payload:{receiptId:l,reasonCode:"high_confidence_transient_task"},dedupeKey:l,producer:"devflow-memory-turn"}),y({event:"memory.semantic.decided",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId},level:"info",timestamp:Date.now(),data:{status:"semantic_empty",operation:"none",reason:"high_confidence_transient_task"}}),{turn:m,additionalContext:Re(m),skipSkillRouting:!1}}let d=c?"commit_explicit":"capture_prompt",u=e.enqueueWork({idempotencyKey:`memory-turn:${d}:${s.turnId}`,kind:c?"memory.explicit_commit":"memory.turn_capture",projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,payload:{operation:d,turnId:s.turnId,eventId:s.eventId,sessionId:t.sessionId,prompt:n,explicitContent:c,createdAt:s.createdAt}});if(c){let l=`raw-memory:${createHash("sha256").update(`${t.projectRoot}\0${i.turnId}\0${c}`).digest("hex").slice(0,24)}`,m=xe(s.turnId,"committed",[l]),f=e.commitMemoryTurn({turnId:s.turnId,receiptId:m,memoryIds:[l],source:"explicit_intent",reason:"explicit_raw_queued",decidedAt:Date.now()});return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"durable_work.owned",payload:{workId:u.id,obligation:"memory"},dedupeKey:`${u.id}:owned`,producer:"devflow-memory-turn"}),C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.committed",payload:{receiptId:m,reasonCode:"explicit_raw_queued"},dedupeKey:m,producer:"devflow-memory-turn"}),y({event:"memory.write.completed",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,actionReceipt:m},level:"info",timestamp:Date.now(),data:{stage:"explicit_fast_ack",durable:!0,rawMemoryId:l,receiptLatencyMs:Date.now()-i.createdAt,asyncReadiness:"queued"}}),{turn:f,explicitContent:c,additionalContext:Re(f),skipSkillRouting:!0}}return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.pending",payload:{reasonCode:"semantic_decision_queued"},dedupeKey:`${s.turnId}:pending`,producer:"devflow-memory-turn"}),C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"durable_work.owned",payload:{workId:u.id,obligation:"memory"},dedupeKey:`${u.id}:owned`,producer:"devflow-memory-turn"}),{turn:s,explicitContent:c,additionalContext:et(s),skipSkillRouting:!1}}finally{e.close();}}async function Vt(t){let{payload:e,memory:n,projectRoot:o}=t,r=openGlobalDevFlowDatabase();try{let i=r.getMemoryTurn(e.turnId);if(!i)throw new Error(`Memory turn ${e.turnId} does not exist`);let s=e.operation==="commit_explicit"&&i.status==="committed"&&i.source==="explicit_intent"&&i.memoryIds.some(l=>l.startsWith("raw-memory:"));if(i.status!=="pending"&&!s){if(i.receiptId&&typeof n.reconcileTurnObservationLineage=="function")try{await n.reconcileTurnObservationLineage([i]);}catch{}return {turn:i,additionalContext:Re(i),skipSkillRouting:i.source==="explicit_intent"}}if(await n.recordUserMessage(e.prompt,e.sessionId,e.prompt.slice(0,200)),await n.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:et(i),skipSkillRouting:!1};let a=await n.saveExplicitMemoryIntent(e.explicitContent,{actorId:"actor:claude-code",sessionId:e.sessionId},e.eventId),c=[...new Set([a.id,...a.relatedMemoryIds??[]])];y({event:"memory.semantic.decided",identity:{projectRoot:o,sessionId:i.sessionId,turnId:i.turnId},level:a.semanticDecision?.status==="semantic_ready"?"info":"warn",timestamp:Date.now(),data:{status:a.semanticDecision?.status??"semantic_unavailable",operations:a.semanticDecision?.operations??["add"],memoryIds:c,rejectedCount:a.semanticDecision?.rejectedCount??0,durable:a.durable,lexicallyReady:a.lexicallyReady,policyReady:a.policyReady,vectorStatus:a.vectorStatus}});let d=i.receiptId??xe(i.turnId,"committed",c),u=s?r.updateCommittedMemoryTurnProjection({turnId:i.turnId,memoryIds:c,reason:"explicit_async_ready"}):r.commitMemoryTurn({turnId:i.turnId,receiptId:d,memoryIds:c,source:"explicit_intent",reason:"explicit_user_request"});C({projectRoot:o,sessionId:i.sessionId,turnId:i.turnId,kind:"memory.committed",payload:{receiptId:d,reasonCode:"explicit_async_ready"},dedupeKey:`${d}:async_ready`,producer:"devflow-memory-worker"}),y({event:"memory.write.completed",identity:{projectRoot:o,sessionId:i.sessionId,turnId:i.turnId,actionReceipt:d},level:"info",timestamp:Date.now(),data:{stage:"explicit_async_ready",durable:!0,memoryIds:c,receiptLatencyMs:Math.max(0,(i.decidedAt??Date.now())-i.createdAt),asyncReadinessMs:Math.max(0,Date.now()-i.createdAt),vectorStatus:a.vectorStatus}});try{typeof n.finalizeTurnDecision=="function"&&await n.finalizeTurnDecision({turnEventId:i.eventId,sessionId:i.sessionId,turnId:i.turnId,receiptId:d,status:"committed",memoryIds:c,reason:"explicit_user_request"});}catch(l){y({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"lineage_finalize",reason:l.message,fallback:"session_end_reconciliation"}});}try{await n.enrichExplicitMemoryObservation(a.id);}catch(l){y({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"explicit_enrichment",memoryId:a.id,reason:l.message,fallback:"durable_work_queue"}}),r.enqueueWork({idempotencyKey:`explicit-enrichment:${o}:${a.id}`,kind:"memory.explicit_enrichment",projectRoot:o,sessionId:e.sessionId,turnId:u.turnId,payload:{observationId:a.id},maxAttempts:20});}r.enqueueWork({idempotencyKey:`vector:${o}:${a.id}`,kind:"memory.vector_backfill",projectRoot:o,sessionId:e.sessionId,turnId:u.turnId,payload:{observationId:a.id},maxAttempts:20});try{await Ze({projectRoot:o,memory:n,injectConfig:loadConfig(o).sessionStart?.injectMemories,reason:"explicit_memory_commit"});}catch(l){y({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"snapshot_refresh",reason:l.message,fallback:"durable_memory_authoritative"}});}return {turn:u,explicitContent:e.explicitContent,additionalContext:Re(u),skipSkillRouting:!0}}finally{r.close();}}var Yc=new Set(["Write","Edit","NotebookEdit"]),fr="Claude native memory writes are disabled for this project. Use DevFlow explicit memory or mcp__devflow__memory_commit_turn so a canonical receipt is created.";function _r(t){if(!Yc.has(t.toolName))return null;let e=Xc(t.toolInput);if(!e)return null;let n=Qc(e,t.projectRoot),o=resolve(t.projectRoot,".claude");if(gr(n,o)&&basename(n).toLocaleUpperCase("en-US")==="MEMORY.MD")return fr;let r=resolve(t.home??homedir(),".claude","projects");return gr(n,r)&&relative(r,n).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?fr:null}function Xc(t){for(let e of ["file_path","notebook_path","path"]){let n=t[e];if(typeof n=="string"&&n.trim())return n.trim()}return null}function Qc(t,e){return resolve(isAbsolute(t)?t:resolve(e,t))}function gr(t,e){let n=relative(e,t);return n===""||!n.startsWith(`..${sep}`)&&n!==".."&&!isAbsolute(n)}var rd=1024*1024;function kr(t){let e=join(getProjectStateDir(t),"session-start-pending");mkdirSync$1(e,{recursive:true,mode:448});let n=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(e,n),r=/\.json\.claim-\d+$/u.test(n),i=r?o:`${o}.claim-${process.pid}`;if(!r)try{renameSync(o,i);}catch{return null}try{let s=readFileSync$1(i,"utf8");if(Buffer.byteLength(s,"utf8")>rd)throw unlinkSync$1(i),new Error("session_start_spool_input_too_large");return {receiptId:basename(n).replace(/\.json(?:\.claim-\d+)?$/u,""),input:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function br(t){unlinkSync$1(t.path);}function Rr(t){let e=t.path.replace(/\.claim-\d+$/u,"");try{renameSync(t.path,e);}catch{}}function xr(t,e){let n=Cr(t);mkdirSync$1(n,{recursive:true,mode:448});let o=`memory-turn-spool-${Date.now()}-${process.pid}-${randomUUID$1()}`,r=join(n,`${o}.json`),i=`${r}.tmp`;return writeFileSync$1(i,JSON.stringify({...e,prompt:e.prompt.trim().slice(0,4e3)}),{mode:384}),renameSync(i,r),o}function Er(t){let e=Cr(t);mkdirSync$1(e,{recursive:true,mode:448});let n=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(e,n),r=/\.json\.claim-\d+$/u.test(n),i=r?o:`${o}.claim-${process.pid}`;if(!r)try{renameSync(o,i);}catch{return null}try{let s=JSON.parse(readFileSync$1(i,"utf8"));if(typeof s.sessionId!="string"||typeof s.prompt!="string"||typeof s.createdAt!="number")throw unlinkSync$1(i),new Error("memory_turn_spool_payload_invalid");return {receiptId:basename(n).replace(/\.json(?:\.claim-\d+)?$/u,""),payload:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function Tr(t){unlinkSync$1(t.path);}function Ar(t){try{renameSync(t.path,t.path.replace(/\.claim-\d+$/u,""));}catch{}}function Cr(t){return join(P(t),"memory-turn-pending")}var x=class extends Error{constructor(e,n){super(n),this.name="PermanentWorkError",this.category=e;}},md=1e3,pd=3e4,fd=1,gd=5*6e4,nt=class{constructor(e){this.timer=null;this.draining=null;this.stopped=true;this.projectRoot=e.projectRoot,this.handlers=e.handlers,this.pollIntervalMs=Qt(e.pollIntervalMs,md),this.leaseMs=Qt(e.leaseMs,pd),this.batchSize=Qt(e.batchSize,fd),this.owner=e.owner??`hook-daemon:${process.pid}:${randomUUID$1()}`,this.now=e.now??Date.now,this.random=e.random??Math.random,this.openDatabase=e.openDatabase??(()=>openGlobalDevFlowDatabase()),this.afterComplete=e.afterComplete;}start(){this.stopped&&(this.stopped=false,this.schedule(0));}stop(){this.stopped=true,this.timer&&clearTimeout(this.timer),this.timer=null;}drainOnce(){return this.draining?this.draining:(this.draining=this.performDrain().finally(()=>{this.draining=null;}),this.draining)}async drainWorkItemOnce(e){return e.trim()?(this.draining&&await this.draining,this.draining=this.performDrain(void 0,new Set([e])).finally(()=>{this.draining=null;}),this.draining):0}schedule(e){this.stopped||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null,this.drainOnce().catch(n=>this.logDegradation("drain",n)).finally(()=>this.schedule(this.pollIntervalMs));},e),this.timer.unref());}async performDrain(e,n){let o=Object.keys(this.handlers).filter(i=>!e||e.has(i));if(o.length===0)return 0;let r=this.openDatabase();try{let i=this.now();r.recoverExpiredWork(this.projectRoot,i);let s=r.leaseWork({projectRoot:this.projectRoot,owner:this.owner,kinds:o,workItemIds:n?[...n]:void 0,limit:this.batchSize,leaseMs:this.leaseMs,now:i});for(let a of s)await this.processItem(r,a);return s.length}finally{r.close();}}async processItem(e,n){let o=this.handlers[n.kind];if(!o){e.deadLetterWork(n.id,this.owner,{category:"unsupported_work_kind",message:`No work handler is registered for ${n.kind}`}),this.logWorkTransition("dead_letter",n,{errorCategory:"unsupported_work_kind"},"error");return}let r=setInterval(()=>{e.heartbeatWork(n.id,this.owner,this.leaseMs,this.now())||this.logDegradation("lease_heartbeat",new Error("work_lease_heartbeat_rejected"),n);},Math.max(1e3,Math.floor(this.leaseMs/3)));r.unref();try{if(await o({item:n}),!e.completeWork(n.id,this.owner,this.now()))throw new Error(`Work lease was lost before completion: ${n.id}`);this.logWorkTransition("completed",n,{attempt:n.attempts});try{await this.afterComplete?.({item:n,database:e});}catch(i){this.logDegradation("completion_follow_up",i,n);}}catch(i){let s=hd(i);if(i instanceof x||s.permanent){e.deadLetterWork(n.id,this.owner,s),this.logWorkTransition("dead_letter",n,{attempt:n.attempts,errorCategory:s.category},"error");return}let a=this.now()+Math.max(yd(n.attempts,this.random()),s.retryAfterMs??0);if(s.retryWithoutAttempt){e.deferWork(n.id,this.owner,s,a),this.logWorkTransition("deferred",n,{attempt:n.attempts,nextAttemptAt:a,errorCategory:s.category},"warn");return}e.retryWork(n.id,this.owner,s,a),this.logWorkTransition("retry_wait",n,{attempt:n.attempts,nextAttemptAt:a,errorCategory:s.category},"warn");}finally{clearInterval(r);}}logDegradation(e,n,o){y({event:"hook.runtime.degraded",identity:{projectRoot:this.projectRoot,sessionId:o?.sessionId,turnId:o?.turnId,executionId:o?.executionId},level:"warn",timestamp:this.now(),data:{stage:`work_${e}`,workId:o?.id,workKind:o?.kind,reason:Dr(n)}});}logWorkTransition(e,n,o,r="info"){try{y({event:"durable.work.transitioned",identity:{projectRoot:this.projectRoot,sessionId:n.sessionId,turnId:n.turnId,executionId:n.executionId},level:r,timestamp:this.now(),data:{stage:e,workId:n.id,workKind:n.kind,...o}});}catch{}}};function Qt(t,e){return Number.isSafeInteger(t)&&t>0?t:e}function hd(t){if(t instanceof x)return {category:t.category,message:t.message};let e=t&&typeof t=="object"?t:null,n=typeof e?.category=="string"?e.category:"runtime_error";return {category:n,message:Dr(t),retryAfterMs:typeof e?.retryAfterMs=="number"&&Number.isFinite(e.retryAfterMs)?Math.max(0,e.retryAfterMs):void 0,retryWithoutAttempt:e?.retryWithoutAttempt===true,permanent:n==="policy_verification_failed"||n==="invalid_payload"}}function yd(t,e){let n=Math.min(gd,500*2**Math.max(0,t-1)),o=Math.floor(n*.2*Math.max(0,Math.min(1,e)));return n+o}function Dr(t){return t instanceof Error?t.message:String(t)}var kd=250;function Pr(t,e=process.env){let n=Or(join(getDevFlowStateRoot({env:e}),"config.json")),o=Or(join(t,".devflow","config.json")),r=Zt(e.DEVFLOW_HOOK_PROFILE)??Zt(o.profile)??Zt(n.profile)??"standard",i=Number(e.DEVFLOW_HOOK_ACK_BUDGET_MS??o.acknowledgementBudgetMs??n.acknowledgementBudgetMs),s=Number.isSafeInteger(i)&&i>0?Math.min(i,5e3):kd,a=new Set([...en(n.disabledHandlers),...en(o.disabledHandlers),...en(e.DEVFLOW_DISABLED_HOOK_HANDLERS?.split(","))].map(xd).filter(c=>!!c));return {profile:r,acknowledgementBudgetMs:s,disabledHandlers:a}}async function jr(t,e,n,o,r=process.env.CLAUDE_PROJECT_DIR||process.cwd()){let i,s=new Promise(a=>{i=setTimeout(()=>{y({event:"hook.runtime.degraded",identity:{projectRoot:r},level:"warn",timestamp:Date.now(),data:{stage:"acknowledgement_budget",eventName:t,budgetMs:e,fallback:"timeout_result"}}),a(o());},e),i.unref();});try{return await Promise.race([Promise.resolve().then(n),s])}finally{i&&clearTimeout(i);}}async function $r(t,e=process.env){let n=e.DEVFLOW_HOST_ADAPTER??(e.CLAUDE_PROJECT_DIR||e.CLAUDE_PLUGIN_ROOT||e.CLAUDE_CODE_ENTRYPOINT?"claude-code":void 0),o=await selectHostAdapter({projectRoot:t,env:e,explicitHost:n});if(o.status==="failed")throw new Error(`host_adapter_selection_failed:${o.code}:${o.reason}`);let r=await o.adapter.capabilities({projectRoot:t,env:e,explicitHost:n});return {hostId:o.adapter.id,capabilities:new Map(r.map(i=>[i.capability,i])),profiles:new Set(o.adapter.hooks?.profileSupport??[])}}function tn(t,e,n){let o=Sd(t,e.profile);if(!n.profiles.has(e.profile))return {enabled:false,policy:"fail_open",reason:`hook_profile_${e.profile}_unsupported_by_${n.hostId}`,fallback:"host_event_continues_without_devflow_handler"};if(e.disabledHandlers.has(t))return {enabled:false,policy:"fail_open",reason:"hook_handler_disabled",fallback:"host_event_continues_without_devflow_handler"};if(e.profile==="minimal"&&!bd.has(t))return {enabled:false,policy:"fail_open",reason:"hook_handler_not_in_minimal_profile",fallback:"critical_receipts_only"};let r=Rd[t];if(!r)return {enabled:true,policy:o};let i=n.capabilities.get(r);return !i||i.status!=="supported"?{enabled:false,policy:"fail_open",reason:i?.reason??`${r}_unsupported_by_${n.hostId}`,fallback:i?.fallback??"host_event_continues_without_native_hook_processing"}:{enabled:true,policy:o}}var bd=new Set(["session-start","user-prompt-submit","stop","session-end","memory-snapshot"]),Rd={"session-start":"hooks.session_start","user-prompt-submit":"hooks.prompt_submit","pre-tool-use":"hooks.pre_tool_use","post-tool-use":"hooks.post_tool_use","post-tool-use-failure":"hooks.post_tool_use",stop:"hooks.stop","session-end":"hooks.session_end"};function Sd(t,e){return t==="user-prompt-submit"||t==="stop"||t==="session-end"?"enqueue_and_open":t==="pre-tool-use"&&e==="strict"?"fail_closed":"fail_open"}function Or(t){if(!existsSync(t))return {};try{let n=JSON.parse(readFileSync$1(t,"utf8")).hooks;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return {}}}function Zt(t){return t==="minimal"||t==="standard"||t==="strict"?t:void 0}function en(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function xd(t){let e=t.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase();return ({sessionstart:"session-start",userpromptsubmit:"user-prompt-submit",pretooluse:"pre-tool-use",posttooluse:"post-tool-use",posttoolusefailure:"post-tool-use-failure",sessionend:"session-end",precompact:"pre-compact",memorysnapshot:"memory-snapshot"}[e.replace(/-/g,"")]??e)||void 0}var ot=class{decode(e){let n;try{let d=JSON.parse(e.rawInput);if(!d||typeof d!="object"||Array.isArray(d))return null;n=d;}catch{return null}let o=Td[e.requestType];if(typeof n.hook_event_name=="string"&&n.hook_event_name!==o)return null;let r=resolve(on(n.cwd)??e.projectRoot??process.cwd()),i=on(n.session_id),s=on(n.tool_use_id),a=e.receivedAt??Date.now(),c={requestType:e.requestType,projectRoot:r,sessionId:i??"",toolUseId:s??"",payloadHash:stableRuntimeHash(n)};return {schemaVersion:"normalized-hook-event.v1",eventId:`hook-event:${stableRuntimeHash(c).slice(0,32)}`,requestType:e.requestType,eventName:o,projectRoot:r,...i?{sessionId:i}:{},...s?{toolUseId:s}:{},retryKey:`${e.requestType}:${stableRuntimeHash(c).slice(0,24)}`,receivedAt:a,rawInput:e.rawInput,payload:n}}},Td={"session-start":"SessionStart","user-prompt-submit":"UserPromptSubmit","pre-tool-use":"PreToolUse","post-tool-use":"PostToolUse","post-tool-use-failure":"PostToolUseFailure",stop:"Stop","session-end":"SessionEnd","pre-compact":"PreCompact","memory-snapshot":"MemorySnapshot"};function on(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function Fr(t){let e=Object.keys(t.handlers).map(n=>{let o=Cd[n];return [n,{requestType:n,eventName:o,capability:Dd[n],failurePolicy:t.failurePolicy(n),acknowledgeWithinBudget:Ad.has(n),handler:t.handlers[n],timeoutResult:()=>Md(n)}]});return new Map(e)}async function Hr(t){let e=t.registry.get(t.requestType);if(!e)return {status:"degraded",reason:"unknown_hook_handler",fallback:"host_event_continues"};let n=new ot().decode({requestType:t.requestType,rawInput:t.rawInput,projectRoot:t.projectRoot}),o=()=>Promise.resolve(e.handler(n?.rawInput??t.rawInput));return e.acknowledgeWithinBudget?jr(e.eventName,t.acknowledgementBudgetMs,o,e.timeoutResult,t.projectRoot):o()}var Ad=new Set(["stop","session-end","user-prompt-submit"]),Cd={"session-start":"SessionStart","user-prompt-submit":"UserPromptSubmit","pre-tool-use":"PreToolUse","post-tool-use":"PostToolUse","post-tool-use-failure":"PostToolUseFailure",stop:"Stop","session-end":"SessionEnd","pre-compact":"PreCompact","memory-snapshot":"MemorySnapshot"},Dd={"session-start":"hooks.session_start","user-prompt-submit":"hooks.prompt_submit","pre-tool-use":"hooks.pre_tool_use","post-tool-use":"hooks.post_tool_use","post-tool-use-failure":"hooks.post_tool_use",stop:"hooks.stop","session-end":"hooks.session_end"};function Md(t){return t==="user-prompt-submit"?{hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",additionalContext:"DevFlow background processing exceeded its acknowledgement budget; continue in degraded mode and do not claim unreceipted work completed."}}:{status:"degraded",reason:"hook_budget_exceeded",fallback:t==="session-end"?"durable_session_recovery":"background_processing"}}var it=class{constructor(e){this.records=new Map;this.path=join(P(e),"hook-handler-health.json"),this.load();}recordSuccess(e,n,o=Date.now()){let r={handler:e,host:n,status:"healthy",consecutiveFailures:0,lastSuccessAt:o,updatedAt:o};return this.records.set(rt(e,n),r),this.persist(),r}recordFailure(e,n,o,r,i=Date.now()){let s=this.records.get(rt(e,n)),a=(s?.consecutiveFailures??0)+1,c=Math.min(5*6e4,1e3*2**Math.min(8,a-1)),d={handler:e,host:n,status:"degraded",consecutiveFailures:a,lastFailureCategory:o,lastFailureReason:r.slice(0,500),retryAt:i+c,lastSuccessAt:s?.lastSuccessAt,updatedAt:i};return this.records.set(rt(e,n),d),this.persist(),d}list(){return [...this.records.values()].sort((e,n)=>e.handler.localeCompare(n.handler))}load(){try{let e=JSON.parse(readFileSync$1(this.path,"utf8"));for(let n of e)n?.handler&&n?.host&&this.records.set(rt(n.handler,n.host),n);}catch{}}persist(){try{mkdirSync$1(dirname$1(this.path),{recursive:!0,mode:448});let e=`${this.path}.${process.pid}.tmp`;writeFileSync$1(e,JSON.stringify(this.list(),null,2),{mode:384}),renameSync(e,this.path);}catch{}}};function rt(t,e){return `${e}\0${t}`}function Lr(t,e){return e||(t==="post-tool-use"||t==="post-tool-use-failure"?{status:"ok"}:{status:"ok"})}function Nr(t){let e=t instanceof Error?t.message:String(t??"hook_handler_failed");return {category:/timeout|budget|deadline/iu.test(e)?"timeout":/sqlite|database|locked|busy/iu.test(e)?"storage":/socket|connect|unreachable/iu.test(e)?"transport":/json|parse|schema|invalid/iu.test(e)?"protocol":"handler",reason:e}}function qr(t){let e=Do({projectRoot:t.projectRoot,sessionId:t.sessionId,transcriptPath:t.transcriptPath,runtimeStore:t.runtimeStore}),n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{Ud(t.runtimeStore,t.sessionId,n);let o=n.getPendingMemoryTurn(t.projectRoot,t.sessionId),r=o?n.markMemoryTurnStopPrompted(o.turnId):!1,i=[];e&&i.push(e.reason),o&&r&&i.push(et(o)),o&&!r&&qd(n,o.turnId)&&Wd(Be(t.transcriptPath))&&i.push(`DevFlow explicit memory ${o.turnId} still has no canonical receipt. Remove the memory-success claim and tell the user that the memory was not saved, or complete the pending turn.`);let a=n.listSessionObligations(t.projectRoot,t.sessionId,["open"]).map(c=>({obligationId:c.obligationId,kind:c.kind,action:c.kind==="memory_decision"?"Call mcp__devflow__memory_decide_turn using the canonical turn ID.":c.kind==="evidence_contract"?c.payload.subtype==="policy_verification"?`Complete the required project verification: ${String(c.payload.command??c.payload.verificationKind??"unknown command")}.`:"Return a final answer that satisfies the canonical evidence contract.":"Allow SessionEnd durable finalization to complete.",canonicalInput:c.kind==="memory_decision"&&c.turnId?{turnId:c.turnId}:void 0}));return i.length>0?{decision:"block_once",unresolved:a,additionalContext:["DevFlow has unresolved terminal obligations. Complete all actions below before stopping.",...i].join(`
30
30
 
31
- `)}:a.length>0?{decision:"degrade",unresolved:a,additionalContext:"DevFlow terminal obligations remain unresolved after their one-shot correction budget."}:{decision:"allow",unresolved:[]}}finally{n.close();}}function Nd(t,e){return !!t.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${e}`)}function qd(t){if(!t)return false;let e=t.normalize("NFKC").replace(/\s+/gu," ");return /(?:未|没有|无法|失败|暂未|尚未).{0,24}(?:记住|记下|记录|保存|持久化|回执)|(?:memory|receipt).{0,24}(?:failed|missing|pending|degraded|not saved)|status=(?:pending|degraded|rejected|failed)/iu.test(e)?false:/(?:已|已经|成功).{0,20}(?:记住|记下|记录|保存|持久化)|跨会话生效|(?:memory|preference).{0,20}(?:saved|remembered|persisted)|status=(?:accepted|committed)/iu.test(e)}function Wd(t,e,n){let o=t.get(e);if(o){for(let r of o.evidenceObligations)n.upsertSessionObligation({obligationId:`evidence:${r.obligationId}`,projectRoot:o.projectRoot,sessionId:e,executionId:o.executionId,kind:"evidence_contract",state:"open",payload:{contract:r.contract,runtimeObligationId:r.obligationId},createdAt:r.promptedAt,updatedAt:o.lastActivityAt});for(let r of o.evidenceOutcomes){let i=`evidence:${r.obligationId}`,s=n.getSessionObligation(o.projectRoot,e,i);if(!s||s.state!=="open"&&!(s.state==="degraded"&&r.status==="resolved"))continue;let a=r.status==="resolved"?`evidence-receipt:${createHash("sha256").update(`${r.obligationId}\0${r.completedAt}\0${r.attempt}`).digest("hex").slice(0,24)}`:void 0;n.resolveSessionObligation({projectRoot:o.projectRoot,sessionId:e,obligationId:i,state:r.status==="resolved"?"satisfied":"degraded",receiptId:a,reason:r.reason,resolvedAt:r.completedAt});}}}var Ud=[/\b(?:rm\s+-rf|sudo|chmod|chown|force\s+push|reset\s+--hard|publish|release|deploy)\b/iu,/\b(?:secret|credential|token|password|security|authentication|authorization)\b/iu,/(?:删除|强制推送|发布|部署|凭据|密钥|安全|权限)/u],zd=[/\b(?:migration|upgrade|dependency|dependencies|generated files?|write all|rewrite)\b/iu,/(?:迁移|升级|依赖|生成文件|批量写入)/u];function rn(t){let e=`${t.instruction}
32
- ${JSON.stringify(t.trigger)}`,n=[];Ud.some(r=>r.test(e))&&n.push("high_risk_operation"),zd.some(r=>r.test(e))&&n.push("broad_or_migrating_change"),t.kind==="correction"&&n.push("user_correction_requires_observation");let o=n.includes("high_risk_operation")?"high":n.includes("broad_or_migrating_change")||t.scope==="global"?"medium":"low";return {risk:o,manualOnly:o==="high"||n.includes("broad_or_migrating_change"),reasons:n}}var Bd=new Set(["project_convention","user_preference","decision_made","config_discovery"]);function an(t){let e=t.payload.executionId?t.database.getSkillExecution(t.payload.executionId):t.database.getLatestSkillExecutionForSession(t.payload.sessionId),n=t.database.listHostActionsForSession(t.payload.projectRoot,t.payload.sessionId,t.payload.executionId),o=n.find(u=>u.state==="verified"),r=n.find(u=>["failed","cancelled","degraded"].includes(u.state)),i=r?"negative":o?"positive":"unknown",s=new Set,a=[],c=0,d=0;for(let u of t.evidence){if(!Jd(u)){d+=1;continue}let l=Br(u),m=Vd(u,e?.skillName),f=Jr(u),p=Yd(t.payload.projectRoot,l,u.facetKey??u.semanticKey??u.id,m),g=t.database.getLearningCandidate(p),k=rn({scope:"project",kind:l,instruction:f,trigger:m});t.database.upsertLearningCandidate({id:p,projectRoot:t.payload.projectRoot,scope:"project",kind:l,trigger:m,instruction:f,confidence:Kd(u),manualOnly:k.manualOnly,risk:k.risk});g&&g.instruction!==f&&t.database.addLearningCandidateEvidence({id:Wr(p,t.payload.sessionId,u.id,"contradicting"),candidateId:p,projectRoot:t.payload.projectRoot,sessionId:t.payload.sessionId,executionId:t.payload.executionId,memoryObservationId:u.id,sourceType:"correction",polarity:"contradicting",outcome:i,evidenceHash:Ur(p,t.payload,u,"contradicting"),receipt:t.payload.closureReceipt,payload:{previousInstruction:g.instruction,replacementInstruction:f,projectRevision:t.payload.projectRevision},createdAt:u.createdAt});let R=t.database.addLearningCandidateEvidence({id:Wr(p,t.payload.sessionId,u.id,"supporting"),candidateId:p,projectRoot:t.payload.projectRoot,sessionId:t.payload.sessionId,executionId:t.payload.executionId,memoryObservationId:u.id,outcomeId:o?.id??r?.id,sourceType:Gd(u),polarity:"supporting",outcome:i,evidenceHash:Ur(p,t.payload,u,"supporting"),receipt:t.payload.closureReceipt,payload:{semanticKey:u.semanticKey,facetKey:u.facetKey,evidenceStatus:u.evidenceStatus,source:u.source,projectRevision:t.payload.projectRevision,executionStatus:e?.status,policyReasons:k.reasons},createdAt:u.createdAt});c+=1,s.add(p),t.rolloutMode!=="off"&&R.state==="candidate"&&R.supportingSessions>=3&&R.successfulOutcomes>=2&&t.database.transitionLearningCandidate(p,{target:"shadow",reason:"evidence_threshold_satisfied"}).state==="shadow"&&a.push(p);}return {considered:t.evidence.length,accepted:c,excluded:d,candidateIds:[...s],promotedToShadow:a}}function Jd(t){return !(!Bd.has(t.type)||t.source!=="explicit_intent"&&t.source!=="manual"&&t.evidenceStatus!=="verified"||!t.narrative.trim()&&!t.title.trim())}function Br(t){return t.type==="decision_made"?"workflow":t.type==="user_preference"&&(t.semanticValue.startsWith("--")||t.tools.length>0)?"tool_preference":"convention"}function Vd(t,e){return {...e?{skills:[e]}:{},...t.entities.length>0?{entities:[...new Set(t.entities)].slice(0,8)}:{},...t.files.length>0?{files:[...new Set(t.files)].slice(0,8)}:{},...t.tools.length>0?{commands:[...new Set(t.tools)].slice(0,8)}:{},semantic:{subject:t.semanticSubject,predicate:t.semanticPredicate,value:t.semanticValue,polarity:t.semanticPolarity}}}function Jr(t){return (t.narrative.trim()||t.title.trim()).replace(/\s+/gu," ").slice(0,1200)}function Kd(t){let e=t.source==="explicit_intent"?.08:0;return Math.max(0,Math.min(1,t.confidence+e))}function Gd(t){return t.semanticPolarity==="negative"?"correction":Br(t)==="tool_preference"?"tool_preference":t.source==="explicit_intent"?"memory":"convention"}function Yd(t,e,n,o){let r={...o,semantic:void 0};return `learning:${createHash("sha256").update(`${t}\0project\0${e}\0${n}\0${stableLearningJson(r)}`).digest("hex").slice(0,24)}`}function Wr(t,e,n,o){return `learning-evidence:${createHash("sha256").update(`${t}\0${e}\0${n}\0${o}`).digest("hex").slice(0,24)}`}function Ur(t,e,n,o){return createHash("sha256").update(stableLearningJson({candidateId:t,sessionId:e.sessionId,executionId:e.executionId,closureReceipt:e.closureReceipt,projectRevision:e.projectRevision,observationId:n.id,instruction:Jr(n),polarity:o})).digest("hex")}var ie=3e4,ln=1e3,ml=new Set(["git","npm","pnpm","yarn"]);function Vr(t){return {"workflow.worker_start":async({item:e})=>pl(t,e),"workflow.worker_monitor":async({item:e})=>fl(t,e),"workflow.worker_verify":async({item:e})=>gl(t,e),"workflow.worker_merge":async({item:e})=>hl(t,e),"workflow.worker_cleanup":async({item:e})=>yl(t,e)}}async function pl(t,e){await Te(t,e,async(n,o)=>{if(o.state==="running"||o.state==="starting"){cn(n,o);return}if(o.state!=="planned")return;let r=`worker-plane:${process.pid}`;n.leaseWorkflowWorker(t,o.workerId,r,ie);let i=await createManagedWorktree({projectRoot:t,runId:o.runId,stepId:o.stepId,baseRevision:o.baseRevision,registered:!0});if(i.worktreePath!==o.worktreePath||i.branch!==o.branch){n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"hold",leaseOwner:r,reason:"managed_worktree_identity_mismatch"});return}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"starting",leaseOwner:r});let s=Yr(o.workerId),a=vl(o);createWorkerArtifacts(s,a);let d=createDefaultHostAdapterRegistry().list().find(f=>f.id===o.host);if(!d)throw new x("unsupported_worker_host",`Unsupported worker host ${o.host}`);let u=se(o.handoff.actionId,"actionId"),l=n.getHostAction(t,u);if(!l)throw new x("worker_host_action_missing",`Host action ${u} was not found`);l.state==="waiting"&&n.startHostAction({actionId:u,projectRoot:t});let m=launchWorker(d,{workerId:o.workerId,runId:o.runId,stepId:o.stepId,host:o.host==="codex"?"codex":"claude-code",worktreePath:o.worktreePath,taskFile:s.taskFile,handoffFile:s.handoffFile,statusFile:s.statusFile,sessionId:o.sessionId??"worker",executionId:o.executionId??o.workerId,contextReceipt:o.contextReceipt,timeoutMs:30*6e4},s,{onHeartbeat:()=>{let f=openGlobalDevFlowDatabase();try{f.heartbeatWorkflowWorker(t,o.workerId,r,ie);}catch{}finally{f.close();}}});_l(s,{state:"running",pid:m.child.pid,owner:r,startedAt:Date.now()}),n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"running",leaseOwner:r,heartbeatAt:Date.now(),leaseExpiresAt:Date.now()+ie}),cn(n,o),m.completion.finally(()=>{let f=openGlobalDevFlowDatabase();try{cn(f,o,Date.now());}finally{f.close();}});});}async function fl(t,e){await Te(t,e,async(n,o)=>{if(o.state!=="running"&&o.state!=="starting")return;let r=Yr(o.workerId);if(existsSync(r.handoffFile)){let c=readWorkerHandoff(r.handoffFile,{workerId:o.workerId,runId:o.runId,stepId:o.stepId,contextReceipt:o.contextReceipt,worktreePath:o.worktreePath}),d=se(o.handoff.actionId,"actionId");n.reportHostAction({actionId:d,projectRoot:t,report:{workerId:o.workerId,handoff:c},evidenceHash:Qr(c)}),n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"reported",leaseOwner:o.leaseOwner,finalRevision:c.finalRevision,handoff:{...o.handoff,terminalHandoff:c}}),n.enqueueWork({idempotencyKey:`workflow-worker-verify:${o.workerId}:${c.finalRevision}`,kind:"workflow.worker_verify",projectRoot:t,payload:{workerId:o.workerId}});return}let i=Il(r),s=typeof i?.pid=="number"?i.pid:void 0;if(s&&kl(s)){let c=typeof i?.startedAt=="number"?i.startedAt:o.updatedAt;if(Date.now()-c>30*6e4){try{process.kill(s,"SIGTERM");}catch{}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_process_timeout"});let u=se(o.handoff.actionId,"actionId");n.failHostAction({actionId:u,projectRoot:t,report:{reason:"worker_process_timeout"}});return}let d=o.leaseOwner??(typeof i?.owner=="string"?i.owner:void 0);throw d?(n.heartbeatWorkflowWorker(t,o.workerId,d,ie),Xr("worker_running",ln)):new x("worker_lease_owner_missing","Worker lease owner is missing")}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_exited_without_handoff"});let a=se(o.handoff.actionId,"actionId");n.failHostAction({actionId:a,projectRoot:t,report:{reason:"worker_exited_without_handoff"}});});}async function gl(t,e){await Te(t,e,async(n,o)=>{if(o.state!=="reported")return;n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"verifying",leaseOwner:o.leaseOwner});let r=o.handoff.terminalHandoff;if(!r)throw new x("worker_handoff_missing","Persisted worker handoff is missing");let i=se(o.handoff.actionId,"actionId"),s=n.getHostAction(t,i);if(!s)throw new x("worker_host_action_missing",`Host action ${i} was not found`);let a=Gr(o),c=new GraderRegistry,d=await Kr(n,o,async()=>verifyWorkerOutput({workerId:o.workerId,projectRoot:t,worktreePath:o.worktreePath,baseRevision:o.baseRevision,parentRevision:await wl(t),contextReceipt:o.contextReceipt,allowedFiles:o.allowedFiles,handoff:r,hostAction:s,verificationCommands:a,graderIds:["receipt_validity","lifecycle_terminal_state","workflow_evidence"],graderRunner:{run:async u=>{let l=await c.run({taskId:o.stepId,taskKind:u.taskKind,projectRoot:u.projectRoot,acceptanceCriteria:[],evidence:u.evidence});return {...l,unavailableBlocking:l.unavailableRequired}}}}));if(!d.passed){n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:d.state,leaseOwner:o.leaseOwner,reason:d.reason}),d.state==="failed"&&n.failHostAction({actionId:i,projectRoot:t,outcome:"failed",report:{...s.report,verification:d},evidenceHash:d.simulationHash});return}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"merge_ready",leaseOwner:o.leaseOwner,finalRevision:d.finalRevision,handoff:{...o.handoff,terminalHandoff:r,verification:d}}),n.enqueueWork({idempotencyKey:`workflow-worker-merge:${o.workerId}:${d.finalRevision}`,kind:"workflow.worker_merge",projectRoot:t,payload:{workerId:o.workerId}});});}async function hl(t,e){await Te(t,e,async(n,o)=>{if(o.state!=="merge_ready")return;let r=o.handoff.verification;if(!r?.passed)throw new x("worker_verification_missing","Verified merge evidence is missing");let i=se(o.handoff.actionId,"actionId"),s=new SerializedWorkerMergeQueue(n,{onMerged:async({mergeCommit:c})=>{n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"merged",leaseOwner:o.leaseOwner,finalRevision:o.finalRevision,reason:`merged:${c}`});let d=n.getHostAction(t,i);n.verifyHostAction({actionId:i,projectRoot:t,report:{...d?.report??{},mergeCommit:c,verification:r},evidenceHash:Qr({mergeCommit:c,verification:r})});},scheduleCleanup:()=>{n.enqueueWork({idempotencyKey:`workflow-worker-cleanup:${o.workerId}:merged`,kind:"workflow.worker_cleanup",projectRoot:t,payload:{workerId:o.workerId}});}}),a=await Kr(n,o,()=>s.enqueueAndMerge({workerId:o.workerId,projectRoot:t,baseRevision:o.baseRevision,verification:r,message:`merge(devflow-worker): ${o.runId}/${o.stepId}`}));a.state==="conflict"&&n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"hold",leaseOwner:o.leaseOwner,reason:a.reason??"merge_conflict"});});}async function yl(t,e){await Te(t,e,async(n,o)=>{let r=e.payload,i=await cleanupManagedWorktree({repositoryRoot:t,worktreePath:o.worktreePath,branch:o.branch,registered:!0,handoffDurable:!!o.handoff.terminalHandoff||r.operatorApproved===!0});if(!i.cleaned)throw Xr(`cleanup_${i.reason??"refused"}`,3e4)});}async function Kr(t,e,n){let o=e.leaseOwner;if(!o)return n();let r=setInterval(()=>{try{t.heartbeatWorkflowWorker(e.projectRoot,e.workerId,o,ie);}catch{}},Math.floor(ie/3));r.unref();try{return await n()}finally{clearInterval(r);}}async function Te(t,e,n){let o=bl(e.payload),r=openGlobalDevFlowDatabase();try{let i=r.getWorkflowWorker(t,o);if(!i)throw new x("worker_not_found",`Worker ${o} was not found`);await n(r,i);}finally{r.close();}}function vl(t){let e=t.handoff.task;if(!e||typeof e!="object"||Array.isArray(e))throw new x("worker_task_missing","Worker task envelope is missing");let n=Gr(t);return {workerId:t.workerId,runId:t.runId,stepId:t.stepId,projectRoot:t.projectRoot,worktreePath:t.worktreePath,baseRevision:t.baseRevision,contextReceipt:t.contextReceipt,retrievalSessionId:t.retrievalSessionId,allowedFiles:t.allowedFiles,requiredTools:[],task:e,verification:{commands:n,graders:["receipt_validity","lifecycle_terminal_state","workflow_evidence"]},constraints:{recursiveWorkers:false,maxContextCycles:3}}}function Gr(t){let e=t.handoff.verificationCommands;if(!Array.isArray(e)||e.length===0)throw new x("verification_contract_missing","Worker verification commands are missing");return e.map(n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new x("verification_contract_invalid","Worker verification command is malformed");let o=n;if(typeof o.command!="string"||!ml.has(o.command)||!Array.isArray(o.args)||o.args.some(r=>typeof r!="string"))throw new x("verification_contract_invalid","Worker verification command is not allowlisted");return {command:o.command,args:o.args}})}function Yr(t){let e=workerCoordinationRoot(t,homedir());return {root:e,taskFile:join(e,"task.json"),handoffFile:join(e,"handoff.json"),statusFile:join(e,"status.json"),stdoutFile:join(e,"stdout.log"),stderrFile:join(e,"stderr.log")}}function _l(t,e){writeJsonAtomic(t.statusFile,e);}function Il(t){try{return JSON.parse(readFileSync$1(t.statusFile,"utf8"))}catch{return null}}function cn(t,e,n=Date.now()+ln){t.enqueueWork({idempotencyKey:`workflow-worker-monitor:${e.workerId}:${Math.floor(n/ln)}`,kind:"workflow.worker_monitor",projectRoot:e.projectRoot,payload:{workerId:e.workerId},nextAttemptAt:n,maxAttempts:1e3});}async function wl(t){let{gitRevision:e}=await import('@devflow-tools/workflow-engine');return e(t,"HEAD")}function kl(t){try{return process.kill(t,0),!0}catch{return false}}function Xr(t,e){return Object.assign(new Error(t),{category:t,retryAfterMs:e,retryWithoutAttempt:true})}function bl(t){if(!t||typeof t!="object"||typeof t.workerId!="string")throw new x("invalid_worker_payload","Worker work item requires workerId");return t.workerId}function se(t,e){if(typeof t!="string"||!t.trim())throw new x("worker_identity_missing",`Worker ${e} is missing`);return t}function Qr(t){return createHash("sha256").update(JSON.stringify(t)).digest("hex")}var xl=new Set(["Write","Edit","NotebookEdit"]);function ni(t){if(!xl.has(t.toolName)||Dl(t.toolResponse))return null;let e=Cl(t.projectRoot,t.toolInput);if(!e)return null;let n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let o=n.getActiveContextReceipt(t.projectRoot,t.sessionId,t.executionId),r=o?.canonicalAction?.verificationPlan??[];if(!o||r.length===0)return null;let i=[],s=[];for(let c of r){let d=El({projectRoot:t.projectRoot,targetFile:e,kind:c.kind,mode:c.mode==="write"?"write":"check",required:c.required===!0,contextReceipt:o.contextHash}),u=`${o.contextHash}\0${t.toolUseId??e}\0${c.kind}\0${e}`,l=`policy-verification:${createHash("sha256").update(u).digest("hex")}`,m=Date.now();if(!d){let g=`verification_unavailable:${c.kind}`;n.upsertSessionObligation({obligationId:l,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,kind:"evidence_contract",state:"degraded",payload:{subtype:"policy_verification",status:"unknown",verificationKind:c.kind,targetFile:e,contextReceipt:o.contextHash},reason:g,createdAt:m,updatedAt:m,resolvedAt:m}),s.push(c.kind),c.required===!0&&C({projectRoot:t.projectRoot,sessionId:t.sessionId,requestId:o.requestId,executionId:t.executionId,kind:"verification.failed",payload:{receiptId:l,reasonCode:g},dedupeKey:`${l}:unavailable`,producer:"devflow-verification-scheduler"});continue}let f={...d,obligationId:l,sessionId:t.sessionId,executionId:t.executionId,requestId:o.requestId};n.upsertSessionObligation({obligationId:l,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,kind:"evidence_contract",state:"open",payload:{subtype:"policy_verification",status:"scheduled",verificationKind:c.kind,command:d.display,targetFile:e,contextReceipt:o.contextHash,required:c.required===!0},createdAt:m,updatedAt:m});let p=n.enqueueWork({idempotencyKey:l,kind:"verification.policy",projectRoot:t.projectRoot,sessionId:t.sessionId,payload:f,maxAttempts:2,nextAttemptAt:m});C({projectRoot:t.projectRoot,sessionId:t.sessionId,requestId:o.requestId,executionId:t.executionId,kind:"durable_work.owned",payload:{workId:p.id,obligation:"verification"},dedupeKey:`${p.id}:owned`,producer:"devflow-verification-scheduler"}),i.push(d.display);}return [i.length>0?`DevFlow scheduled policy verification: ${i.join(" && ")}`:"",s.length>0?`Verification unavailable and recorded as unknown: ${s.join(", ")}`:""].filter(Boolean).join(`
33
- `)||null}finally{n.close();}}async function oi(t,e){let n=Tl(t,e.payload),o=await Al(n,t),r=n.kind==="typecheck"?$l(o.output,n.targetFile,t):[],i=ei({command:n.command,args:n.args}),s=openGlobalDevFlowDatabase();try{let a=Hl(t),c=n.kind==="typecheck"?s.getPolicyVerificationBaseline(t,n.kind,i):null,d=c&&c.sourceRevision===a?c:null,u=d?r.filter(b=>!d.diagnosticHashes.includes(b)):[],l;o.spawnError||/could not determine executable|command not found|not recognized as an internal|ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL/iu.test(o.output)?l="unavailable":o.timedOut?l="unknown":o.exitCode===0?l="passed":n.kind==="typecheck"&&!d?l="unknown":n.kind==="typecheck"&&u.length===0?l="passed":l="failed";let m=createHash("sha256").update(o.output).digest("hex"),f=`verification-receipt:${ei({obligationId:n.obligationId,commandHash:i,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:m,diagnosticHashes:r,introduced:u,status:l})}`,p={status:l,kind:n.kind,command:n.display,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:m,diagnosticHashes:r,introducedDiagnosticHashes:u,baselineAvailable:d!==null,receiptId:f},g=s.getWorkByIdempotencyKey(n.obligationId)?.id,k=s.getSessionObligation(t,n.sessionId,n.obligationId);if(k?.state==="open"&&(s.upsertSessionObligation({...k,payload:{...k.payload,status:l,outcome:p},updatedAt:Date.now()}),l!=="failed"&&s.resolveSessionObligation({projectRoot:t,sessionId:n.sessionId,obligationId:n.obligationId,state:l==="passed"?"satisfied":"degraded",receiptId:f,reason:l==="unknown"?"verification_result_unknown":l==="unavailable"?"verification_command_unavailable":void 0})),n.kind==="typecheck"&&o.exitCode===0&&s.upsertPolicyVerificationBaseline({projectRoot:t,kind:n.kind,commandHash:i,diagnosticHashes:[],sourceRevision:a,updatedAt:Date.now()}),Fl(s,n,p),C({projectRoot:t,sessionId:n.sessionId,requestId:n.requestId,executionId:n.executionId,kind:l==="passed"?"verification.succeeded":"verification.failed",payload:{receiptId:f,reasonCode:`verification_${l}`,verificationKind:n.kind},dedupeKey:f,producer:"devflow-verification-worker"}),g&&l!=="failed"&&C({projectRoot:t,sessionId:n.sessionId,requestId:n.requestId,executionId:n.executionId,kind:"durable_work.completed",payload:{workId:g,obligation:"verification"},dedupeKey:`${g}:completed`,producer:"devflow-verification-worker"}),l==="failed"){let b=new Error(`Policy verification failed: ${n.display}`);throw b.category="policy_verification_failed",b}return p}finally{s.close();}}function El(t){let e=Ml(t.projectRoot),n=Ol(t.projectRoot),o=e?.scripts??{},r={...e?.dependencies,...e?.devDependencies},i=null;if(t.kind==="formatter"&&(r.prettier||Pl(t.projectRoot)))i=st(n,"prettier",[t.mode==="write"?"--write":"--check",t.targetFile],6e4);else if(t.kind==="typecheck"){let s=pn(o,["typecheck","type-check","check:types"]);s?i=un(n,s,12e4):r.typescript&&existsSync(join(t.projectRoot,"tsconfig.json"))&&(i=st(n,"tsc",["--noEmit","--pretty","false"],12e4));}else if(t.kind==="lint"){let s=pn(o,["lint"]);s&&(i=un(n,s,12e4));}else if(t.kind==="test"){let s=jl(t.projectRoot,t.targetFile);s&&r.vitest?i=st(n,"vitest",["run",s],12e4):s&&(r.jest||r["@jest/core"])&&(i=st(n,"jest",["--runTestsByPath",s],12e4));}else if(t.kind==="build"){let s=pn(o,["build"]);s&&(i=un(n,s,18e4));}else t.kind==="generated_files"&&(i={command:"git",args:["diff","--check","--",t.targetFile],timeoutMs:3e4});return i?{kind:t.kind,...i,display:[i.command,...i.args].map(Ll).join(" "),required:t.required,targetFile:t.targetFile,contextReceipt:t.contextReceipt}:null}function un(t,e,n){return t==="yarn"?{command:"yarn",args:["run",e],timeoutMs:n}:t==="pnpm"?{command:"pnpm",args:["run",e],timeoutMs:n}:t==="bun"?{command:"bun",args:["run",e],timeoutMs:n}:{command:"npm",args:["run",e],timeoutMs:n}}function st(t,e,n,o){return t==="pnpm"?{command:"pnpm",args:["exec",e,...n],timeoutMs:o}:t==="yarn"?{command:"yarn",args:[e,...n],timeoutMs:o}:t==="bun"?{command:"bunx",args:[e,...n],timeoutMs:o}:{command:"npx",args:["--no-install",e,...n],timeoutMs:o}}function Tl(t,e){if(!e||typeof e!="object"||Array.isArray(e))throw mn();let n=e,o=new Set(["npm","npx","pnpm","yarn","bun","bunx","git"]);if(!n.command||!o.has(n.command)||!Array.isArray(n.args)||!n.args.every(r=>typeof r=="string")||!n.obligationId||!n.sessionId||!n.kind||!n.targetFile||!n.contextReceipt||!n.display||!Number.isFinite(n.timeoutMs)||!ri(t,n.targetFile))throw mn();return n}function mn(){let t=new Error("Policy verification work payload is invalid");return t.category="invalid_payload",t}function Al(t,e){return new Promise(n=>{let o=spawn$1(t.command,t.args,{cwd:e,shell:false,stdio:["ignore","pipe","pipe"],env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),r="",i=false,s=u=>{i||(i=true,n(u));},a=u=>{r=(r+String(u)).slice(-32768);};o.stdout.on("data",a),o.stderr.on("data",a);let c=false,d=setTimeout(()=>{c=true,o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),1e3).unref();},t.timeoutMs);o.on("error",u=>{clearTimeout(d),s({exitCode:null,timedOut:false,spawnError:true,output:`${r}
34
- ${u.message}`.slice(-32768)});}),o.on("close",u=>{clearTimeout(d),s({exitCode:u,timedOut:c,spawnError:false,output:r});});})}function Cl(t,e){let n=e.file_path??e.notebook_path;if(typeof n!="string"||!n.trim())return null;let o=isAbsolute(n)?resolve(n):resolve(t,n);return ri(t,o)?relative(t,o).split(sep).join("/"):null}function ri(t,e){let n=isAbsolute(e)?resolve(e):resolve(t,e),o=relative(resolve(t),n);return o!==""&&o!==".."&&!o.startsWith(`..${sep}`)&&!isAbsolute(o)}function Dl(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.ok===false||e.success===false||e.isError===true||!!e.error}function Ml(t){try{return JSON.parse(readFileSync$1(join(t,"package.json"),"utf8"))}catch{return null}}function Ol(t){return existsSync(join(t,"pnpm-lock.yaml"))?"pnpm":existsSync(join(t,"yarn.lock"))?"yarn":existsSync(join(t,"bun.lockb"))||existsSync(join(t,"bun.lock"))?"bun":"npm"}function Pl(t){return [".prettierrc",".prettierrc.json",".prettierrc.js",".prettierrc.cjs","prettier.config.js","prettier.config.cjs"].some(e=>existsSync(join(t,e)))}function pn(t,e){return e.find(n=>typeof t[n]=="string"&&t[n].trim())??null}function jl(t,e){let n=e.replace(/\.[^.]+$/u,""),o=[".test.ts",".test.tsx",".spec.ts",".spec.tsx",".test.js",".spec.js"];for(let s of o){let a=`${n}${s}`;if(existsSync(join(t,a)))return a}let r=join(t,e.split("/").slice(0,-1).join("/")),i=e.split("/").at(-1)?.replace(/\.[^.]+$/u,"");if(!i||!existsSync(r))return null;try{return readdirSync$1(r).filter(s=>s.startsWith(`${i}.`)&&/\.(?:test|spec)\.[cm]?[jt]sx?$/u.test(s)).map(s=>relative(t,join(r,s)).split(sep).join("/"))[0]??null}catch{return null}}function $l(t,e,n){let o=e.split(sep).join("/"),r=resolve(n,e).split(sep).join("/"),i=t.split(/\r?\n/u).map(s=>s.trim().split(sep).join("/")).filter(s=>s.includes(o)||s.includes(r)).map(s=>s.replace(/:\d+:\d+/gu,":#:#").replace(/\(\d+,\d+\)/gu,"(#,#)")).filter(s=>/\berror\s+TS\d+\b/iu.test(s));return [...new Set(i.map(s=>createHash("sha256").update(s).digest("hex")))]}function Fl(t,e,n){if(!e.executionId)return;let o=t.getSkillExecution(e.executionId);if(!o)return;let r=o.metadata&&typeof o.metadata=="object"?o.metadata:{},i=Array.isArray(r.policyVerificationOutcomes)?r.policyVerificationOutcomes:[];t.updateSkillExecution(e.executionId,{metadata:{...r,policyVerificationOutcomes:[...i,n]}});}function Hl(t){try{let e=readFileSync$1(join(t,".git","HEAD"),"utf8").trim();return e.startsWith("ref:")?readFileSync$1(join(t,".git",e.slice(5).trim()),"utf8").trim():e}catch{return}}function ei(t){return createHash("sha256").update(JSON.stringify(t)).digest("hex")}function Ll(t){return /^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)}async function ci(t){let e=Date.now(),n=Ql(t.projectRoot),o=claudeCodeRuntimeAdapter.normalizePrompt(t.hostEvent??{session_id:t.sessionId,prompt:t.prompt},{projectRoot:n}),r=semanticTextHash(ai(o.rawPrompt)),i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100});try{let s=i.getTaskIntentArtifactBySource({projectRoot:n,sessionId:t.sessionId,sourceHash:r});if(s){let k=ii(s).identity,b=i.getRuntimeActivation(k.projectRoot,k.sessionId,k.turnId,s.version);if(!b)throw new Error(`RUNTIME_ACTIVATION_MISSING:${s.artifactHash}`);return {artifact:ii(s),memoryIdentity:si(s),activation:b,reused:!0}}let a=`turn:${ct(`${t.sessionId}\0${r}`)}`,c=`request:${ct(`${n}\0${t.sessionId}\0${a}`)}`,d={projectRoot:n,projectId:`project:${stableRuntimeHash(n).slice(0,20)}`,hostId:o.hostId,sessionId:t.sessionId,executionId:t.sessionId,turnId:a,requestId:c},u=1,l=resolveRuntimeActivationSnapshot({projectRoot:n,createdAt:o.timestamp}),m=Yl(o.rawPrompt),f={identity:d,version:u,rawPrompt:o.rawPrompt,normalizedPrompt:ai(o.rawPrompt),...o.command?{command:o.command}:{},slashArgs:o.slashArgs,...o.activeSkill?{activeSkill:o.activeSkill}:{},intent:"unknown",action:"unknown",entities:[],targetAnchors:m,policyConstraints:[],classificationEvidence:[],sourceEventIds:[o.sourceEventId??`host-event:${r.slice(0,24)}`],sourceHash:r,createdAt:o.timestamp},p={...f,artifactHash:Zl(f)};i.appendTaskIntentArtifact(Kl(p)),i.bindRuntimeActivation({identity:d,revision:u,snapshot:l});let g=Vl(i,p);return y({event:"host.prompt.normalized",identity:d,level:"info",timestamp:Date.now(),data:{sourceHash:r,command:p.command,activeSkill:p.activeSkill,rawPromptBytes:Buffer.byteLength(p.rawPrompt)}}),y({event:"intent.artifact.created",identity:d,level:"info",timestamp:Date.now(),data:{artifactHash:p.artifactHash,targetCount:m.length}}),y({event:"intent.artifact.persisted",identity:d,level:"info",timestamp:Date.now(),data:{artifactHash:p.artifactHash,version:p.version,sourceHash:p.sourceHash,authority:"immutable-intent",captureLatencyMs:Date.now()-e}}),y({event:"terminal.transition.persisted",identity:d,level:"info",timestamp:Date.now(),data:{state:"intent_bound",receiptId:g,sourceIntentHash:p.artifactHash}}),{artifact:p,memoryIdentity:si(p),activation:l,reused:!1}}finally{i.close();}}function Vl(t,e){let n=t.getLatestTerminalTransition(e.identity.projectRoot,e.identity.sessionId,e.identity.turnId);if(n)return n.receiptId;let o=`terminal:${ct(`${e.artifactHash}\0open`)}`;return t.appendTerminalTransition({...e.identity,sequence:1,toState:"open",receiptId:o,reason:"host_prompt_accepted",payload:{sourceHash:e.sourceHash},createdAt:e.createdAt}),t.appendTerminalTransition({...e.identity,sequence:2,fromState:"open",toState:"intent_bound",receiptId:`terminal:${ct(`${e.artifactHash}\0intent_bound`)}`,sourceReceiptId:o,reason:"immutable_intent_persisted",payload:{intentArtifactHash:e.artifactHash},createdAt:Math.max(e.createdAt,Date.now())}).receiptId}function Kl(t){return {...t.identity,version:t.version,supersedesHash:t.supersedesHash,rawPrompt:t.rawPrompt,normalizedPrompt:t.normalizedPrompt,command:t.command,slashArgs:t.slashArgs,activeSkill:t.activeSkill,intent:t.intent,action:t.action,entities:t.entities,targetAnchors:t.targetAnchors,policyConstraints:t.policyConstraints,classificationEvidence:t.classificationEvidence.map(e=>({...e})),sourceEventIds:t.sourceEventIds,sourceHash:t.sourceHash,artifactHash:t.artifactHash,createdAt:t.createdAt}}function ii(t){return {identity:Gl(t),version:t.version,...t.supersedesHash?{supersedesHash:t.supersedesHash}:{},rawPrompt:t.rawPrompt,normalizedPrompt:t.normalizedPrompt,...t.command?{command:t.command}:{},slashArgs:t.slashArgs,...t.activeSkill?{activeSkill:t.activeSkill}:{},intent:t.intent,action:t.action,entities:t.entities,targetAnchors:t.targetAnchors,policyConstraints:t.policyConstraints,classificationEvidence:t.classificationEvidence,sourceEventIds:t.sourceEventIds,sourceHash:t.sourceHash,artifactHash:t.artifactHash,createdAt:t.createdAt}}function Gl(t){return {projectRoot:t.projectRoot,projectId:t.projectId,hostId:t.hostId,sessionId:t.sessionId,turnId:t.turnId,requestId:t.requestId,...t.executionId?{executionId:t.executionId}:{}}}function si(t){let e=t.rawPrompt.trim().slice(0,4e3),n="identity"in t?t.identity.turnId:t.turnId;return {turnId:n,eventId:`memory-turn:${n.replace(/^turn:/u,"")}`,promptHash:createHash("sha256").update(e).digest("hex"),createdAt:t.createdAt}}function Yl(t){let e=t.match(/(?:^|[\s`'"(])((?:\.{0,2}\/)?(?:[A-Za-z0-9_@.-]+\/)+[A-Za-z0-9_@.-]+(?:\.[A-Za-z0-9]+)?)/gu)??[];return Xl(e.map(n=>n.trim().replace(/^[`'"(]+|[`'"),.;:,。;:]+$/gu,"")).filter(n=>!n.startsWith("/")||/\.[A-Za-z0-9]+$/u.test(n))).slice(0,16)}function ai(t){return t.normalize("NFKC").replace(/\s+/gu," ").trim().slice(0,4e3)}function Xl(t){return [...new Set(t.filter(Boolean))]}function Ql(t){let e=resolve(t);try{return realpathSync(e)}catch{return e}}function Zl(t){return createHash("sha256").update(yn(t)).digest("hex")}function ct(t){return createHash("sha256").update(t).digest("hex").slice(0,24)}function yn(t){if(t===null||typeof t=="string"||typeof t=="boolean")return JSON.stringify(t);if(typeof t=="number")return Number.isFinite(t)?JSON.stringify(t):"null";if(Array.isArray(t))return `[${t.map(yn).join(",")}]`;if(!t||typeof t!="object")return JSON.stringify(String(t));let e=t;return `{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${yn(e[n])}`).join(",")}}`}var fu=600*1e3,gu=2e3,hu=250,yu=2e3,vu=1e3,mi=1024*1024,_u=2*1024*1024,Iu=6e4,wu=100,ku={Agent:"get_project_context",Bash:"get_project_context",Glob:"get_project_context",Grep:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function bu(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.status=="string"?e.status:void 0;if(!(e.ok===false||e.success===false||e.isError===true||n==="failed"||n==="rejected"||n==="unavailable"||n==="warming"||!!e.error))return;let r=e.error;if(typeof r=="string"&&r.trim())return r;if(r&&typeof r=="object"){let i=r;if(typeof i.message=="string"&&i.message.trim())return i.message;if(typeof i.code=="string"&&i.code.trim())return i.code}return n?`Tool response status: ${n}`:"Tool response reported failure"}function pi(t){return /timeout|timed out|deadline|warming/i.test(t)?"timeout":/unavailable|not active|unknown tool|not found|not registered|route not found/i.test(t)?"unavailable":"failed"}function fi(t,e,n,o,r){let i=t.recordDomainActionOutcome;typeof i=="function"&&i.call(t,e,n,o,r);}function Ru(t){switch(t){case "Read":case "Glob":return "file_read";case "Write":case "Edit":case "NotebookEdit":return "file_write";case "Bash":return "bash_command";case "Agent":return "subagent";case "Skill":return "skill_invoke";default:return "tool_use"}}function In(t){return typeof t=="string"&&t.trim().length>0}function Su(t,e,n=process.env,o){if(!t.startsWith("mcp__devflow__"))return e;let r=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};if(In(r.projectRoot))return r;let i=In(n.CLAUDE_PROJECT_DIR)?n.CLAUDE_PROJECT_DIR:o;return In(i)&&(r.projectRoot=i),r}var wn=class{constructor(e,n){this.socketIdentity=null;this.pidIdentity=null;this.server=null;this.activeSessionIds=new Set;this.eventMap=[];this.idleTimer=null;this.telemetryFlushTimer=null;this.successfulTelemetryOperations=0;this.shutdownPromise=null;this.explicitMemoryGate=null;this.memoryWarmup=null;this.explicitIntentFlush=null;this.hostRuntime=null;this.memoryTurnSpoolTimer=null;this.sessionFinalizeSpoolTimer=null;this.projectRoot=e,this.socketPath=getDaemonSocketPath(e),this.pidPath=getDaemonPidPath(e),this.telemetry=new Z,this.runtimeStore=new q(this.projectRoot),this.serverManager=new $e(e),this.hookRuntime=Pr(e),this.hookHealth=new it(e),this.hookHandlers=Fr({handlers:{"pre-tool-use":o=>this.handlePreToolUse(o),"post-tool-use":o=>this.handlePostToolUse(o),"post-tool-use-failure":o=>this.handlePostToolUseFailure(o),stop:o=>this.handleStop(o),"memory-snapshot":()=>this.handleMemorySnapshot(),"session-start":o=>this.handleSessionStart(o),"session-end":o=>this.handleSessionEnd(o),"user-prompt-submit":o=>this.handleUserPromptSubmit(o),"pre-compact":o=>this.handlePreCompact(o)},failurePolicy:o=>tn(o,this.hookRuntime,this.hostRuntime??{hostId:"unresolved",capabilities:new Map,profiles:new Set(["minimal","standard","strict"])}).policy}),this.initialSessionInput=n,this.workRuntime=new nt({projectRoot:e,handlers:{...Vr(e),"memory.explicit_commit":async({item:o})=>{await this.persistMemoryTurnItem(o.payload);},"memory.turn_capture":async({item:o})=>{await this.persistMemoryTurnItem(o.payload);},"memory.explicit_enrichment":async({item:o})=>{let r=o.payload;if(typeof r?.observationId!="string"||!r.observationId)throw new x("invalid_payload","Explicit enrichment requires observationId");await(await this.getMemoryGate()).enrichExplicitMemoryObservation(r.observationId);},"session.bootstrap":async({item:o})=>{await this.bootstrapSessionWork(o.payload);},"memory.vector_backfill":async()=>{await(await this.getMemoryGate()).backfillObservationVectors({batchSize:32});},"memory.turn_distill":async({item:o})=>{await ge({projectRoot:this.projectRoot,sessionId:o.sessionId,trigger:"session_end",memory:await this.getMemoryGate()}),await this.refreshMemorySnapshot("memory_turn_distill");},"context.prefetch":async({item:o})=>{let r=o.payload;if(typeof r.prompt!="string"||typeof r.sessionId!="string"||typeof r.executionId!="string"||typeof r.profileFingerprint!="string"||typeof r.rolloutMode!="string")throw new x("invalid_payload","Context prefetch identity is incomplete");let[{createEngines:i},{projectDiagnosticCodeResult:s},{writeContextPrefetchCache:a}]=await Promise.all([import('@devflow-tools/mcp-server/composition'),import('@devflow-tools/mcp-server/retrieval'),import('@devflow-tools/context-engine')]),c=await i(this.projectRoot);try{let d=await c.context.buildTaskContext(r.prompt,{mode:"fast",sessionId:r.sessionId,executionId:r.executionId,activeSkill:r.skillName}),u=s(d,0,{projectRoot:this.projectRoot,query:r.prompt,sessionId:r.sessionId,executionId:r.executionId,requestId:`prefetch:${r.sessionId}:${r.executionId}`,turnId:`prefetch:${r.sessionId}:${r.executionId}`,host:"claude-code"});if(!a({projectRoot:this.projectRoot,query:r.prompt,sessionId:r.sessionId,executionId:r.executionId,profileFingerprint:r.profileFingerprint,rolloutMode:r.rolloutMode,retrievalVersion:r.retrievalVersion},u))throw new Error("Context prefetch envelope was not receipt-valid")}finally{for(let d of Object.values(c))try{d.close?.();}catch{}}},"verification.policy":async({item:o})=>{await oi(this.projectRoot,o);},"learning.analyze_session":async({item:o})=>{let r=o.payload;if(typeof r.projectRoot!="string"||typeof r.sessionId!="string"||typeof r.closureReceipt!="string"||typeof r.projectRevision!="string"||typeof r.createdAt!="number")throw new x("invalid_payload","Learning analysis identity is incomplete");let i=openGlobalDevFlowDatabase();try{let s=await(await this.getMemoryGate()).listLearningEvidence(r.sessionId),a=an({payload:r,evidence:s,database:i,rolloutMode:resolveCapabilityRollout(this.projectRoot).config.learningOverlays});i.insertEvent({kind:"learning_analysis",timestamp:Date.now(),success:!0,metadata:{...r,...a}});}finally{i.close();}},"session.finalize":async({item:o})=>{await this.finalizeSessionWork(o.payload,o.id);},"telemetry.reconcile":async()=>{await this.flushTelemetry();}},afterComplete:({item:o,database:r})=>{let i=o.kind==="memory.explicit_commit"||o.kind==="memory.turn_capture"?"memory":o.kind==="verification.policy"?"verification":null;i&&o.sessionId&&o.turnId&&C({projectRoot:this.projectRoot,sessionId:o.sessionId,turnId:o.turnId,kind:"durable_work.completed",payload:{workId:o.id,obligation:i},dedupeKey:`${o.id}:completed`,producer:"devflow-work-runtime"}),o.sessionId&&this.enqueueLearningAnalysisIfReady(r,o.sessionId);}});}logRuntime(e,n,o={},r){let i=r?this.runtimeStore.get(r):void 0;y({event:e==="warn"||e==="error"?"hook.runtime.degraded":"hook.runtime.completed",identity:{projectRoot:this.projectRoot,sessionId:r,executionId:i?.executionId},level:e,timestamp:Date.now(),data:{stage:n,...o}});}async start(){this.hostRuntime=await $r(this.projectRoot),mkdirSync(dirname(this.socketPath),{recursive:true,mode:448}),mkdirSync(dirname(this.pidPath),{recursive:true,mode:448}),await this.cleanStaleStartupResources(),this.server=createServer(e=>this.handleConnection(e));try{await this.listen(),this.writePidFile(),io(this.projectRoot,process.pid);}catch(e){throw await this.closeServer(),this.cleanupOwnedResources(),e}if(this.server.on("error",e=>{this.logRuntime("error","server_error",{reason:e.message});}),this.logRuntime("info","server_listening",{socketHash:createHash("sha256").update(this.socketPath).digest("hex").slice(0,16)}),await this.telemetry.flushAndAggregate(),this.telemetryFlushTimer=setInterval(()=>{this.flushTelemetry();},Iu),this.telemetryFlushTimer.unref(),prepareEmbeddingModel().then(e=>{this.logRuntime("info","embedding_ready",{source:e.source,cacheRootHash:createHash("sha256").update(e.cacheRoot).digest("hex").slice(0,16)});}).catch(e=>{this.logRuntime("warn","embedding_unavailable",{reason:e.message,fallback:"lexical_retrieval"});}),this.workRuntime.start(),this.initialSessionInput){let e=this.initialSessionInput;this.initialSessionInput=void 0,this.handleRequest({type:"session-start",input:e});}this.drainSessionStartSpool(),this.scheduleMemoryTurnSpoolDrain(0),this.scheduleSessionFinalizeSpoolDrain(0),this.resetIdleTimer();}handleConnection(e){let n="",o=false,r=false,i=0,s=Promise.resolve();e.setEncoding("utf8");let a=()=>{r||(r=true,clearTimeout(c),e.destroy());},c=setTimeout(()=>{a();},gu).unref(),d=async u=>{if(!r){r=true,clearTimeout(c);try{await this.writeFrame(e,u);}catch{}finally{e.destroy();}}};e.on("data",u=>{if(r)return;n+=u;let l=n.split(`
35
- `);if(n=l.pop()??"",Buffer.byteLength(n,"utf8")>mi){a();return}if(l.length===0)return;let m=0;for(let f of l){let p=Buffer.byteLength(f,"utf8");if(p>mi){a();return}m+=p+1;}if(i+m>_u){a();return}i+=m,s=s.then(async()=>{for(let f of l){if(r)return;if(!o){let p;try{p=JSON.parse(f);}catch{await d({error:"handshake_invalid"});return}if(p?.type!=="hello"||typeof p.rootPath!="string"){await d({error:"handshake_invalid"});return}if(p.rootPath!==this.projectRoot){await d({error:"handshake_root_mismatch",expected:this.projectRoot});return}o=true,clearTimeout(c),this.resetIdleTimer();continue}if(f.trim())try{let p=JSON.parse(f),g=await this.handleRequest(p);g!==null&&!r&&await this.writeFrame(e,g);}catch(p){r||await this.writeFrame(e,{error:p.message});}}}).catch(()=>{a();}).finally(()=>{i-=m;});}),e.on("close",()=>clearTimeout(c)),e.on("error",()=>{});}writeFrame(e,n){return new Promise((o,r)=>{if(e.destroyed||!e.writable){r(new Error("Socket is not writable"));return}let i=false,s=true,a=false,c=setTimeout(()=>{e.destroy(),u(new Error("Timed out writing daemon response"));},vu),d=()=>{clearTimeout(c),e.off("close",l),e.off("error",m),e.off("drain",f);},u=g=>{a||!g&&(!i||!s)||(a=true,d(),g?r(g):o());},l=()=>u(new Error("Socket closed during write")),m=g=>u(g),f=()=>{s=true,u();};e.once("close",l),e.once("error",m),e.write(`${JSON.stringify(n)}
31
+ `)}:a.length>0?{decision:"degrade",unresolved:a,additionalContext:"DevFlow terminal obligations remain unresolved after their one-shot correction budget."}:{decision:"allow",unresolved:[]}}finally{n.close();}}function qd(t,e){return !!t.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${e}`)}function Wd(t){if(!t)return false;let e=t.normalize("NFKC").replace(/\s+/gu," ");return /(?:未|没有|无法|失败|暂未|尚未).{0,24}(?:记住|记下|记录|保存|持久化|回执)|(?:memory|receipt).{0,24}(?:failed|missing|pending|degraded|not saved)|status=(?:pending|degraded|rejected|failed)/iu.test(e)?false:/(?:已|已经|成功).{0,20}(?:记住|记下|记录|保存|持久化)|跨会话生效|(?:memory|preference).{0,20}(?:saved|remembered|persisted)|status=(?:accepted|committed)/iu.test(e)}function Ud(t,e,n){let o=t.get(e);if(o){for(let r of o.evidenceObligations)n.upsertSessionObligation({obligationId:`evidence:${r.obligationId}`,projectRoot:o.projectRoot,sessionId:e,executionId:o.executionId,kind:"evidence_contract",state:"open",payload:{contract:r.contract,runtimeObligationId:r.obligationId},createdAt:r.promptedAt,updatedAt:o.lastActivityAt});for(let r of o.evidenceOutcomes){let i=`evidence:${r.obligationId}`,s=n.getSessionObligation(o.projectRoot,e,i);if(!s||s.state!=="open"&&!(s.state==="degraded"&&r.status==="resolved"))continue;let a=r.status==="resolved"?`evidence-receipt:${createHash("sha256").update(`${r.obligationId}\0${r.completedAt}\0${r.attempt}`).digest("hex").slice(0,24)}`:void 0;n.resolveSessionObligation({projectRoot:o.projectRoot,sessionId:e,obligationId:i,state:r.status==="resolved"?"satisfied":"degraded",receiptId:a,reason:r.reason,resolvedAt:r.completedAt});}}}var zd=[/\b(?:rm\s+-rf|sudo|chmod|chown|force\s+push|reset\s+--hard|publish|release|deploy)\b/iu,/\b(?:secret|credential|token|password|security|authentication|authorization)\b/iu,/(?:删除|强制推送|发布|部署|凭据|密钥|安全|权限)/u],Bd=[/\b(?:migration|upgrade|dependency|dependencies|generated files?|write all|rewrite)\b/iu,/(?:迁移|升级|依赖|生成文件|批量写入)/u];function rn(t){let e=`${t.instruction}
32
+ ${JSON.stringify(t.trigger)}`,n=[];zd.some(r=>r.test(e))&&n.push("high_risk_operation"),Bd.some(r=>r.test(e))&&n.push("broad_or_migrating_change"),t.kind==="correction"&&n.push("user_correction_requires_observation");let o=n.includes("high_risk_operation")?"high":n.includes("broad_or_migrating_change")||t.scope==="global"?"medium":"low";return {risk:o,manualOnly:o==="high"||n.includes("broad_or_migrating_change"),reasons:n}}var Jd=new Set(["project_convention","user_preference","decision_made","config_discovery"]);function an(t){let e=t.payload.executionId?t.database.getSkillExecution(t.payload.executionId):t.database.getLatestSkillExecutionForSession(t.payload.sessionId),n=t.database.listHostActionsForSession(t.payload.projectRoot,t.payload.sessionId,t.payload.executionId),o=n.find(u=>u.state==="verified"),r=n.find(u=>["failed","cancelled","degraded"].includes(u.state)),i=r?"negative":o?"positive":"unknown",s=new Set,a=[],c=0,d=0;for(let u of t.evidence){if(!Vd(u)){d+=1;continue}let l=Br(u),m=Kd(u,e?.skillName),f=Jr(u),p=Xd(t.payload.projectRoot,l,u.facetKey??u.semanticKey??u.id,m),g=t.database.getLearningCandidate(p),k=rn({scope:"project",kind:l,instruction:f,trigger:m});t.database.upsertLearningCandidate({id:p,projectRoot:t.payload.projectRoot,scope:"project",kind:l,trigger:m,instruction:f,confidence:Gd(u),manualOnly:k.manualOnly,risk:k.risk});g&&g.instruction!==f&&t.database.addLearningCandidateEvidence({id:Wr(p,t.payload.sessionId,u.id,"contradicting"),candidateId:p,projectRoot:t.payload.projectRoot,sessionId:t.payload.sessionId,executionId:t.payload.executionId,memoryObservationId:u.id,sourceType:"correction",polarity:"contradicting",outcome:i,evidenceHash:Ur(p,t.payload,u,"contradicting"),receipt:t.payload.closureReceipt,payload:{previousInstruction:g.instruction,replacementInstruction:f,projectRevision:t.payload.projectRevision},createdAt:u.createdAt});let R=t.database.addLearningCandidateEvidence({id:Wr(p,t.payload.sessionId,u.id,"supporting"),candidateId:p,projectRoot:t.payload.projectRoot,sessionId:t.payload.sessionId,executionId:t.payload.executionId,memoryObservationId:u.id,outcomeId:o?.id??r?.id,sourceType:Yd(u),polarity:"supporting",outcome:i,evidenceHash:Ur(p,t.payload,u,"supporting"),receipt:t.payload.closureReceipt,payload:{semanticKey:u.semanticKey,facetKey:u.facetKey,evidenceStatus:u.evidenceStatus,source:u.source,projectRevision:t.payload.projectRevision,executionStatus:e?.status,policyReasons:k.reasons},createdAt:u.createdAt});c+=1,s.add(p),t.rolloutMode!=="off"&&R.state==="candidate"&&R.supportingSessions>=3&&R.successfulOutcomes>=2&&t.database.transitionLearningCandidate(p,{target:"shadow",reason:"evidence_threshold_satisfied"}).state==="shadow"&&a.push(p);}return {considered:t.evidence.length,accepted:c,excluded:d,candidateIds:[...s],promotedToShadow:a}}function Vd(t){return !(!Jd.has(t.type)||t.source!=="explicit_intent"&&t.source!=="manual"&&t.evidenceStatus!=="verified"||!t.narrative.trim()&&!t.title.trim())}function Br(t){return t.type==="decision_made"?"workflow":t.type==="user_preference"&&(t.semanticValue.startsWith("--")||t.tools.length>0)?"tool_preference":"convention"}function Kd(t,e){return {...e?{skills:[e]}:{},...t.entities.length>0?{entities:[...new Set(t.entities)].slice(0,8)}:{},...t.files.length>0?{files:[...new Set(t.files)].slice(0,8)}:{},...t.tools.length>0?{commands:[...new Set(t.tools)].slice(0,8)}:{},semantic:{subject:t.semanticSubject,predicate:t.semanticPredicate,value:t.semanticValue,polarity:t.semanticPolarity}}}function Jr(t){return (t.narrative.trim()||t.title.trim()).replace(/\s+/gu," ").slice(0,1200)}function Gd(t){let e=t.source==="explicit_intent"?.08:0;return Math.max(0,Math.min(1,t.confidence+e))}function Yd(t){return t.semanticPolarity==="negative"?"correction":Br(t)==="tool_preference"?"tool_preference":t.source==="explicit_intent"?"memory":"convention"}function Xd(t,e,n,o){let r={...o,semantic:void 0};return `learning:${createHash("sha256").update(`${t}\0project\0${e}\0${n}\0${stableLearningJson(r)}`).digest("hex").slice(0,24)}`}function Wr(t,e,n,o){return `learning-evidence:${createHash("sha256").update(`${t}\0${e}\0${n}\0${o}`).digest("hex").slice(0,24)}`}function Ur(t,e,n,o){return createHash("sha256").update(stableLearningJson({candidateId:t,sessionId:e.sessionId,executionId:e.executionId,closureReceipt:e.closureReceipt,projectRevision:e.projectRevision,observationId:n.id,instruction:Jr(n),polarity:o})).digest("hex")}var ie=3e4,ln=1e3,pl=new Set(["git","npm","pnpm","yarn"]);function Vr(t){return {"workflow.worker_start":async({item:e})=>fl(t,e),"workflow.worker_monitor":async({item:e})=>gl(t,e),"workflow.worker_verify":async({item:e})=>hl(t,e),"workflow.worker_merge":async({item:e})=>yl(t,e),"workflow.worker_cleanup":async({item:e})=>vl(t,e)}}async function fl(t,e){await Te(t,e,async(n,o)=>{if(o.state==="running"||o.state==="starting"){cn(n,o);return}if(o.state!=="planned")return;let r=`worker-plane:${process.pid}`;n.leaseWorkflowWorker(t,o.workerId,r,ie);let i=await createManagedWorktree({projectRoot:t,runId:o.runId,stepId:o.stepId,baseRevision:o.baseRevision,registered:!0});if(i.worktreePath!==o.worktreePath||i.branch!==o.branch){n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"hold",leaseOwner:r,reason:"managed_worktree_identity_mismatch"});return}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"starting",leaseOwner:r});let s=Yr(o.workerId),a=_l(o);createWorkerArtifacts(s,a);let d=createDefaultHostAdapterRegistry().list().find(f=>f.id===o.host);if(!d)throw new x("unsupported_worker_host",`Unsupported worker host ${o.host}`);let u=se(o.handoff.actionId,"actionId"),l=n.getHostAction(t,u);if(!l)throw new x("worker_host_action_missing",`Host action ${u} was not found`);l.state==="waiting"&&n.startHostAction({actionId:u,projectRoot:t});let m=launchWorker(d,{workerId:o.workerId,runId:o.runId,stepId:o.stepId,host:o.host==="codex"?"codex":"claude-code",worktreePath:o.worktreePath,taskFile:s.taskFile,handoffFile:s.handoffFile,statusFile:s.statusFile,sessionId:o.sessionId??"worker",executionId:o.executionId??o.workerId,contextReceipt:o.contextReceipt,timeoutMs:30*6e4},s,{onHeartbeat:()=>{let f=openGlobalDevFlowDatabase();try{f.heartbeatWorkflowWorker(t,o.workerId,r,ie);}catch{}finally{f.close();}}});Il(s,{state:"running",pid:m.child.pid,owner:r,startedAt:Date.now()}),n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"running",leaseOwner:r,heartbeatAt:Date.now(),leaseExpiresAt:Date.now()+ie}),cn(n,o),m.completion.finally(()=>{let f=openGlobalDevFlowDatabase();try{cn(f,o,Date.now());}finally{f.close();}});});}async function gl(t,e){await Te(t,e,async(n,o)=>{if(o.state!=="running"&&o.state!=="starting")return;let r=Yr(o.workerId);if(existsSync(r.handoffFile)){let c=readWorkerHandoff(r.handoffFile,{workerId:o.workerId,runId:o.runId,stepId:o.stepId,contextReceipt:o.contextReceipt,worktreePath:o.worktreePath}),d=se(o.handoff.actionId,"actionId");n.reportHostAction({actionId:d,projectRoot:t,report:{workerId:o.workerId,handoff:c},evidenceHash:Qr(c)}),n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"reported",leaseOwner:o.leaseOwner,finalRevision:c.finalRevision,handoff:{...o.handoff,terminalHandoff:c}}),n.enqueueWork({idempotencyKey:`workflow-worker-verify:${o.workerId}:${c.finalRevision}`,kind:"workflow.worker_verify",projectRoot:t,payload:{workerId:o.workerId}});return}let i=wl(r),s=typeof i?.pid=="number"?i.pid:void 0;if(s&&bl(s)){let c=typeof i?.startedAt=="number"?i.startedAt:o.updatedAt;if(Date.now()-c>30*6e4){try{process.kill(s,"SIGTERM");}catch{}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_process_timeout"});let u=se(o.handoff.actionId,"actionId");n.failHostAction({actionId:u,projectRoot:t,report:{reason:"worker_process_timeout"}});return}let d=o.leaseOwner??(typeof i?.owner=="string"?i.owner:void 0);throw d?(n.heartbeatWorkflowWorker(t,o.workerId,d,ie),Xr("worker_running",ln)):new x("worker_lease_owner_missing","Worker lease owner is missing")}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_exited_without_handoff"});let a=se(o.handoff.actionId,"actionId");n.failHostAction({actionId:a,projectRoot:t,report:{reason:"worker_exited_without_handoff"}});});}async function hl(t,e){await Te(t,e,async(n,o)=>{if(o.state!=="reported")return;n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"verifying",leaseOwner:o.leaseOwner});let r=o.handoff.terminalHandoff;if(!r)throw new x("worker_handoff_missing","Persisted worker handoff is missing");let i=se(o.handoff.actionId,"actionId"),s=n.getHostAction(t,i);if(!s)throw new x("worker_host_action_missing",`Host action ${i} was not found`);let a=Gr(o),c=new GraderRegistry,d=await Kr(n,o,async()=>verifyWorkerOutput({workerId:o.workerId,projectRoot:t,worktreePath:o.worktreePath,baseRevision:o.baseRevision,parentRevision:await kl(t),contextReceipt:o.contextReceipt,allowedFiles:o.allowedFiles,handoff:r,hostAction:s,verificationCommands:a,graderIds:["receipt_validity","lifecycle_terminal_state","workflow_evidence"],graderRunner:{run:async u=>{let l=await c.run({taskId:o.stepId,taskKind:u.taskKind,projectRoot:u.projectRoot,acceptanceCriteria:[],evidence:u.evidence});return {...l,unavailableBlocking:l.unavailableRequired}}}}));if(!d.passed){n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:d.state,leaseOwner:o.leaseOwner,reason:d.reason}),d.state==="failed"&&n.failHostAction({actionId:i,projectRoot:t,outcome:"failed",report:{...s.report,verification:d},evidenceHash:d.simulationHash});return}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"merge_ready",leaseOwner:o.leaseOwner,finalRevision:d.finalRevision,handoff:{...o.handoff,terminalHandoff:r,verification:d}}),n.enqueueWork({idempotencyKey:`workflow-worker-merge:${o.workerId}:${d.finalRevision}`,kind:"workflow.worker_merge",projectRoot:t,payload:{workerId:o.workerId}});});}async function yl(t,e){await Te(t,e,async(n,o)=>{if(o.state!=="merge_ready")return;let r=o.handoff.verification;if(!r?.passed)throw new x("worker_verification_missing","Verified merge evidence is missing");let i=se(o.handoff.actionId,"actionId"),s=new SerializedWorkerMergeQueue(n,{onMerged:async({mergeCommit:c})=>{n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"merged",leaseOwner:o.leaseOwner,finalRevision:o.finalRevision,reason:`merged:${c}`});let d=n.getHostAction(t,i);n.verifyHostAction({actionId:i,projectRoot:t,report:{...d?.report??{},mergeCommit:c,verification:r},evidenceHash:Qr({mergeCommit:c,verification:r})});},scheduleCleanup:()=>{n.enqueueWork({idempotencyKey:`workflow-worker-cleanup:${o.workerId}:merged`,kind:"workflow.worker_cleanup",projectRoot:t,payload:{workerId:o.workerId}});}}),a=await Kr(n,o,()=>s.enqueueAndMerge({workerId:o.workerId,projectRoot:t,baseRevision:o.baseRevision,verification:r,message:`merge(devflow-worker): ${o.runId}/${o.stepId}`}));a.state==="conflict"&&n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"hold",leaseOwner:o.leaseOwner,reason:a.reason??"merge_conflict"});});}async function vl(t,e){await Te(t,e,async(n,o)=>{let r=e.payload,i=await cleanupManagedWorktree({repositoryRoot:t,worktreePath:o.worktreePath,branch:o.branch,registered:!0,handoffDurable:!!o.handoff.terminalHandoff||r.operatorApproved===!0});if(!i.cleaned)throw Xr(`cleanup_${i.reason??"refused"}`,3e4)});}async function Kr(t,e,n){let o=e.leaseOwner;if(!o)return n();let r=setInterval(()=>{try{t.heartbeatWorkflowWorker(e.projectRoot,e.workerId,o,ie);}catch{}},Math.floor(ie/3));r.unref();try{return await n()}finally{clearInterval(r);}}async function Te(t,e,n){let o=Rl(e.payload),r=openGlobalDevFlowDatabase();try{let i=r.getWorkflowWorker(t,o);if(!i)throw new x("worker_not_found",`Worker ${o} was not found`);await n(r,i);}finally{r.close();}}function _l(t){let e=t.handoff.task;if(!e||typeof e!="object"||Array.isArray(e))throw new x("worker_task_missing","Worker task envelope is missing");let n=Gr(t);return {workerId:t.workerId,runId:t.runId,stepId:t.stepId,projectRoot:t.projectRoot,worktreePath:t.worktreePath,baseRevision:t.baseRevision,contextReceipt:t.contextReceipt,retrievalSessionId:t.retrievalSessionId,allowedFiles:t.allowedFiles,requiredTools:[],task:e,verification:{commands:n,graders:["receipt_validity","lifecycle_terminal_state","workflow_evidence"]},constraints:{recursiveWorkers:false,maxContextCycles:3}}}function Gr(t){let e=t.handoff.verificationCommands;if(!Array.isArray(e)||e.length===0)throw new x("verification_contract_missing","Worker verification commands are missing");return e.map(n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new x("verification_contract_invalid","Worker verification command is malformed");let o=n;if(typeof o.command!="string"||!pl.has(o.command)||!Array.isArray(o.args)||o.args.some(r=>typeof r!="string"))throw new x("verification_contract_invalid","Worker verification command is not allowlisted");return {command:o.command,args:o.args}})}function Yr(t){let e=workerCoordinationRoot(t,homedir());return {root:e,taskFile:join(e,"task.json"),handoffFile:join(e,"handoff.json"),statusFile:join(e,"status.json"),stdoutFile:join(e,"stdout.log"),stderrFile:join(e,"stderr.log")}}function Il(t,e){writeJsonAtomic(t.statusFile,e);}function wl(t){try{return JSON.parse(readFileSync$1(t.statusFile,"utf8"))}catch{return null}}function cn(t,e,n=Date.now()+ln){t.enqueueWork({idempotencyKey:`workflow-worker-monitor:${e.workerId}:${Math.floor(n/ln)}`,kind:"workflow.worker_monitor",projectRoot:e.projectRoot,payload:{workerId:e.workerId},nextAttemptAt:n,maxAttempts:1e3});}async function kl(t){let{gitRevision:e}=await import('@devflow-tools/workflow-engine');return e(t,"HEAD")}function bl(t){try{return process.kill(t,0),!0}catch{return false}}function Xr(t,e){return Object.assign(new Error(t),{category:t,retryAfterMs:e,retryWithoutAttempt:true})}function Rl(t){if(!t||typeof t!="object"||typeof t.workerId!="string")throw new x("invalid_worker_payload","Worker work item requires workerId");return t.workerId}function se(t,e){if(typeof t!="string"||!t.trim())throw new x("worker_identity_missing",`Worker ${e} is missing`);return t}function Qr(t){return createHash("sha256").update(JSON.stringify(t)).digest("hex")}var El=new Set(["Write","Edit","NotebookEdit"]);function ni(t){if(!El.has(t.toolName)||Ml(t.toolResponse))return null;let e=Dl(t.projectRoot,t.toolInput);if(!e)return null;let n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let o=n.getActiveContextReceipt(t.projectRoot,t.sessionId,t.executionId),r=o?.canonicalAction?.verificationPlan??[];if(!o||r.length===0)return null;let i=[],s=[];for(let c of r){let d=Tl({projectRoot:t.projectRoot,targetFile:e,kind:c.kind,mode:c.mode==="write"?"write":"check",required:c.required===!0,contextReceipt:o.contextHash}),u=`${o.contextHash}\0${t.toolUseId??e}\0${c.kind}\0${e}`,l=`policy-verification:${createHash("sha256").update(u).digest("hex")}`,m=Date.now();if(!d){let g=`verification_unavailable:${c.kind}`;n.upsertSessionObligation({obligationId:l,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,kind:"evidence_contract",state:"degraded",payload:{subtype:"policy_verification",status:"unknown",verificationKind:c.kind,targetFile:e,contextReceipt:o.contextHash},reason:g,createdAt:m,updatedAt:m,resolvedAt:m}),s.push(c.kind),c.required===!0&&C({projectRoot:t.projectRoot,sessionId:t.sessionId,requestId:o.requestId,executionId:t.executionId,kind:"verification.failed",payload:{receiptId:l,reasonCode:g},dedupeKey:`${l}:unavailable`,producer:"devflow-verification-scheduler"});continue}let f={...d,obligationId:l,sessionId:t.sessionId,executionId:t.executionId,requestId:o.requestId};n.upsertSessionObligation({obligationId:l,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,kind:"evidence_contract",state:"open",payload:{subtype:"policy_verification",status:"scheduled",verificationKind:c.kind,command:d.display,targetFile:e,contextReceipt:o.contextHash,required:c.required===!0},createdAt:m,updatedAt:m});let p=n.enqueueWork({idempotencyKey:l,kind:"verification.policy",projectRoot:t.projectRoot,sessionId:t.sessionId,payload:f,maxAttempts:2,nextAttemptAt:m});C({projectRoot:t.projectRoot,sessionId:t.sessionId,requestId:o.requestId,executionId:t.executionId,kind:"durable_work.owned",payload:{workId:p.id,obligation:"verification"},dedupeKey:`${p.id}:owned`,producer:"devflow-verification-scheduler"}),i.push(d.display);}return [i.length>0?`DevFlow scheduled policy verification: ${i.join(" && ")}`:"",s.length>0?`Verification unavailable and recorded as unknown: ${s.join(", ")}`:""].filter(Boolean).join(`
33
+ `)||null}finally{n.close();}}async function oi(t,e){let n=Al(t,e.payload),o=await Cl(n,t),r=n.kind==="typecheck"?Fl(o.output,n.targetFile,t):[],i=ei({command:n.command,args:n.args}),s=openGlobalDevFlowDatabase();try{let a=Ll(t),c=n.kind==="typecheck"?s.getPolicyVerificationBaseline(t,n.kind,i):null,d=c&&c.sourceRevision===a?c:null,u=d?r.filter(b=>!d.diagnosticHashes.includes(b)):[],l;o.spawnError||/could not determine executable|command not found|not recognized as an internal|ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL/iu.test(o.output)?l="unavailable":o.timedOut?l="unknown":o.exitCode===0?l="passed":n.kind==="typecheck"&&!d?l="unknown":n.kind==="typecheck"&&u.length===0?l="passed":l="failed";let m=createHash("sha256").update(o.output).digest("hex"),f=`verification-receipt:${ei({obligationId:n.obligationId,commandHash:i,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:m,diagnosticHashes:r,introduced:u,status:l})}`,p={status:l,kind:n.kind,command:n.display,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:m,diagnosticHashes:r,introducedDiagnosticHashes:u,baselineAvailable:d!==null,receiptId:f},g=s.getWorkByIdempotencyKey(n.obligationId)?.id,k=s.getSessionObligation(t,n.sessionId,n.obligationId);if(k?.state==="open"&&(s.upsertSessionObligation({...k,payload:{...k.payload,status:l,outcome:p},updatedAt:Date.now()}),l!=="failed"&&s.resolveSessionObligation({projectRoot:t,sessionId:n.sessionId,obligationId:n.obligationId,state:l==="passed"?"satisfied":"degraded",receiptId:f,reason:l==="unknown"?"verification_result_unknown":l==="unavailable"?"verification_command_unavailable":void 0})),n.kind==="typecheck"&&o.exitCode===0&&s.upsertPolicyVerificationBaseline({projectRoot:t,kind:n.kind,commandHash:i,diagnosticHashes:[],sourceRevision:a,updatedAt:Date.now()}),Hl(s,n,p),C({projectRoot:t,sessionId:n.sessionId,requestId:n.requestId,executionId:n.executionId,kind:l==="passed"?"verification.succeeded":"verification.failed",payload:{receiptId:f,reasonCode:`verification_${l}`,verificationKind:n.kind},dedupeKey:f,producer:"devflow-verification-worker"}),g&&l!=="failed"&&C({projectRoot:t,sessionId:n.sessionId,requestId:n.requestId,executionId:n.executionId,kind:"durable_work.completed",payload:{workId:g,obligation:"verification"},dedupeKey:`${g}:completed`,producer:"devflow-verification-worker"}),l==="failed"){let b=new Error(`Policy verification failed: ${n.display}`);throw b.category="policy_verification_failed",b}return p}finally{s.close();}}function Tl(t){let e=Ol(t.projectRoot),n=Pl(t.projectRoot),o=e?.scripts??{},r={...e?.dependencies,...e?.devDependencies},i=null;if(t.kind==="formatter"&&(r.prettier||jl(t.projectRoot)))i=st(n,"prettier",[t.mode==="write"?"--write":"--check",t.targetFile],6e4);else if(t.kind==="typecheck"){let s=pn(o,["typecheck","type-check","check:types"]);s?i=un(n,s,12e4):r.typescript&&existsSync(join(t.projectRoot,"tsconfig.json"))&&(i=st(n,"tsc",["--noEmit","--pretty","false"],12e4));}else if(t.kind==="lint"){let s=pn(o,["lint"]);s&&(i=un(n,s,12e4));}else if(t.kind==="test"){let s=$l(t.projectRoot,t.targetFile);s&&r.vitest?i=st(n,"vitest",["run",s],12e4):s&&(r.jest||r["@jest/core"])&&(i=st(n,"jest",["--runTestsByPath",s],12e4));}else if(t.kind==="build"){let s=pn(o,["build"]);s&&(i=un(n,s,18e4));}else t.kind==="generated_files"&&(i={command:"git",args:["diff","--check","--",t.targetFile],timeoutMs:3e4});return i?{kind:t.kind,...i,display:[i.command,...i.args].map(Nl).join(" "),required:t.required,targetFile:t.targetFile,contextReceipt:t.contextReceipt}:null}function un(t,e,n){return t==="yarn"?{command:"yarn",args:["run",e],timeoutMs:n}:t==="pnpm"?{command:"pnpm",args:["run",e],timeoutMs:n}:t==="bun"?{command:"bun",args:["run",e],timeoutMs:n}:{command:"npm",args:["run",e],timeoutMs:n}}function st(t,e,n,o){return t==="pnpm"?{command:"pnpm",args:["exec",e,...n],timeoutMs:o}:t==="yarn"?{command:"yarn",args:[e,...n],timeoutMs:o}:t==="bun"?{command:"bunx",args:[e,...n],timeoutMs:o}:{command:"npx",args:["--no-install",e,...n],timeoutMs:o}}function Al(t,e){if(!e||typeof e!="object"||Array.isArray(e))throw mn();let n=e,o=new Set(["npm","npx","pnpm","yarn","bun","bunx","git"]);if(!n.command||!o.has(n.command)||!Array.isArray(n.args)||!n.args.every(r=>typeof r=="string")||!n.obligationId||!n.sessionId||!n.kind||!n.targetFile||!n.contextReceipt||!n.display||!Number.isFinite(n.timeoutMs)||!ri(t,n.targetFile))throw mn();return n}function mn(){let t=new Error("Policy verification work payload is invalid");return t.category="invalid_payload",t}function Cl(t,e){return new Promise(n=>{let o=spawn$1(t.command,t.args,{cwd:e,shell:false,stdio:["ignore","pipe","pipe"],env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),r="",i=false,s=u=>{i||(i=true,n(u));},a=u=>{r=(r+String(u)).slice(-32768);};o.stdout.on("data",a),o.stderr.on("data",a);let c=false,d=setTimeout(()=>{c=true,o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),1e3).unref();},t.timeoutMs);o.on("error",u=>{clearTimeout(d),s({exitCode:null,timedOut:false,spawnError:true,output:`${r}
34
+ ${u.message}`.slice(-32768)});}),o.on("close",u=>{clearTimeout(d),s({exitCode:u,timedOut:c,spawnError:false,output:r});});})}function Dl(t,e){let n=e.file_path??e.notebook_path;if(typeof n!="string"||!n.trim())return null;let o=isAbsolute(n)?resolve(n):resolve(t,n);return ri(t,o)?relative(t,o).split(sep).join("/"):null}function ri(t,e){let n=isAbsolute(e)?resolve(e):resolve(t,e),o=relative(resolve(t),n);return o!==""&&o!==".."&&!o.startsWith(`..${sep}`)&&!isAbsolute(o)}function Ml(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.ok===false||e.success===false||e.isError===true||!!e.error}function Ol(t){try{return JSON.parse(readFileSync$1(join(t,"package.json"),"utf8"))}catch{return null}}function Pl(t){return existsSync(join(t,"pnpm-lock.yaml"))?"pnpm":existsSync(join(t,"yarn.lock"))?"yarn":existsSync(join(t,"bun.lockb"))||existsSync(join(t,"bun.lock"))?"bun":"npm"}function jl(t){return [".prettierrc",".prettierrc.json",".prettierrc.js",".prettierrc.cjs","prettier.config.js","prettier.config.cjs"].some(e=>existsSync(join(t,e)))}function pn(t,e){return e.find(n=>typeof t[n]=="string"&&t[n].trim())??null}function $l(t,e){let n=e.replace(/\.[^.]+$/u,""),o=[".test.ts",".test.tsx",".spec.ts",".spec.tsx",".test.js",".spec.js"];for(let s of o){let a=`${n}${s}`;if(existsSync(join(t,a)))return a}let r=join(t,e.split("/").slice(0,-1).join("/")),i=e.split("/").at(-1)?.replace(/\.[^.]+$/u,"");if(!i||!existsSync(r))return null;try{return readdirSync$1(r).filter(s=>s.startsWith(`${i}.`)&&/\.(?:test|spec)\.[cm]?[jt]sx?$/u.test(s)).map(s=>relative(t,join(r,s)).split(sep).join("/"))[0]??null}catch{return null}}function Fl(t,e,n){let o=e.split(sep).join("/"),r=resolve(n,e).split(sep).join("/"),i=t.split(/\r?\n/u).map(s=>s.trim().split(sep).join("/")).filter(s=>s.includes(o)||s.includes(r)).map(s=>s.replace(/:\d+:\d+/gu,":#:#").replace(/\(\d+,\d+\)/gu,"(#,#)")).filter(s=>/\berror\s+TS\d+\b/iu.test(s));return [...new Set(i.map(s=>createHash("sha256").update(s).digest("hex")))]}function Hl(t,e,n){if(!e.executionId)return;let o=t.getSkillExecution(e.executionId);if(!o)return;let r=o.metadata&&typeof o.metadata=="object"?o.metadata:{},i=Array.isArray(r.policyVerificationOutcomes)?r.policyVerificationOutcomes:[];t.updateSkillExecution(e.executionId,{metadata:{...r,policyVerificationOutcomes:[...i,n]}});}function Ll(t){try{let e=readFileSync$1(join(t,".git","HEAD"),"utf8").trim();return e.startsWith("ref:")?readFileSync$1(join(t,".git",e.slice(5).trim()),"utf8").trim():e}catch{return}}function ei(t){return createHash("sha256").update(JSON.stringify(t)).digest("hex")}function Nl(t){return /^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)}async function ci(t){let e=Date.now(),n=Zl(t.projectRoot),o=claudeCodeRuntimeAdapter.normalizePrompt(t.hostEvent??{session_id:t.sessionId,prompt:t.prompt},{projectRoot:n}),r=semanticTextHash(ai(o.rawPrompt)),i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100});try{let s=i.getTaskIntentArtifactBySource({projectRoot:n,sessionId:t.sessionId,sourceHash:r});if(s){let k=ii(s).identity,b=i.getRuntimeActivation(k.projectRoot,k.sessionId,k.turnId,s.version);if(!b)throw new Error(`RUNTIME_ACTIVATION_MISSING:${s.artifactHash}`);return {artifact:ii(s),memoryIdentity:si(s),activation:b,reused:!0}}let a=`turn:${ct(`${t.sessionId}\0${r}`)}`,c=`request:${ct(`${n}\0${t.sessionId}\0${a}`)}`,d={projectRoot:n,projectId:`project:${stableRuntimeHash(n).slice(0,20)}`,hostId:o.hostId,sessionId:t.sessionId,executionId:t.sessionId,turnId:a,requestId:c},u=1,l=resolveRuntimeActivationSnapshot({projectRoot:n,createdAt:o.timestamp}),m=Xl(o.rawPrompt),f={identity:d,version:u,rawPrompt:o.rawPrompt,normalizedPrompt:ai(o.rawPrompt),...o.command?{command:o.command}:{},slashArgs:o.slashArgs,...o.activeSkill?{activeSkill:o.activeSkill}:{},intent:"unknown",action:"unknown",entities:[],targetAnchors:m,policyConstraints:[],classificationEvidence:[],sourceEventIds:[o.sourceEventId??`host-event:${r.slice(0,24)}`],sourceHash:r,createdAt:o.timestamp},p={...f,artifactHash:eu(f)};i.appendTaskIntentArtifact(Gl(p)),i.bindRuntimeActivation({identity:d,revision:u,snapshot:l});let g=Kl(i,p);return y({event:"host.prompt.normalized",identity:d,level:"info",timestamp:Date.now(),data:{sourceHash:r,command:p.command,activeSkill:p.activeSkill,rawPromptBytes:Buffer.byteLength(p.rawPrompt)}}),y({event:"intent.artifact.created",identity:d,level:"info",timestamp:Date.now(),data:{artifactHash:p.artifactHash,targetCount:m.length}}),y({event:"intent.artifact.persisted",identity:d,level:"info",timestamp:Date.now(),data:{artifactHash:p.artifactHash,version:p.version,sourceHash:p.sourceHash,authority:"immutable-intent",captureLatencyMs:Date.now()-e}}),y({event:"terminal.transition.persisted",identity:d,level:"info",timestamp:Date.now(),data:{state:"intent_bound",receiptId:g,sourceIntentHash:p.artifactHash}}),{artifact:p,memoryIdentity:si(p),activation:l,reused:!1}}finally{i.close();}}function Kl(t,e){let n=t.getLatestTerminalTransition(e.identity.projectRoot,e.identity.sessionId,e.identity.turnId);if(n)return n.receiptId;let o=`terminal:${ct(`${e.artifactHash}\0open`)}`;return t.appendTerminalTransition({...e.identity,sequence:1,toState:"open",receiptId:o,reason:"host_prompt_accepted",payload:{sourceHash:e.sourceHash},createdAt:e.createdAt}),t.appendTerminalTransition({...e.identity,sequence:2,fromState:"open",toState:"intent_bound",receiptId:`terminal:${ct(`${e.artifactHash}\0intent_bound`)}`,sourceReceiptId:o,reason:"immutable_intent_persisted",payload:{intentArtifactHash:e.artifactHash},createdAt:Math.max(e.createdAt,Date.now())}).receiptId}function Gl(t){return {...t.identity,version:t.version,supersedesHash:t.supersedesHash,rawPrompt:t.rawPrompt,normalizedPrompt:t.normalizedPrompt,command:t.command,slashArgs:t.slashArgs,activeSkill:t.activeSkill,intent:t.intent,action:t.action,entities:t.entities,targetAnchors:t.targetAnchors,policyConstraints:t.policyConstraints,classificationEvidence:t.classificationEvidence.map(e=>({...e})),sourceEventIds:t.sourceEventIds,sourceHash:t.sourceHash,artifactHash:t.artifactHash,createdAt:t.createdAt}}function ii(t){return {identity:Yl(t),version:t.version,...t.supersedesHash?{supersedesHash:t.supersedesHash}:{},rawPrompt:t.rawPrompt,normalizedPrompt:t.normalizedPrompt,...t.command?{command:t.command}:{},slashArgs:t.slashArgs,...t.activeSkill?{activeSkill:t.activeSkill}:{},intent:t.intent,action:t.action,entities:t.entities,targetAnchors:t.targetAnchors,policyConstraints:t.policyConstraints,classificationEvidence:t.classificationEvidence,sourceEventIds:t.sourceEventIds,sourceHash:t.sourceHash,artifactHash:t.artifactHash,createdAt:t.createdAt}}function Yl(t){return {projectRoot:t.projectRoot,projectId:t.projectId,hostId:t.hostId,sessionId:t.sessionId,turnId:t.turnId,requestId:t.requestId,...t.executionId?{executionId:t.executionId}:{}}}function si(t){let e=t.rawPrompt.trim().slice(0,4e3),n="identity"in t?t.identity.turnId:t.turnId;return {turnId:n,eventId:`memory-turn:${n.replace(/^turn:/u,"")}`,promptHash:createHash("sha256").update(e).digest("hex"),createdAt:t.createdAt}}function Xl(t){let e=t.match(/(?:^|[\s`'"(])((?:\.{0,2}\/)?(?:[A-Za-z0-9_@.-]+\/)+[A-Za-z0-9_@.-]+(?:\.[A-Za-z0-9]+)?)/gu)??[];return Ql(e.map(n=>n.trim().replace(/^[`'"(]+|[`'"),.;:,。;:]+$/gu,"")).filter(n=>!n.startsWith("/")||/\.[A-Za-z0-9]+$/u.test(n))).slice(0,16)}function ai(t){return t.normalize("NFKC").replace(/\s+/gu," ").trim().slice(0,4e3)}function Ql(t){return [...new Set(t.filter(Boolean))]}function Zl(t){let e=resolve(t);try{return realpathSync(e)}catch{return e}}function eu(t){return createHash("sha256").update(yn(t)).digest("hex")}function ct(t){return createHash("sha256").update(t).digest("hex").slice(0,24)}function yn(t){if(t===null||typeof t=="string"||typeof t=="boolean")return JSON.stringify(t);if(typeof t=="number")return Number.isFinite(t)?JSON.stringify(t):"null";if(Array.isArray(t))return `[${t.map(yn).join(",")}]`;if(!t||typeof t!="object")return JSON.stringify(String(t));let e=t;return `{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${yn(e[n])}`).join(",")}}`}var gu=600*1e3,hu=2e3,yu=250,vu=2e3,_u=1e3,mi=1024*1024,Iu=2*1024*1024,wu=6e4,ku=100,bu={Agent:"get_project_context",Bash:"get_project_context",Glob:"get_project_context",Grep:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function Ru(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.status=="string"?e.status:void 0;if(!(e.ok===false||e.success===false||e.isError===true||n==="failed"||n==="rejected"||n==="unavailable"||n==="warming"||!!e.error))return;let r=e.error;if(typeof r=="string"&&r.trim())return r;if(r&&typeof r=="object"){let i=r;if(typeof i.message=="string"&&i.message.trim())return i.message;if(typeof i.code=="string"&&i.code.trim())return i.code}return n?`Tool response status: ${n}`:"Tool response reported failure"}function pi(t){return /timeout|timed out|deadline|warming/i.test(t)?"timeout":/unavailable|not active|unknown tool|not found|not registered|route not found/i.test(t)?"unavailable":"failed"}function fi(t,e,n,o,r){let i=t.recordDomainActionOutcome;typeof i=="function"&&i.call(t,e,n,o,r);}function Su(t){switch(t){case "Read":case "Glob":return "file_read";case "Write":case "Edit":case "NotebookEdit":return "file_write";case "Bash":return "bash_command";case "Agent":return "subagent";case "Skill":return "skill_invoke";default:return "tool_use"}}function In(t){return typeof t=="string"&&t.trim().length>0}function xu(t,e,n=process.env,o){if(!t.startsWith("mcp__devflow__"))return e;let r=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};if(In(r.projectRoot))return r;let i=In(n.CLAUDE_PROJECT_DIR)?n.CLAUDE_PROJECT_DIR:o;return In(i)&&(r.projectRoot=i),r}var wn=class{constructor(e,n){this.socketIdentity=null;this.pidIdentity=null;this.server=null;this.activeSessionIds=new Set;this.eventMap=[];this.idleTimer=null;this.telemetryFlushTimer=null;this.successfulTelemetryOperations=0;this.shutdownPromise=null;this.explicitMemoryGate=null;this.memoryWarmup=null;this.explicitIntentFlush=null;this.hostRuntime=null;this.memoryTurnSpoolTimer=null;this.sessionFinalizeSpoolTimer=null;this.projectRoot=e,this.socketPath=getDaemonSocketPath(e),this.pidPath=getDaemonPidPath(e),this.telemetry=new Z,this.runtimeStore=new q(this.projectRoot),this.serverManager=new $e(e),this.hookRuntime=Pr(e),this.hookHealth=new it(e),this.hookHandlers=Fr({handlers:{"pre-tool-use":o=>this.handlePreToolUse(o),"post-tool-use":o=>this.handlePostToolUse(o),"post-tool-use-failure":o=>this.handlePostToolUseFailure(o),stop:o=>this.handleStop(o),"memory-snapshot":()=>this.handleMemorySnapshot(),"session-start":o=>this.handleSessionStart(o),"session-end":o=>this.handleSessionEnd(o),"user-prompt-submit":o=>this.handleUserPromptSubmit(o),"pre-compact":o=>this.handlePreCompact(o)},failurePolicy:o=>tn(o,this.hookRuntime,this.hostRuntime??{hostId:"unresolved",capabilities:new Map,profiles:new Set(["minimal","standard","strict"])}).policy}),this.initialSessionInput=n,this.workRuntime=new nt({projectRoot:e,handlers:{...Vr(e),"memory.explicit_commit":async({item:o})=>{await this.persistMemoryTurnItem(o.payload);},"memory.turn_capture":async({item:o})=>{await this.persistMemoryTurnItem(o.payload);},"memory.explicit_enrichment":async({item:o})=>{let r=o.payload;if(typeof r?.observationId!="string"||!r.observationId)throw new x("invalid_payload","Explicit enrichment requires observationId");await(await this.getMemoryGate()).enrichExplicitMemoryObservation(r.observationId);},"session.bootstrap":async({item:o})=>{await this.bootstrapSessionWork(o.payload);},"memory.vector_backfill":async()=>{await(await this.getMemoryGate()).backfillObservationVectors({batchSize:32});},"memory.turn_distill":async({item:o})=>{await ge({projectRoot:this.projectRoot,sessionId:o.sessionId,trigger:"session_end",memory:await this.getMemoryGate()}),await this.refreshMemorySnapshot("memory_turn_distill");},"context.prefetch":async({item:o})=>{let r=o.payload;if(typeof r.prompt!="string"||typeof r.sessionId!="string"||typeof r.executionId!="string"||typeof r.profileFingerprint!="string"||typeof r.rolloutMode!="string")throw new x("invalid_payload","Context prefetch identity is incomplete");let[{createEngines:i},{projectDiagnosticCodeResult:s},{writeContextPrefetchCache:a}]=await Promise.all([import('@devflow-tools/mcp-server/composition'),import('@devflow-tools/mcp-server/retrieval'),import('@devflow-tools/context-engine')]),c=await i(this.projectRoot);try{let d=await c.context.buildTaskContext(r.prompt,{mode:"fast",sessionId:r.sessionId,executionId:r.executionId,activeSkill:r.skillName}),u=s(d,0,{projectRoot:this.projectRoot,query:r.prompt,sessionId:r.sessionId,executionId:r.executionId,requestId:`prefetch:${r.sessionId}:${r.executionId}`,turnId:`prefetch:${r.sessionId}:${r.executionId}`,host:"claude-code"});if(!a({projectRoot:this.projectRoot,query:r.prompt,sessionId:r.sessionId,executionId:r.executionId,profileFingerprint:r.profileFingerprint,rolloutMode:r.rolloutMode,retrievalVersion:r.retrievalVersion},u))throw new Error("Context prefetch envelope was not receipt-valid")}finally{for(let d of Object.values(c))try{d.close?.();}catch{}}},"verification.policy":async({item:o})=>{await oi(this.projectRoot,o);},"learning.analyze_session":async({item:o})=>{let r=o.payload;if(typeof r.projectRoot!="string"||typeof r.sessionId!="string"||typeof r.closureReceipt!="string"||typeof r.projectRevision!="string"||typeof r.createdAt!="number")throw new x("invalid_payload","Learning analysis identity is incomplete");let i=openGlobalDevFlowDatabase();try{let s=await(await this.getMemoryGate()).listLearningEvidence(r.sessionId),a=an({payload:r,evidence:s,database:i,rolloutMode:resolveCapabilityRollout(this.projectRoot).config.learningOverlays});i.insertEvent({kind:"learning_analysis",timestamp:Date.now(),success:!0,metadata:{...r,...a}});}finally{i.close();}},"session.finalize":async({item:o})=>{await this.finalizeSessionWork(o.payload,o.id);},"telemetry.reconcile":async()=>{await this.flushTelemetry();}},afterComplete:({item:o,database:r})=>{let i=o.kind==="memory.explicit_commit"||o.kind==="memory.turn_capture"?"memory":o.kind==="verification.policy"?"verification":null;i&&o.sessionId&&o.turnId&&C({projectRoot:this.projectRoot,sessionId:o.sessionId,turnId:o.turnId,kind:"durable_work.completed",payload:{workId:o.id,obligation:i},dedupeKey:`${o.id}:completed`,producer:"devflow-work-runtime"}),o.sessionId&&this.enqueueLearningAnalysisIfReady(r,o.sessionId);}});}logRuntime(e,n,o={},r){let i=r?this.runtimeStore.get(r):void 0;y({event:e==="warn"||e==="error"?"hook.runtime.degraded":"hook.runtime.completed",identity:{projectRoot:this.projectRoot,sessionId:r,executionId:i?.executionId},level:e,timestamp:Date.now(),data:{stage:n,...o}});}async start(){this.hostRuntime=await $r(this.projectRoot),mkdirSync(dirname(this.socketPath),{recursive:true,mode:448}),mkdirSync(dirname(this.pidPath),{recursive:true,mode:448}),await this.cleanStaleStartupResources(),this.server=createServer(e=>this.handleConnection(e));try{await this.listen(),this.writePidFile(),io(this.projectRoot,process.pid);}catch(e){throw await this.closeServer(),this.cleanupOwnedResources(),e}if(this.server.on("error",e=>{this.logRuntime("error","server_error",{reason:e.message});}),this.logRuntime("info","server_listening",{socketHash:createHash("sha256").update(this.socketPath).digest("hex").slice(0,16)}),await this.telemetry.flushAndAggregate(),this.telemetryFlushTimer=setInterval(()=>{this.flushTelemetry();},wu),this.telemetryFlushTimer.unref(),prepareEmbeddingModel().then(e=>{this.logRuntime("info","embedding_ready",{source:e.source,cacheRootHash:createHash("sha256").update(e.cacheRoot).digest("hex").slice(0,16)});}).catch(e=>{this.logRuntime("warn","embedding_unavailable",{reason:e.message,fallback:"lexical_retrieval"});}),this.workRuntime.start(),this.initialSessionInput){let e=this.initialSessionInput;this.initialSessionInput=void 0,this.handleRequest({type:"session-start",input:e});}this.drainSessionStartSpool(),this.scheduleMemoryTurnSpoolDrain(0),this.scheduleSessionFinalizeSpoolDrain(0),this.resetIdleTimer();}handleConnection(e){let n="",o=false,r=false,i=0,s=Promise.resolve();e.setEncoding("utf8");let a=()=>{r||(r=true,clearTimeout(c),e.destroy());},c=setTimeout(()=>{a();},hu).unref(),d=async u=>{if(!r){r=true,clearTimeout(c);try{await this.writeFrame(e,u);}catch{}finally{e.destroy();}}};e.on("data",u=>{if(r)return;n+=u;let l=n.split(`
35
+ `);if(n=l.pop()??"",Buffer.byteLength(n,"utf8")>mi){a();return}if(l.length===0)return;let m=0;for(let f of l){let p=Buffer.byteLength(f,"utf8");if(p>mi){a();return}m+=p+1;}if(i+m>Iu){a();return}i+=m,s=s.then(async()=>{for(let f of l){if(r)return;if(!o){let p;try{p=JSON.parse(f);}catch{await d({error:"handshake_invalid"});return}if(p?.type!=="hello"||typeof p.rootPath!="string"){await d({error:"handshake_invalid"});return}if(p.rootPath!==this.projectRoot){await d({error:"handshake_root_mismatch",expected:this.projectRoot});return}o=true,clearTimeout(c),this.resetIdleTimer();continue}if(f.trim())try{let p=JSON.parse(f),g=await this.handleRequest(p);g!==null&&!r&&await this.writeFrame(e,g);}catch(p){r||await this.writeFrame(e,{error:p.message});}}}).catch(()=>{a();}).finally(()=>{i-=m;});}),e.on("close",()=>clearTimeout(c)),e.on("error",()=>{});}writeFrame(e,n){return new Promise((o,r)=>{if(e.destroyed||!e.writable){r(new Error("Socket is not writable"));return}let i=false,s=true,a=false,c=setTimeout(()=>{e.destroy(),u(new Error("Timed out writing daemon response"));},_u),d=()=>{clearTimeout(c),e.off("close",l),e.off("error",m),e.off("drain",f);},u=g=>{a||!g&&(!i||!s)||(a=true,d(),g?r(g):o());},l=()=>u(new Error("Socket closed during write")),m=g=>u(g),f=()=>{s=true,u();};e.once("close",l),e.once("error",m),e.write(`${JSON.stringify(n)}
36
36
  `,g=>{if(g){u(g);return}i=true,u();})||(s=false,e.once("drain",f));})}async cleanStaleStartupResources(){let e=this.getPathIdentity(this.socketPath);if(e){if(await this.isSocketAcceptingConnections())throw new Error(`Daemon socket already active for ${this.projectRoot}`);this.removePathIfOwned(this.socketPath,e,"stale socket");}let n=this.getPathIdentity(this.pidPath);n&&this.removePathIfOwned(this.pidPath,n,"stale PID file");}getPathIdentity(e){try{let n=lstatSync(e);return {dev:n.dev,ino:n.ino}}catch(n){if(n.code==="ENOENT")return null;throw n}}pathMatchesIdentity(e,n){if(!n)return false;try{let o=this.getPathIdentity(e);return o?.dev===n.dev&&o.ino===n.ino}catch(o){return this.logRuntime("warn","path_ownership_check",{reason:o.message}),false}}writePidFile(){let e=openSync(this.pidPath,"wx",384);try{writeFileSync(e,`${process.pid}
37
- `);let n=fstatSync(e);this.pidIdentity={dev:n.dev,ino:n.ino};}finally{closeSync(e);}}removePathIfOwned(e,n,o,r){try{return !this.pathMatchesIdentity(e,n)||r!==void 0&&readFileSync(e,"utf8")!==r||!this.pathMatchesIdentity(e,n)?!1:(unlinkSync(e),!0)}catch(i){return i.code!=="ENOENT"&&this.logRuntime("warn","owned_path_cleanup",{label:o,reason:i.message}),false}}isSocketAcceptingConnections(){return new Promise((e,n)=>{let o=createConnection(this.socketPath),r=setTimeout(()=>{o.destroy(),n(new Error(`Timed out probing daemon socket ${this.socketPath}`));},hu),i=s=>{clearTimeout(r),o.destroy(),e(s);};o.once("connect",()=>i(true)),o.once("error",s=>{let a=s.code;a==="ENOENT"||a==="ECONNREFUSED"?i(false):(clearTimeout(r),n(s));});})}listen(){return new Promise((e,n)=>{let o=this.server;if(!o){n(new Error("Daemon server is not initialized"));return}let r=s=>{o.off("listening",i),n(s);},i=()=>{o.off("error",r);try{let s=this.getPathIdentity(this.socketPath);if(!s)throw new Error(`Daemon socket missing after listen: ${this.socketPath}`);this.socketIdentity=s,e();}catch(s){n(s);}};o.once("error",r),o.once("listening",i),o.listen(this.socketPath);})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!(this.activeSessionIds.size>0)&&(this.idleTimer=setTimeout(()=>{let e=openGlobalDevFlowDatabase();try{if(e.listWorkflowWorkers(this.projectRoot,{states:["leased","starting","running","reported","verifying","merge_ready"],limit:1}).length>0){this.logRuntime("debug","idle_timeout_deferred",{reason:"active_workflow_worker"}),this.resetIdleTimer();return}}finally{e.close();}this.logRuntime("info","idle_timeout_exit"),this.shutdown();},fu).unref());}async handleRequest(e){let n=this.hostRuntime,o=xu(e.input);if(!n)return this.hookFailureResponse(e.type,{enabled:false,policy:"fail_open",reason:"host_adapter_not_ready",fallback:"host_event_continues_without_devflow_handler"});let r=tn(e.type,this.hookRuntime,n);if(!r.enabled)return this.hookFailureResponse(e.type,r);let i=Date.now();try{let s=Lr(e.type,await Hr({registry:this.hookHandlers,requestType:e.type,rawInput:e.input??"",acknowledgementBudgetMs:this.hookRuntime.acknowledgementBudgetMs,projectRoot:this.projectRoot})),a="status"in s&&s.status==="degraded";if(a){let c="reason"in s?String(s.reason):"handler_degraded";this.hookHealth.recordFailure(e.type,n.hostId,"degraded",c);}else this.hookHealth.recordSuccess(e.type,n.hostId);return Q("hook_handler_outcome",{success:!a,projectRoot:this.projectRoot,host:n.hostId,handler:e.type,degraded:a},Date.now()-i),this.logRuntime(a?"warn":"info","handler_outcome",{handler:e.type,host:n.hostId,degraded:a,durationMs:Date.now()-i,..."reason"in s&&s.reason?{reason:String(s.reason)}:{}},o),s}catch(s){let a=Nr(s);return this.hookHealth.recordFailure(e.type,n.hostId,a.category,a.reason),Q("hook_handler_outcome",{success:false,projectRoot:this.projectRoot,host:n.hostId,handler:e.type,category:a.category,reason:a.reason},Date.now()-i),this.logRuntime("error","handler_outcome",{handler:e.type,host:n.hostId,category:a.category,reason:a.reason,durationMs:Date.now()-i},o),this.hookFailureResponse(e.type,r,s)}}async drainSessionStartSpool(){for(;;){let e=kr(this.projectRoot);if(!e)return;try{let n=await this.handleRequest({type:"session-start",input:e.input});if(n&&"status"in n&&n.status==="degraded")throw new Error(`session_start_degraded:${String(n.reason??"unknown")}`);br(e),this.logRuntime("info","session_start_spool_accepted",{receiptId:e.receiptId});}catch(n){Rr(e),this.logRuntime("warn","session_start_spool_deferred",{reason:n.message,fallback:"durable_spool"});return}}}hookFailureResponse(e,n,o){let r=o instanceof Error?o.message:n.reason??"hook_handler_unavailable",i=n.fallback??(n.policy==="enqueue_and_open"?"durable_background_processing":"host_event_continues");return e==="pre-tool-use"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:n.policy==="fail_closed"?"deny":"allow",permissionDecisionReason:r,additionalContext:`DevFlow hook degraded: ${r}; fallback=${i}.`}}:e==="user-prompt-submit"?{hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",additionalContext:`DevFlow hook degraded: ${r}; fallback=${i}. Do not claim unreceipted work completed.`}}:{status:"degraded",reason:r,fallback:i}}async handlePreToolUse(e){try{if(!e||e.trim()==="")return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};let n=JSON.parse(e);n.tool_input=Su(n.tool_name,n.tool_input,process.env,this.projectRoot);let o=this.trackSession(n.session_id),r="";if(n.tool_name==="Skill"){let R=n.tool_input?.skill,I=R?Ve(R):null;I&&(r=this.startSkillExecution(o,I));}let i=this.runtimeStore.get(o);n.tool_name.startsWith("mcp__devflow__")&&(n.tool_input._devflow_session_id=o,n.tool_input._devflow_execution_id=i?.executionId??o,i?.activeTurnId&&(n.tool_input._devflow_turn_id=i.activeTurnId),i?.activeRequestId&&(n.tool_input._devflow_request_id=i.activeRequestId),i?.intentArtifactHash&&(n.tool_input._devflow_intent_artifact_hash=i.intentArtifactHash),i?.skillName&&(n.tool_input._devflow_active_skill=i.skillName),n.tool_use_id&&(n.tool_input._devflow_tool_use_id=n.tool_use_id));let s=n.tool_name.startsWith("mcp__"),a=s?n.tool_name.replace(/^mcp__[^_]+__/,""):void 0,c=new ee(this.projectRoot,o,i?.executionId),d=c.getPhase(),u=_r({toolName:n.tool_name,toolInput:n.tool_input,projectRoot:this.projectRoot}),l=u?{permissionDecision:"deny",reason:u}:c.evaluate(n.tool_name,s),m;if(l.permissionDecision==="deny"?m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:l.reason??"MCP context required"}}:l.additionalContext?m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:l.additionalContext}}:m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}},r){let R=m.hookSpecificOutput,I=typeof R.additionalContext=="string"?R.additionalContext:"";R.additionalContext=I?`${I}
38
- ${r}`:r;}n.tool_name.startsWith("mcp__devflow__")&&(m.hookSpecificOutput.updatedInput=n.tool_input);let f={...n.tool_input};delete f._devflow_session_id,delete f._devflow_execution_id,delete f._devflow_tool_use_id;let p=i?.executionId??o,k={eventId:we(o,n.tool_use_id),executionId:p,sessionId:o,projectRoot:this.projectRoot,toolUseId:n.tool_use_id,timestamp:Date.now(),toolName:n.tool_name,toolType:s?"mcp":n.tool_name==="Agent"?"subagent":"direct",isMcpTool:s,mcpToolName:a,mcpEnforced:s&&d==="context_gathering",mcpFallback:!s&&d==="context_gathering",kind:Ru(n.tool_name),input:f,duration:0,blocked:m&&m.hookSpecificOutput?.permissionDecision==="deny"},b=await this.telemetry.sendEvent({...k,blockReason:k.blocked?u?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0,error:k.blocked?u?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0});return b&&!k.blocked&&(this.eventMap.push({toolName:n.tool_name,toolUseId:n.tool_use_id,eventId:b,sessionId:o,timestamp:k.timestamp}),this.noteTelemetryOperation()),b&&k.blocked&&await this.telemetry.completeEvent({eventId:b,sessionId:o,error:u?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED",duration:Date.now()-k.timestamp,completedAt:Date.now()}),m}catch{return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}}trackSession(e){let n=e?.trim()||(this.activeSessionIds.size===1?[...this.activeSessionIds][0]:"");if(!n)throw new Error("session_id_required");return this.registerSession(n),n}registerSession(e){this.activeSessionIds.has(e)||(this.activeSessionIds.size===0&&Fe(this.projectRoot,{bypassCount:0}),this.activeSessionIds.add(e),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.serverManager.addRef(e),this.telemetry.sendSessionStart(e,this.projectRoot,Date.now()).catch(()=>{})),this.runtimeStore.registerSession(e);}startSkillExecution(e,n,o){let r=this.runtimeStore.get(e)?.executionId,i=this.runtimeStore.startExecution(e,n,Un(n));return i.executionId&&i.executionId!==r&&this.telemetry.sendExecutionStart(i.executionId,e,n,i.lastActivityAt,this.projectRoot,i.requiredMcpTools).catch(()=>{}),zn(n,this.projectRoot,o)}async handleSessionStart(e){try{let n=JSON.parse(e);if(typeof n.session_id!="string"||!n.session_id.trim())return {error:"session_id_required"};let o=n.session_id.trim();this.registerSession(o);let r=`session-start:${createHash("sha256").update(`${this.projectRoot}\0${o}`).digest("hex").slice(0,24)}`,i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50}),s="pending";try{s=i.enqueueWork({idempotencyKey:r,kind:"session.bootstrap",projectRoot:this.projectRoot,sessionId:o,payload:{sessionId:o}}).state;}finally{i.close();}return {status:s==="completed"?"completed":"accepted",receiptId:r,workState:s}}catch{return {error:"session_start_invalid"}}}popEventFromMap(e,n,o){let r=this.eventMap.filter(s=>s.toolName===e&&s.sessionId===n);if(r.length===0)return null;let i=o?r.find(s=>s.toolUseId===o):r.sort((s,a)=>s.timestamp-a.timestamp)[0];return i?(this.eventMap=this.eventMap.filter(s=>s.eventId!==i.eventId),i):null}enforcePostToolUse(e){if(!ku[e])return null;let n=Math.floor(Date.now()/1e3),o=It(this.projectRoot,s=>n-(s.lastMcpCall??0)<30?s:{...s,bypassCount:(s.bypassCount??0)+1});if(!o.applied||!o.changed)return null;let r=o.receipt.bypassCount??0;if(r===1)return null;let i;switch(e){case "Agent":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u4F7F\u7528\u4E86 Agent \u5B50\u4EE3\u7406\u6267\u884C\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Bash":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Bash \u547D\u4EE4\u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Glob":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Glob \u5339\u914D\u6587\u4EF6\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Grep":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Grep \u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "WebSearch":case "WebFetch":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86\u7F51\u7EDC\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_knowledge MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;default:i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u8BF7\u4F7F\u7528 DevFlow MCP \u5DE5\u5177\u66FF\u4EE3\u76F4\u63A5\u8C03\u7528\u3002`;}return r>=3?i=`${i} \u5DF2\u8FBE\u5230\u6700\u5927\u8FDD\u89C4\u6B21\u6570\uFF0C\u540E\u7EED\u7ED5\u8FC7\u5C06\u88AB\u786C\u963B\u6B62\u3002`:r>=2?i=`${i} \u4E0B\u6B21\u8FDD\u89C4\u5C06\u88AB\u963B\u6B62\u3002`:i=`${i} \u8BF7\u7ACB\u5373\u7EA0\u6B63\u3002`,i}async handlePostToolUse(e){if(!e)return null;let n;try{n=JSON.parse(e);}catch{return null}let o=n.tool_name||"",r=n.tool_input||{},i=n.tool_response,s=this.trackSession(n.session_id),a=this.enforcePostToolUse(o);if(a&&this.logRuntime("warn","post_tool_enforcement",{tool:o,reason:a},s),Fo({projectRoot:this.projectRoot,sessionId:s,executionId:this.runtimeStore.get(s)?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:n.tool_use_id}),o==="Skill"){let S=r?.skill,A=S?Ve(S):null;A&&(this.startSkillExecution(s,A),Fe(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0}));}if(o.startsWith("mcp__")){let S=this.runtimeStore.get(s),A=new ee(this.projectRoot,s,S?.executionId??s);A.recordMcpCall();let E=bu(i);fi(A,o.replace(/^mcp__[^_]+__/,""),E?pi(E):"succeeded",E,n.tool_use_id);}let c=this.popEventFromMap(o,s,n.tool_use_id);if(c){let S=typeof i=="string"?i:JSON.stringify(i),A=S.length>5e3?{_truncated:true,_originalSize:S.length,text:S.slice(0,5e3)}:i,E=Date.now()-c.timestamp;await this.telemetry.completeEvent({eventId:c.eventId,sessionId:s,output:A,duration:E,completedAt:Date.now()})&&this.noteTelemetryOperation();}let d=typeof i=="object"&&i!==null?i:null,u=d?.exitCode,l=d?.stderr,m=/^\s*(ls|cat|pwd|cd|echo|head|tail|wc|which|whoami|date|env|printenv|id|hostname|uname)\b/,f=r.command||"",p=JSON.stringify(i),g=Buffer.byteLength(p,"utf8"),k=this.countResults(i),b,R,I=true;if(o.startsWith("mcp__"))b="mcp_call",R={mcpTool:o.replace(/^mcp__[^_]+__/,""),query:r.query??null,resultCount:k,resultSizeBytes:g};else if(o==="Read"||o==="Write"||o==="Edit")b=o==="Read"?"file_read":"file_write",R={filePath:r.file_path??null,fileContentSize:g};else if(o==="Bash"){let S=m.test(f),A=u!==void 0&&u!==0;I=!S||A,b=A?"bash_error":"bash_command",R={command:f||o,exitCode:u??null,stderr:l??null};}else o==="Agent"?(b="subagent",R={subagentType:r.subagent_type??null,description:typeof r.description=="string"?r.description.slice(0,200):null}):o==="WebSearch"||o==="WebFetch"?(b=o==="WebSearch"?"web_search":"web_fetch",R={query:typeof r.query=="string"?r.query.slice(0,200):null}):(I=false,b="tool_use",R={});if(I){let S={id:n.tool_use_id?`memory:${we(s,n.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:s,tool:o,kind:b,payload:{...R,durationMs:0},createdAt:Date.now()};this.postMemoryEvent(S);}let F=Co({toolName:o,toolResponse:i,sessionId:s,toolUseId:n.tool_use_id,runtimeStore:this.runtimeStore}),T=this.runtimeStore.get(s),M=ni({projectRoot:this.projectRoot,sessionId:s,executionId:T?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:n.tool_use_id}),L=[F,M,a].filter(S=>!!S).join(`
37
+ `);let n=fstatSync(e);this.pidIdentity={dev:n.dev,ino:n.ino};}finally{closeSync(e);}}removePathIfOwned(e,n,o,r){try{return !this.pathMatchesIdentity(e,n)||r!==void 0&&readFileSync(e,"utf8")!==r||!this.pathMatchesIdentity(e,n)?!1:(unlinkSync(e),!0)}catch(i){return i.code!=="ENOENT"&&this.logRuntime("warn","owned_path_cleanup",{label:o,reason:i.message}),false}}isSocketAcceptingConnections(){return new Promise((e,n)=>{let o=createConnection(this.socketPath),r=setTimeout(()=>{o.destroy(),n(new Error(`Timed out probing daemon socket ${this.socketPath}`));},yu),i=s=>{clearTimeout(r),o.destroy(),e(s);};o.once("connect",()=>i(true)),o.once("error",s=>{let a=s.code;a==="ENOENT"||a==="ECONNREFUSED"?i(false):(clearTimeout(r),n(s));});})}listen(){return new Promise((e,n)=>{let o=this.server;if(!o){n(new Error("Daemon server is not initialized"));return}let r=s=>{o.off("listening",i),n(s);},i=()=>{o.off("error",r);try{let s=this.getPathIdentity(this.socketPath);if(!s)throw new Error(`Daemon socket missing after listen: ${this.socketPath}`);this.socketIdentity=s,e();}catch(s){n(s);}};o.once("error",r),o.once("listening",i),o.listen(this.socketPath);})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!(this.activeSessionIds.size>0)&&(this.idleTimer=setTimeout(()=>{let e=openGlobalDevFlowDatabase();try{if(e.listWorkflowWorkers(this.projectRoot,{states:["leased","starting","running","reported","verifying","merge_ready"],limit:1}).length>0){this.logRuntime("debug","idle_timeout_deferred",{reason:"active_workflow_worker"}),this.resetIdleTimer();return}}finally{e.close();}this.logRuntime("info","idle_timeout_exit"),this.shutdown();},gu).unref());}async handleRequest(e){let n=this.hostRuntime,o=Eu(e.input);if(!n)return this.hookFailureResponse(e.type,{enabled:false,policy:"fail_open",reason:"host_adapter_not_ready",fallback:"host_event_continues_without_devflow_handler"});let r=tn(e.type,this.hookRuntime,n);if(!r.enabled)return this.hookFailureResponse(e.type,r);let i=Date.now();try{let s=Lr(e.type,await Hr({registry:this.hookHandlers,requestType:e.type,rawInput:e.input??"",acknowledgementBudgetMs:this.hookRuntime.acknowledgementBudgetMs,projectRoot:this.projectRoot})),a="status"in s&&s.status==="degraded";if(a){let c="reason"in s?String(s.reason):"handler_degraded";this.hookHealth.recordFailure(e.type,n.hostId,"degraded",c);}else this.hookHealth.recordSuccess(e.type,n.hostId);return Q("hook_handler_outcome",{success:!a,projectRoot:this.projectRoot,host:n.hostId,handler:e.type,degraded:a},Date.now()-i),this.logRuntime(a?"warn":"info","handler_outcome",{handler:e.type,host:n.hostId,degraded:a,durationMs:Date.now()-i,..."reason"in s&&s.reason?{reason:String(s.reason)}:{}},o),s}catch(s){let a=Nr(s);return this.hookHealth.recordFailure(e.type,n.hostId,a.category,a.reason),Q("hook_handler_outcome",{success:false,projectRoot:this.projectRoot,host:n.hostId,handler:e.type,category:a.category,reason:a.reason},Date.now()-i),this.logRuntime("error","handler_outcome",{handler:e.type,host:n.hostId,category:a.category,reason:a.reason,durationMs:Date.now()-i},o),this.hookFailureResponse(e.type,r,s)}}async drainSessionStartSpool(){for(;;){let e=kr(this.projectRoot);if(!e)return;try{let n=await this.handleRequest({type:"session-start",input:e.input});if(n&&"status"in n&&n.status==="degraded")throw new Error(`session_start_degraded:${String(n.reason??"unknown")}`);br(e),this.logRuntime("info","session_start_spool_accepted",{receiptId:e.receiptId});}catch(n){Rr(e),this.logRuntime("warn","session_start_spool_deferred",{reason:n.message,fallback:"durable_spool"});return}}}hookFailureResponse(e,n,o){let r=o instanceof Error?o.message:n.reason??"hook_handler_unavailable",i=n.fallback??(n.policy==="enqueue_and_open"?"durable_background_processing":"host_event_continues");return e==="pre-tool-use"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:n.policy==="fail_closed"?"deny":"allow",permissionDecisionReason:r,additionalContext:`DevFlow hook degraded: ${r}; fallback=${i}.`}}:e==="user-prompt-submit"?{hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",additionalContext:`DevFlow hook degraded: ${r}; fallback=${i}. Do not claim unreceipted work completed.`}}:{status:"degraded",reason:r,fallback:i}}async handlePreToolUse(e){try{if(!e||e.trim()==="")return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};let n=JSON.parse(e);n.tool_input=xu(n.tool_name,n.tool_input,process.env,this.projectRoot);let o=this.trackSession(n.session_id),r="";if(n.tool_name==="Skill"){let R=n.tool_input?.skill,I=R?Ve(R):null;I&&(r=this.startSkillExecution(o,I));}let i=this.runtimeStore.get(o);n.tool_name.startsWith("mcp__devflow__")&&(n.tool_input._devflow_session_id=o,n.tool_input._devflow_execution_id=i?.executionId??o,i?.activeTurnId&&(n.tool_input._devflow_turn_id=i.activeTurnId),i?.activeRequestId&&(n.tool_input._devflow_request_id=i.activeRequestId),i?.intentArtifactHash&&(n.tool_input._devflow_intent_artifact_hash=i.intentArtifactHash),i?.skillName&&(n.tool_input._devflow_active_skill=i.skillName),n.tool_use_id&&(n.tool_input._devflow_tool_use_id=n.tool_use_id));let s=n.tool_name.startsWith("mcp__"),a=s?n.tool_name.replace(/^mcp__[^_]+__/,""):void 0,c=new ee(this.projectRoot,o,i?.executionId),d=c.getPhase(),u=_r({toolName:n.tool_name,toolInput:n.tool_input,projectRoot:this.projectRoot}),l=u?{permissionDecision:"deny",reason:u}:c.evaluate(n.tool_name,s),m;if(l.permissionDecision==="deny"?m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:l.reason??"MCP context required"}}:l.additionalContext?m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:l.additionalContext}}:m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}},r){let R=m.hookSpecificOutput,I=typeof R.additionalContext=="string"?R.additionalContext:"";R.additionalContext=I?`${I}
38
+ ${r}`:r;}n.tool_name.startsWith("mcp__devflow__")&&(m.hookSpecificOutput.updatedInput=n.tool_input);let f={...n.tool_input};delete f._devflow_session_id,delete f._devflow_execution_id,delete f._devflow_tool_use_id;let p=i?.executionId??o,k={eventId:we(o,n.tool_use_id),executionId:p,sessionId:o,projectRoot:this.projectRoot,toolUseId:n.tool_use_id,timestamp:Date.now(),toolName:n.tool_name,toolType:s?"mcp":n.tool_name==="Agent"?"subagent":"direct",isMcpTool:s,mcpToolName:a,mcpEnforced:s&&d==="context_gathering",mcpFallback:!s&&d==="context_gathering",kind:Su(n.tool_name),input:f,duration:0,blocked:m&&m.hookSpecificOutput?.permissionDecision==="deny"},b=await this.telemetry.sendEvent({...k,blockReason:k.blocked?u?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0,error:k.blocked?u?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0});return b&&!k.blocked&&(this.eventMap.push({toolName:n.tool_name,toolUseId:n.tool_use_id,eventId:b,sessionId:o,timestamp:k.timestamp}),this.noteTelemetryOperation()),b&&k.blocked&&await this.telemetry.completeEvent({eventId:b,sessionId:o,error:u?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED",duration:Date.now()-k.timestamp,completedAt:Date.now()}),m}catch{return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}}trackSession(e){let n=e?.trim()||(this.activeSessionIds.size===1?[...this.activeSessionIds][0]:"");if(!n)throw new Error("session_id_required");return this.registerSession(n),n}registerSession(e){this.activeSessionIds.has(e)||(this.activeSessionIds.size===0&&Fe(this.projectRoot,{bypassCount:0}),this.activeSessionIds.add(e),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.serverManager.addRef(e),this.telemetry.sendSessionStart(e,this.projectRoot,Date.now()).catch(()=>{})),this.runtimeStore.registerSession(e);}startSkillExecution(e,n,o){let r=this.runtimeStore.get(e)?.executionId,i=this.runtimeStore.startExecution(e,n,Un(n));return i.executionId&&i.executionId!==r&&this.telemetry.sendExecutionStart(i.executionId,e,n,i.lastActivityAt,this.projectRoot,i.requiredMcpTools).catch(()=>{}),zn(n,this.projectRoot,o)}async handleSessionStart(e){try{let n=JSON.parse(e);if(typeof n.session_id!="string"||!n.session_id.trim())return {error:"session_id_required"};let o=n.session_id.trim();this.registerSession(o);let r=`session-start:${createHash("sha256").update(`${this.projectRoot}\0${o}`).digest("hex").slice(0,24)}`,i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50}),s="pending";try{s=i.enqueueWork({idempotencyKey:r,kind:"session.bootstrap",projectRoot:this.projectRoot,sessionId:o,payload:{sessionId:o}}).state;}finally{i.close();}return {status:s==="completed"?"completed":"accepted",receiptId:r,workState:s}}catch{return {error:"session_start_invalid"}}}popEventFromMap(e,n,o){let r=this.eventMap.filter(s=>s.toolName===e&&s.sessionId===n);if(r.length===0)return null;let i=o?r.find(s=>s.toolUseId===o):r.sort((s,a)=>s.timestamp-a.timestamp)[0];return i?(this.eventMap=this.eventMap.filter(s=>s.eventId!==i.eventId),i):null}enforcePostToolUse(e){if(!bu[e])return null;let n=Math.floor(Date.now()/1e3),o=It(this.projectRoot,s=>n-(s.lastMcpCall??0)<30?s:{...s,bypassCount:(s.bypassCount??0)+1});if(!o.applied||!o.changed)return null;let r=o.receipt.bypassCount??0;if(r===1)return null;let i;switch(e){case "Agent":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u4F7F\u7528\u4E86 Agent \u5B50\u4EE3\u7406\u6267\u884C\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Bash":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Bash \u547D\u4EE4\u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Glob":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Glob \u5339\u914D\u6587\u4EF6\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Grep":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Grep \u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "WebSearch":case "WebFetch":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86\u7F51\u7EDC\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_knowledge MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;default:i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u8BF7\u4F7F\u7528 DevFlow MCP \u5DE5\u5177\u66FF\u4EE3\u76F4\u63A5\u8C03\u7528\u3002`;}return r>=3?i=`${i} \u5DF2\u8FBE\u5230\u6700\u5927\u8FDD\u89C4\u6B21\u6570\uFF0C\u540E\u7EED\u7ED5\u8FC7\u5C06\u88AB\u786C\u963B\u6B62\u3002`:r>=2?i=`${i} \u4E0B\u6B21\u8FDD\u89C4\u5C06\u88AB\u963B\u6B62\u3002`:i=`${i} \u8BF7\u7ACB\u5373\u7EA0\u6B63\u3002`,i}async handlePostToolUse(e){if(!e)return null;let n;try{n=JSON.parse(e);}catch{return null}let o=n.tool_name||"",r=n.tool_input||{},i=n.tool_response,s=this.trackSession(n.session_id),a=this.enforcePostToolUse(o);if(a&&this.logRuntime("warn","post_tool_enforcement",{tool:o,reason:a},s),Fo({projectRoot:this.projectRoot,sessionId:s,executionId:this.runtimeStore.get(s)?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:n.tool_use_id}),o==="Skill"){let S=r?.skill,A=S?Ve(S):null;A&&(this.startSkillExecution(s,A),Fe(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0}));}if(o.startsWith("mcp__")){let S=this.runtimeStore.get(s),A=new ee(this.projectRoot,s,S?.executionId??s);A.recordMcpCall();let E=Ru(i);fi(A,o.replace(/^mcp__[^_]+__/,""),E?pi(E):"succeeded",E,n.tool_use_id);}let c=this.popEventFromMap(o,s,n.tool_use_id);if(c){let S=typeof i=="string"?i:JSON.stringify(i),A=S.length>5e3?{_truncated:true,_originalSize:S.length,text:S.slice(0,5e3)}:i,E=Date.now()-c.timestamp;await this.telemetry.completeEvent({eventId:c.eventId,sessionId:s,output:A,duration:E,completedAt:Date.now()})&&this.noteTelemetryOperation();}let d=typeof i=="object"&&i!==null?i:null,u=d?.exitCode,l=d?.stderr,m=/^\s*(ls|cat|pwd|cd|echo|head|tail|wc|which|whoami|date|env|printenv|id|hostname|uname)\b/,f=r.command||"",p=JSON.stringify(i),g=Buffer.byteLength(p,"utf8"),k=this.countResults(i),b,R,I=true;if(o.startsWith("mcp__"))b="mcp_call",R={mcpTool:o.replace(/^mcp__[^_]+__/,""),query:r.query??null,resultCount:k,resultSizeBytes:g};else if(o==="Read"||o==="Write"||o==="Edit")b=o==="Read"?"file_read":"file_write",R={filePath:r.file_path??null,fileContentSize:g};else if(o==="Bash"){let S=m.test(f),A=u!==void 0&&u!==0;I=!S||A,b=A?"bash_error":"bash_command",R={command:f||o,exitCode:u??null,stderr:l??null};}else o==="Agent"?(b="subagent",R={subagentType:r.subagent_type??null,description:typeof r.description=="string"?r.description.slice(0,200):null}):o==="WebSearch"||o==="WebFetch"?(b=o==="WebSearch"?"web_search":"web_fetch",R={query:typeof r.query=="string"?r.query.slice(0,200):null}):(I=false,b="tool_use",R={});if(I){let S={id:n.tool_use_id?`memory:${we(s,n.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:s,tool:o,kind:b,payload:{...R,durationMs:0},createdAt:Date.now()};this.postMemoryEvent(S);}let F=Co({toolName:o,toolResponse:i,sessionId:s,toolUseId:n.tool_use_id,runtimeStore:this.runtimeStore}),T=this.runtimeStore.get(s),M=ni({projectRoot:this.projectRoot,sessionId:s,executionId:T?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:n.tool_use_id}),L=[F,M,a].filter(S=>!!S).join(`
39
39
 
40
40
  `);return L?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:L}}:null}async handlePostToolUseFailure(e){let n;try{n=JSON.parse(e);}catch{return null}let o=this.trackSession(n.session_id),r=n.tool_name??"unknown",i=n.error??`${r} failed`;if(r.startsWith("mcp__devflow__")){let a=this.runtimeStore.get(o),c=new ee(this.projectRoot,o,a?.executionId??o);fi(c,r.replace(/^mcp__[^_]+__/,""),pi(i),i,n.tool_use_id);}let s=this.popEventFromMap(r,o,n.tool_use_id);if(s)await this.telemetry.completeEvent({eventId:s.eventId,sessionId:o,error:i,duration:Date.now()-s.timestamp,completedAt:Date.now()})&&this.noteTelemetryOperation();else {let a=we(o,n.tool_use_id);await this.telemetry.sendEvent({eventId:a,executionId:this.runtimeStore.get(o)?.executionId??o,sessionId:o,projectRoot:this.projectRoot,toolUseId:n.tool_use_id,timestamp:Date.now(),toolName:r,toolType:r.startsWith("mcp__")?"mcp":"direct",isMcpTool:r.startsWith("mcp__"),mcpToolName:r.startsWith("mcp__")?r.replace(/^mcp__[^_]+__/,""):void 0,mcpEnforced:false,mcpFallback:false,kind:"error",input:n.tool_input??{},duration:0,error:i,blocked:false});}return this.postMemoryEvent({id:n.tool_use_id?`memory:${we(o,n.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:o,tool:r,command:typeof n.tool_input?.command=="string"?n.tool_input.command:r,exitCode:-1,stderr:i,durationMs:s?Date.now()-s.timestamp:0,createdAt:Date.now(),kind:r==="Bash"?"bash_error":"tool_use",payload:{command:n.tool_input?.command??r,exitCode:-1,stderr:i}}),null}countResults(e){if(!e)return 0;let n=e;if(typeof e=="string")try{n=JSON.parse(e);}catch{return 1}let o=n,r=["files","results","data","result","memories","nodes","chunks","findings","symbols"],i=Array.isArray(o.data)?o.data:o.structuredContent??o;if(Array.isArray(i))return i.length;if(typeof i=="object"&&i!==null){let s=i,a=0,c=false;for(let d of r)Array.isArray(s[d])&&(c=true,a+=s[d].length);for(let[,d]of Object.entries(s))d&&typeof d=="object"&&!Array.isArray(d)&&(a+=this.countResults(d));return a>0?a:c?0:Object.keys(s).length>0?1:0}return 0}async postMemoryEvent(e){await new Promise(n=>setImmediate(n)),J(`/api/memory/session-events?rootPath=${encodeURIComponent(this.projectRoot)}`,e);try{await(await this.getMemoryGate()).recordEvent(e);}catch(n){this.logRuntime("warn","memory_event_write",{reason:n.message,fallback:"http_mirror"},e.sessionId);}}async getMemoryGate(){let e=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return this.memoryWarmup??=e.forceWarmUp().catch(n=>{throw this.memoryWarmup=null,n}),await this.memoryWarmup,e}async handleUserPromptSubmit(e){let n=[];try{let o=JSON.parse(e),r=typeof o.prompt=="string"?o.prompt:"",i=typeof o.session_id=="string"&&o.session_id.trim()?this.trackSession(o.session_id):null,s=Yo(r),a=!1,c;if(r.trim()&&i){try{c=await ci({projectRoot:this.projectRoot,sessionId:i,prompt:r,hostEvent:o}),this.runtimeStore.bindTaskIdentity(i,{turnId:c.artifact.identity.turnId,requestId:c.artifact.identity.requestId,intentArtifactHash:c.artifact.artifactHash}),n.push(`DevFlow immutable task identity: turnId=${c.artifact.identity.turnId}; requestId=${c.artifact.identity.requestId}; intentArtifactHash=${c.artifact.artifactHash}. Retrieval query expansion must not replace this original intent.`);}catch(d){n.push("DevFlow task intent persistence degraded; preserve the original user command and do not claim canonical context binding."),y({event:"intent.artifact.failed",identity:{projectRoot:this.projectRoot,sessionId:i},level:"error",timestamp:Date.now(),data:{stage:"daemon_user_prompt_submit",category:"intent_persistence_unavailable",error:d instanceof Error?d.message:String(d)}});}try{let d=Jt({projectRoot:this.projectRoot,sessionId:i,prompt:r,...c?{identity:c.memoryIdentity}:{},...c?{activation:c.activation}:{}});if(d){let u=d;if(d.explicitContent&&d.turn.status==="pending")try{u=await Vt({projectRoot:this.projectRoot,payload:{operation:"commit_explicit",turnId:d.turn.turnId,eventId:d.turn.eventId,sessionId:i,prompt:r.trim().slice(0,4e3),explicitContent:d.explicitContent,createdAt:d.turn.createdAt},memory:await this.getMemoryGate()});}catch(l){this.logRuntime("warn","explicit_memory_commit",{reason:l.message,fallback:"durable_work_queue",turnId:d.turn.turnId},i);}n.push(u.additionalContext),a=u.skipSkillRouting;}}catch(d){a=!!Ie(r);try{let l=xr(this.projectRoot,{sessionId:i,prompt:r,createdAt:Date.now()});n.push(`DevFlow memory turn status=accepted; durable=true; receiptId=${l}; canonicalMemory=false; SQLite queue replay pending. Do not claim memory success without a canonical receipt.`),this.scheduleMemoryTurnSpoolDrain(250),this.logRuntime("warn","memory_turn_capture",{reason:d.message,fallback:"durable_spool",receiptId:l},i);}catch(l){n.push("DevFlow memory turn status=degraded; durable=false; no canonical receipt exists. Do not claim memory success."),this.logRuntime("error","memory_turn_capture",{reason:l.message,fallback:"none"},i);}}}if(i&&s&&!a){let d=this.startSkillExecution(i,s.skillName,r);d&&n.push(d);}}catch{}return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...n.length?{additionalContext:n.join(`
41
- `)}:{}}}}async handlePreCompact(e){let n;try{let s=JSON.parse(e);typeof s.session_id=="string"&&s.session_id.trim()&&(n=s.session_id.trim());}catch{}await this.flushTelemetry(),this.startExplicitIntentFlush(),await this.explicitIntentFlush;let o=await this.getMemoryGate(),r=await ge({projectRoot:this.projectRoot,sessionId:n,trigger:"pre_compact",memory:o}),i=ao(r);return {hookSpecificOutput:{hookEventName:"PreCompact",...i?{additionalContext:i}:{}}}}async persistMemoryTurnItem(e){if(!e||typeof e!="object")throw new Error("memory_turn_payload_invalid");let n=e;if(n.operation!=="capture_prompt"&&n.operation!=="commit_explicit"||typeof n.turnId!="string"||typeof n.eventId!="string"||typeof n.sessionId!="string"||typeof n.prompt!="string"||typeof n.createdAt!="number")throw new Error("memory_turn_payload_invalid");await Vt({projectRoot:this.projectRoot,payload:n,memory:await this.getMemoryGate()});}scheduleMemoryTurnSpoolDrain(e){this.memoryTurnSpoolTimer||(this.memoryTurnSpoolTimer=setTimeout(()=>{this.memoryTurnSpoolTimer=null,this.drainMemoryTurnSpool();},e),this.memoryTurnSpoolTimer.unref());}async drainMemoryTurnSpool(){for(;;){let e=Er(this.projectRoot);if(!e)return;try{Jt({projectRoot:this.projectRoot,sessionId:e.payload.sessionId,prompt:e.payload.prompt}),Tr(e),this.workRuntime.drainOnce();}catch(n){Ar(e),this.logRuntime("warn","memory_turn_spool_replay",{reason:n.message,fallback:"bounded_retry"},e.payload.sessionId),this.scheduleMemoryTurnSpoolDrain(1e3);return}}}async bootstrapSessionWork(e){if(!e||typeof e!="object"||typeof e.sessionId!="string")throw new Error("session_bootstrap_payload_invalid");let n=e.sessionId,o=await this.getMemoryGate();await o.ensureSession(n,this.projectRoot,"Host session"),await o.releasePendingDistillLeases(n),await this.refreshMemorySnapshot("session_bootstrap");}noteTelemetryOperation(){this.successfulTelemetryOperations++,this.successfulTelemetryOperations>=wu&&this.flushTelemetry();}async flushTelemetry(){this.successfulTelemetryOperations=0,await this.telemetry.flushAndAggregate();}startExplicitIntentFlush(){this.explicitIntentFlush||(this.explicitIntentFlush=this.flushExplicitMemoryIntents().finally(()=>{this.explicitIntentFlush=null;}));}async handleStop(e){let n=null,o=false,r;try{let i=JSON.parse(e);typeof i.session_id=="string"&&i.session_id.trim()&&(n=i.session_id.trim()),o=i.stop_hook_active===!0,typeof i.transcript_path=="string"&&i.transcript_path.trim()&&(r=i.transcript_path.trim());}catch{}if(n??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null,this.startExplicitIntentFlush(),n){let i=qr({projectRoot:this.projectRoot,sessionId:n,transcriptPath:r,stopHookActive:o,runtimeStore:this.runtimeStore});if(i.decision==="block_once")return y({event:"hook.stop.degraded",identity:{projectRoot:this.projectRoot,sessionId:n},level:"warn",timestamp:Date.now(),data:{decision:"block_once",unresolved:i.unresolved.map(a=>a.obligationId)}}),{decision:"block",reason:i.additionalContext};let s=this.runtimeStore.completeExecution(n);if(s?.executionId){let a=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50}),c={};try{let d=a.listSessionMemoryTurnsForReconciliation(this.projectRoot,n);c={...Mt(d),evidenceDegradations:s.evidenceDegradations,evidenceContractOutcomes:s.evidenceOutcomes,unresolvedObligations:i.unresolved,terminalState:i.decision};}finally{a.close();}await this.telemetry.sendExecutionComplete(s.executionId,"completed",Date.now(),c),this.deleteContextReceipt(n,s.executionId);}y({event:"hook.stop.completed",identity:{projectRoot:this.projectRoot,sessionId:n,executionId:s?.executionId},level:"info",timestamp:Date.now(),data:{decision:i.decision,unresolvedCount:i.unresolved.length}});}return null}async flushExplicitMemoryIntents(){this.flushTelemetry();let e=Go(this.projectRoot);if(e)try{let n=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);await n.forceWarmUp();let o=!1;for(;e.intents.length>0;){let r=e.intents[0];if(r.turnId){let s=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let a=s.getMemoryTurn(r.turnId);if(!a||a.status!=="pending"){this.logRuntime("warn","legacy_memory_intent_drop",{turnId:r.turnId,status:a?.status??"missing"},r.sessionId),Ot(e);continue}}finally{s.close();}}let i=await n.saveExplicitMemoryIntent(r.content,{actorId:"actor:claude-code",sessionId:r.sessionId},r.eventId);if(o=!0,r.turnId){let s=openGlobalDevFlowDatabase();try{let a=s.commitMemoryTurn({turnId:r.turnId,receiptId:xe(r.turnId,"committed",[i.id]),memoryIds:[i.id],source:"explicit_intent",reason:"explicit_user_request_retry"});if(a.receiptId)try{await n.finalizeTurnDecision({turnEventId:a.eventId,sessionId:a.sessionId,turnId:a.turnId,receiptId:a.receiptId,status:"committed",memoryIds:[i.id],reason:"explicit_user_request_retry"});}catch(c){this.logRuntime("warn","memory_lineage_finalize",{reason:c.message,fallback:"session_end_reconciliation",turnId:r.turnId},r.sessionId);}try{await n.enrichExplicitMemoryObservation(i.id);}catch(c){s.enqueueWork({idempotencyKey:`explicit-enrichment:${this.projectRoot}:${i.id}`,kind:"memory.explicit_enrichment",projectRoot:this.projectRoot,sessionId:r.sessionId,turnId:r.turnId,payload:{observationId:i.id},maxAttempts:20}),this.logRuntime("warn","explicit_memory_enrichment",{reason:c.message,fallback:"durable_work_queue",memoryId:i.id,turnId:r.turnId},r.sessionId);}}finally{s.close();}}Ot(e);}o&&await this.refreshMemorySnapshot("legacy_explicit_memory_commit");}catch(n){this.logRuntime("error","legacy_memory_intent_flush",{reason:n.message,fallback:"claim_remains_retryable"});}}deleteContextReceipt(e,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),o.deleteContextReceipt(this.projectRoot,e,n);}catch{}finally{o?.close();}}async refreshMemorySnapshot(e){try{let n=loadConfig(this.projectRoot).sessionStart?.injectMemories??!0,o=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return await Ze({projectRoot:this.projectRoot,memory:o,injectConfig:n,reason:e})}catch(n){return this.logRuntime("warn","memory_snapshot_refresh",{reason:n.message,fallback:"cached_snapshot",trigger:e}),Bt({projectRoot:this.projectRoot,reason:e,load:async()=>{throw n}})}}async handleMemorySnapshot(){let e=await this.refreshMemorySnapshot("memory_snapshot_request"),{snapshot:n}=e;return {status:n.status==="ready"||n.status==="disabled"?"ok":n.status,enabled:n.status!=="disabled",markdown:n.markdown,memoryIds:n.memoryIds,memoryCount:n.memoryIds.length,conflicts:n.conflicts,snapshot:n,persisted:e.persisted}}async handleSessionEnd(e){let n=null;try{let s=JSON.parse(e);typeof s.session_id=="string"&&s.session_id.trim()&&(n=s.session_id.trim());}catch{}n??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null;let o=n===null?this.activeSessionIds.size<=1:this.activeSessionIds.size<=1&&this.activeSessionIds.has(n),r=n?this.runtimeStore.get(n)?.executionId:void 0,i=Je(e,this.projectRoot,o,r);return i?.workState==="spooled"&&this.scheduleSessionFinalizeSpoolDrain(250),n&&(this.serverManager.removeRef(n),this.activeSessionIds.delete(n),this.eventMap=this.eventMap.filter(s=>s.sessionId!==n)),this.activeSessionIds.size===0&&i?.workState!=="spooled"&&i?.workItemId?setImmediate(()=>{this.workRuntime.drainWorkItemOnce(i.workItemId).finally(()=>{this.shutdown();});}):this.resetIdleTimer(),i??{status:"ok"}}async finalizeSessionWork(e,n){if(!e||typeof e!="object")throw new Error("session_finalize_payload_invalid");let o=e;if(typeof o.inputJson!="string"||typeof o.sessionId!="string")throw new Error("session_finalize_payload_invalid");let r=await this.getMemoryGate();await zo(o.inputJson,this.projectRoot,o.cleanupSharedState!==false,{telemetry:this.telemetry,memory:r,executionId:o.executionId});try{await this.refreshMemorySnapshot("session_finalization");}catch(s){this.logRuntime("warn","session_finalize_snapshot",{reason:s.message,fallback:"durable_memory_authoritative"},o.sessionId);}let i=openGlobalDevFlowDatabase();try{i.completeSessionClosure(this.projectRoot,o.sessionId,n);}finally{i.close();}}enqueueLearningAnalysisIfReady(e,n){if(resolveCapabilityRollout(this.projectRoot).config.learningOverlays==="off")return;let r=e.getSessionClosure(this.projectRoot,n);if(!r||r.state!=="closed"||r.pendingWorkCount!==0||e.listSessionObligations(this.projectRoot,n).some(c=>c.state==="open"||c.state==="degraded"))return;let s=e.getLatestSkillExecutionForSession(n);if(s&&s.status==="running")return;let a=Eu(this.projectRoot);e.enqueueWork({idempotencyKey:`learning-analysis:${r.receiptId}:${a}`,kind:"learning.analyze_session",projectRoot:this.projectRoot,sessionId:n,payload:{projectRoot:this.projectRoot,sessionId:n,executionId:s?.executionId,closureReceipt:r.receiptId,projectRevision:a,createdAt:Date.now()},maxAttempts:5});}scheduleSessionFinalizeSpoolDrain(e){this.sessionFinalizeSpoolTimer||(this.sessionFinalizeSpoolTimer=setTimeout(()=>{this.sessionFinalizeSpoolTimer=null,this.drainSessionFinalizeSpool();},e),this.sessionFinalizeSpoolTimer.unref());}async drainSessionFinalizeSpool(){for(;;){let e=bo(this.projectRoot);if(!e)return;try{if(!Je(e.payload.inputJson,this.projectRoot,e.payload.cleanupSharedState,e.payload.executionId,!1))throw new Error("session_finalize_spool_rejected");Ro(e),this.workRuntime.drainOnce();}catch(n){So(e),this.logRuntime("warn","session_finalize_spool_replay",{reason:n.message,fallback:"bounded_retry"},e.payload.sessionId),this.scheduleSessionFinalizeSpoolDrain(1e3);return}}}shutdown(){return this.shutdownPromise?this.shutdownPromise:(this.shutdownPromise=this.performShutdown(),this.shutdownPromise)}async performShutdown(){this.workRuntime.stop(),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.telemetryFlushTimer&&(clearInterval(this.telemetryFlushTimer),this.telemetryFlushTimer=null),this.memoryTurnSpoolTimer&&(clearTimeout(this.memoryTurnSpoolTimer),this.memoryTurnSpoolTimer=null),this.sessionFinalizeSpoolTimer&&(clearTimeout(this.sessionFinalizeSpoolTimer),this.sessionFinalizeSpoolTimer=null),await this.flushTelemetry(),await this.closeServer(),this.cleanupOwnedResources(),await this.serverManager.stop(),await this.explicitIntentFlush,this.explicitMemoryGate?.close(),this.explicitMemoryGate=null,this.telemetry.close(),process.exit(0);}closeServer(){let e=this.server;return !e||!e.listening||!this.pathMatchesIdentity(this.socketPath,this.socketIdentity)?Promise.resolve():(this.server=null,new Promise(n=>{let o=false,r=()=>{o||(o=true,clearTimeout(i),n());},i=setTimeout(r,yu);e.close(r);}))}cleanupOwnedResources(){try{so(this.projectRoot,process.pid);}catch(e){this.logRuntime("warn","daemon_unregister",{reason:e.message});}this.removePathIfOwned(this.socketPath,this.socketIdentity,"socket"),this.removePathIfOwned(this.pidPath,this.pidIdentity,"PID file",`${process.pid}
42
- `);}};function xu(t){if(t)try{let e=JSON.parse(t);return typeof e.session_id=="string"&&e.session_id.trim()?e.session_id.trim():void 0}catch{return}}function Eu(t){try{return execFileSync("git",["rev-parse","HEAD"],{cwd:t,encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return `unversioned:${createHash("sha256").update(t).digest("hex").slice(0,16)}`}}if(process.env.DEVFLOW_HOOK_DAEMON_DISABLE_AUTOSTART!=="1"){let t=process.argv[2]||process.env.CLAUDE_PROJECT_DIR||process.cwd(),e=new wn(t,process.argv[3]);process.once("SIGTERM",()=>{e.shutdown();}),process.once("SIGINT",()=>{e.shutdown();}),e.start().catch(n=>{console.error("[devflow-daemon] Failed to start:",n),process.exit(1);});}export{wn as HookDaemon,Su as injectProjectRootIfMissing};
41
+ `)}:{}}}}async handlePreCompact(e){let n;try{let s=JSON.parse(e);typeof s.session_id=="string"&&s.session_id.trim()&&(n=s.session_id.trim());}catch{}await this.flushTelemetry(),this.startExplicitIntentFlush(),await this.explicitIntentFlush;let o=await this.getMemoryGate(),r=await ge({projectRoot:this.projectRoot,sessionId:n,trigger:"pre_compact",memory:o}),i=ao(r);return {hookSpecificOutput:{hookEventName:"PreCompact",...i?{additionalContext:i}:{}}}}async persistMemoryTurnItem(e){if(!e||typeof e!="object")throw new Error("memory_turn_payload_invalid");let n=e;if(n.operation!=="capture_prompt"&&n.operation!=="commit_explicit"||typeof n.turnId!="string"||typeof n.eventId!="string"||typeof n.sessionId!="string"||typeof n.prompt!="string"||typeof n.createdAt!="number")throw new Error("memory_turn_payload_invalid");await Vt({projectRoot:this.projectRoot,payload:n,memory:await this.getMemoryGate()});}scheduleMemoryTurnSpoolDrain(e){this.memoryTurnSpoolTimer||(this.memoryTurnSpoolTimer=setTimeout(()=>{this.memoryTurnSpoolTimer=null,this.drainMemoryTurnSpool();},e),this.memoryTurnSpoolTimer.unref());}async drainMemoryTurnSpool(){for(;;){let e=Er(this.projectRoot);if(!e)return;try{Jt({projectRoot:this.projectRoot,sessionId:e.payload.sessionId,prompt:e.payload.prompt}),Tr(e),this.workRuntime.drainOnce();}catch(n){Ar(e),this.logRuntime("warn","memory_turn_spool_replay",{reason:n.message,fallback:"bounded_retry"},e.payload.sessionId),this.scheduleMemoryTurnSpoolDrain(1e3);return}}}async bootstrapSessionWork(e){if(!e||typeof e!="object"||typeof e.sessionId!="string")throw new Error("session_bootstrap_payload_invalid");let n=e.sessionId,o=await this.getMemoryGate();await o.ensureSession(n,this.projectRoot,"Host session"),await o.releasePendingDistillLeases(n),await this.refreshMemorySnapshot("session_bootstrap");}noteTelemetryOperation(){this.successfulTelemetryOperations++,this.successfulTelemetryOperations>=ku&&this.flushTelemetry();}async flushTelemetry(){this.successfulTelemetryOperations=0,await this.telemetry.flushAndAggregate();}startExplicitIntentFlush(){this.explicitIntentFlush||(this.explicitIntentFlush=this.flushExplicitMemoryIntents().finally(()=>{this.explicitIntentFlush=null;}));}async handleStop(e){let n=null,o=false,r;try{let i=JSON.parse(e);typeof i.session_id=="string"&&i.session_id.trim()&&(n=i.session_id.trim()),o=i.stop_hook_active===!0,typeof i.transcript_path=="string"&&i.transcript_path.trim()&&(r=i.transcript_path.trim());}catch{}if(n??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null,this.startExplicitIntentFlush(),n){let i=qr({projectRoot:this.projectRoot,sessionId:n,transcriptPath:r,stopHookActive:o,runtimeStore:this.runtimeStore});if(i.decision==="block_once")return y({event:"hook.stop.degraded",identity:{projectRoot:this.projectRoot,sessionId:n},level:"warn",timestamp:Date.now(),data:{decision:"block_once",unresolved:i.unresolved.map(a=>a.obligationId)}}),{decision:"block",reason:i.additionalContext};let s=this.runtimeStore.completeExecution(n);if(s?.executionId){let a=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50}),c={};try{let d=a.listSessionMemoryTurnsForReconciliation(this.projectRoot,n);c={...Mt(d),evidenceDegradations:s.evidenceDegradations,evidenceContractOutcomes:s.evidenceOutcomes,unresolvedObligations:i.unresolved,terminalState:i.decision};}finally{a.close();}await this.telemetry.sendExecutionComplete(s.executionId,"completed",Date.now(),c),this.deleteContextReceipt(n,s.executionId);}y({event:"hook.stop.completed",identity:{projectRoot:this.projectRoot,sessionId:n,executionId:s?.executionId},level:"info",timestamp:Date.now(),data:{decision:i.decision,unresolvedCount:i.unresolved.length}});}return null}async flushExplicitMemoryIntents(){this.flushTelemetry();let e=Go(this.projectRoot);if(e)try{let n=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);await n.forceWarmUp();let o=!1;for(;e.intents.length>0;){let r=e.intents[0];if(r.turnId){let s=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let a=s.getMemoryTurn(r.turnId);if(!a||a.status!=="pending"){this.logRuntime("warn","legacy_memory_intent_drop",{turnId:r.turnId,status:a?.status??"missing"},r.sessionId),Ot(e);continue}}finally{s.close();}}let i=await n.saveExplicitMemoryIntent(r.content,{actorId:"actor:claude-code",sessionId:r.sessionId},r.eventId);if(o=!0,r.turnId){let s=openGlobalDevFlowDatabase();try{let a=s.commitMemoryTurn({turnId:r.turnId,receiptId:xe(r.turnId,"committed",[i.id]),memoryIds:[i.id],source:"explicit_intent",reason:"explicit_user_request_retry"});if(a.receiptId)try{await n.finalizeTurnDecision({turnEventId:a.eventId,sessionId:a.sessionId,turnId:a.turnId,receiptId:a.receiptId,status:"committed",memoryIds:[i.id],reason:"explicit_user_request_retry"});}catch(c){this.logRuntime("warn","memory_lineage_finalize",{reason:c.message,fallback:"session_end_reconciliation",turnId:r.turnId},r.sessionId);}try{await n.enrichExplicitMemoryObservation(i.id);}catch(c){s.enqueueWork({idempotencyKey:`explicit-enrichment:${this.projectRoot}:${i.id}`,kind:"memory.explicit_enrichment",projectRoot:this.projectRoot,sessionId:r.sessionId,turnId:r.turnId,payload:{observationId:i.id},maxAttempts:20}),this.logRuntime("warn","explicit_memory_enrichment",{reason:c.message,fallback:"durable_work_queue",memoryId:i.id,turnId:r.turnId},r.sessionId);}}finally{s.close();}}Ot(e);}o&&await this.refreshMemorySnapshot("legacy_explicit_memory_commit");}catch(n){this.logRuntime("error","legacy_memory_intent_flush",{reason:n.message,fallback:"claim_remains_retryable"});}}deleteContextReceipt(e,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),o.deleteContextReceipt(this.projectRoot,e,n);}catch{}finally{o?.close();}}async refreshMemorySnapshot(e){try{let n=loadConfig(this.projectRoot).sessionStart?.injectMemories??!0,o=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return await Ze({projectRoot:this.projectRoot,memory:o,injectConfig:n,reason:e})}catch(n){return this.logRuntime("warn","memory_snapshot_refresh",{reason:n.message,fallback:"cached_snapshot",trigger:e}),Bt({projectRoot:this.projectRoot,reason:e,load:async()=>{throw n}})}}async handleMemorySnapshot(){let e=await this.refreshMemorySnapshot("memory_snapshot_request"),{snapshot:n}=e;return {status:n.status==="ready"||n.status==="disabled"?"ok":n.status,enabled:n.status!=="disabled",markdown:n.markdown,memoryIds:n.memoryIds,memoryCount:n.memoryIds.length,conflicts:n.conflicts,snapshot:n,persisted:e.persisted}}async handleSessionEnd(e){let n=null;try{let s=JSON.parse(e);typeof s.session_id=="string"&&s.session_id.trim()&&(n=s.session_id.trim());}catch{}n??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null;let o=n===null?this.activeSessionIds.size<=1:this.activeSessionIds.size<=1&&this.activeSessionIds.has(n),r=n?this.runtimeStore.get(n)?.executionId:void 0,i=Je(e,this.projectRoot,o,r);return i?.workState==="spooled"&&this.scheduleSessionFinalizeSpoolDrain(250),n&&(this.serverManager.removeRef(n),this.activeSessionIds.delete(n),this.eventMap=this.eventMap.filter(s=>s.sessionId!==n)),this.activeSessionIds.size===0&&i?.workState!=="spooled"&&i?.workItemId?setImmediate(()=>{this.workRuntime.drainWorkItemOnce(i.workItemId).finally(()=>{this.shutdown();});}):this.resetIdleTimer(),i??{status:"ok"}}async finalizeSessionWork(e,n){if(!e||typeof e!="object")throw new Error("session_finalize_payload_invalid");let o=e;if(typeof o.inputJson!="string"||typeof o.sessionId!="string")throw new Error("session_finalize_payload_invalid");let r=await this.getMemoryGate();await zo(o.inputJson,this.projectRoot,o.cleanupSharedState!==false,{telemetry:this.telemetry,memory:r,executionId:o.executionId});try{await this.refreshMemorySnapshot("session_finalization");}catch(s){this.logRuntime("warn","session_finalize_snapshot",{reason:s.message,fallback:"durable_memory_authoritative"},o.sessionId);}let i=openGlobalDevFlowDatabase();try{i.completeSessionClosure(this.projectRoot,o.sessionId,n);}finally{i.close();}}enqueueLearningAnalysisIfReady(e,n){if(resolveCapabilityRollout(this.projectRoot).config.learningOverlays==="off")return;let r=e.getSessionClosure(this.projectRoot,n);if(!r||r.state!=="closed"||r.pendingWorkCount!==0||e.listSessionObligations(this.projectRoot,n).some(c=>c.state==="open"||c.state==="degraded"))return;let s=e.getLatestSkillExecutionForSession(n);if(s&&s.status==="running")return;let a=Tu(this.projectRoot);e.enqueueWork({idempotencyKey:`learning-analysis:${r.receiptId}:${a}`,kind:"learning.analyze_session",projectRoot:this.projectRoot,sessionId:n,payload:{projectRoot:this.projectRoot,sessionId:n,executionId:s?.executionId,closureReceipt:r.receiptId,projectRevision:a,createdAt:Date.now()},maxAttempts:5});}scheduleSessionFinalizeSpoolDrain(e){this.sessionFinalizeSpoolTimer||(this.sessionFinalizeSpoolTimer=setTimeout(()=>{this.sessionFinalizeSpoolTimer=null,this.drainSessionFinalizeSpool();},e),this.sessionFinalizeSpoolTimer.unref());}async drainSessionFinalizeSpool(){for(;;){let e=bo(this.projectRoot);if(!e)return;try{if(!Je(e.payload.inputJson,this.projectRoot,e.payload.cleanupSharedState,e.payload.executionId,!1))throw new Error("session_finalize_spool_rejected");Ro(e),this.workRuntime.drainOnce();}catch(n){So(e),this.logRuntime("warn","session_finalize_spool_replay",{reason:n.message,fallback:"bounded_retry"},e.payload.sessionId),this.scheduleSessionFinalizeSpoolDrain(1e3);return}}}shutdown(){return this.shutdownPromise?this.shutdownPromise:(this.shutdownPromise=this.performShutdown(),this.shutdownPromise)}async performShutdown(){this.workRuntime.stop(),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.telemetryFlushTimer&&(clearInterval(this.telemetryFlushTimer),this.telemetryFlushTimer=null),this.memoryTurnSpoolTimer&&(clearTimeout(this.memoryTurnSpoolTimer),this.memoryTurnSpoolTimer=null),this.sessionFinalizeSpoolTimer&&(clearTimeout(this.sessionFinalizeSpoolTimer),this.sessionFinalizeSpoolTimer=null),await this.flushTelemetry(),await this.closeServer(),this.cleanupOwnedResources(),await this.serverManager.stop(),await this.explicitIntentFlush,this.explicitMemoryGate?.close(),this.explicitMemoryGate=null,this.telemetry.close(),process.exit(0);}closeServer(){let e=this.server;return !e||!e.listening||!this.pathMatchesIdentity(this.socketPath,this.socketIdentity)?Promise.resolve():(this.server=null,new Promise(n=>{let o=false,r=()=>{o||(o=true,clearTimeout(i),n());},i=setTimeout(r,vu);e.close(r);}))}cleanupOwnedResources(){try{so(this.projectRoot,process.pid);}catch(e){this.logRuntime("warn","daemon_unregister",{reason:e.message});}this.removePathIfOwned(this.socketPath,this.socketIdentity,"socket"),this.removePathIfOwned(this.pidPath,this.pidIdentity,"PID file",`${process.pid}
42
+ `);}};function Eu(t){if(t)try{let e=JSON.parse(t);return typeof e.session_id=="string"&&e.session_id.trim()?e.session_id.trim():void 0}catch{return}}function Tu(t){try{return execFileSync("git",["rev-parse","HEAD"],{cwd:t,encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return `unversioned:${createHash("sha256").update(t).digest("hex").slice(0,16)}`}}if(process.env.DEVFLOW_HOOK_DAEMON_DISABLE_AUTOSTART!=="1"){let t=process.argv[2]||process.env.CLAUDE_PROJECT_DIR||process.cwd(),e=new wn(t,process.argv[3]);process.once("SIGTERM",()=>{e.shutdown();}),process.once("SIGINT",()=>{e.shutdown();}),e.start().catch(n=>{console.error("[devflow-daemon] Failed to start:",n),process.exit(1);});}export{wn as HookDaemon,xu as injectProjectRootIfMissing};