@devflow-tools/cli 0.17.3 → 0.17.4

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,40 +1,40 @@
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,getDaemonSocketPath,getDaemonPidPath,resolveCapabilityRollout,loadConfig,readRuntimeEndpointState,updateRuntimeEndpointStatus,resolveRuntimeEndpoint,writeRuntimeEndpointState,appendTaskRuntimeBoundary,taskSpecFromImmutableIntent,selectHostAdapter,getProjectStateDir,formatSkillRuntimeOverlay,createSkillRuntimeOverlay,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,claudeCodeRuntimeAdapter,getDaemonRegistryPath,getProjectHash,createDefaultHostAdapterRegistry}from'@devflow-tools/sdk';import {homedir as homedir$1}from'os';import {openGlobalDevFlowDatabase,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,realpathSync,appendFileSync,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 {homedir}from'node:os';import {fileURLToPath}from'url';import {emitSemanticControlLog}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 {GraderRegistry}from'@devflow-tools/benchmark';import {createManagedWorktree,createWorkerArtifacts,launchWorker,readWorkerHandoff,verifyWorkerOutput,SerializedWorkerMergeQueue,cleanupManagedWorktree,workerCoordinationRoot,writeJsonAtomic}from'@devflow-tools/workflow-engine';import {buildRetrievalTaskPlan,parseIntent,buildChannelQueryPlan}from'@devflow-tools/context-engine';function X(e,t,n){try{let o=openGlobalDevFlowDatabase();try{o.insertEvent({kind:e,timestamp:Date.now(),duration:n,success:t.success!==!1,metadata:t});}finally{o.close();}}catch{}}var hi=getLocalApiKey(),ut=join(homedir(),".devflow","errors");async function G(e,t,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,e);if(a&&!c.allowed)return {delivered:false,suppressed:true,fallbackReason:c.state.fallbackReason};let d;for(let u=0;u<=s;u+=1)try{return await yi(o,e,t,r),a&&registerRuntimeHttpSuccess(o,e).transitioned&&X("http_circuit_transition",{endpoint:o,path:new URL(e,o).pathname,previous:c.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(p){d=p instanceof Error?p:new Error(String(p)),u<s&&await _i(Math.min(100*2**u,1e3));}if(!d)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return Sn(e,d),{delivered:false,suppressed:false,fallbackReason:d.message};let l=registerRuntimeHttpFailure(o,e,n.fallbackReason??(i?"local_durable_mirror":"http_delivery_failed"));return l.transitioned&&(Sn(e,d),X("http_circuit_transition",{endpoint:o,path:new URL(e,o).pathname,previous:c.state.status,status:"open",failures:l.state.failures,openUntil:l.state.openUntil,fallbackReason:l.state.fallbackReason})),{delivered:false,suppressed:false,fallbackReason:l.state.fallbackReason}}function yi(e,t,n,o){return new Promise((r,i)=>{let s=JSON.stringify(n),a=new URL(t,e),c=false,d=u=>{c||(c=true,u?i(u):r());},l=request$1({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":hi,"Content-Length":Buffer.byteLength(s)},timeout:o},u=>{u.on("error",d),u.on("end",()=>{let p=u.statusCode??0;d(p>=200&&p<300?void 0:new Error(`HTTP ${p}`));}),u.resume();});l.on("error",d),l.on("timeout",()=>l.destroy(new Error(`HTTP mirror timed out after ${o}ms`))),l.write(s),l.end();})}function Sn(e,t){try{existsSync(ut)||mkdirSync$1(ut,{recursive:!0}),appendFileSync(join(ut,"http-errors.log"),`${new Date().toISOString()} | ${e} | ${t.message}
2
- `);}catch{}}function _i(e){return new Promise(t=>setTimeout(t,e))}var Dn=1e4,bi=3e4,De=500,ee=class{constructor(t){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=t?.apiUrl,this.cacheDir=t?.cacheDir??join$1(process.env.DEVFLOW_STATE_DIR??join$1(homedir$1(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=t?.legacyCacheDir??(t?.cacheDir?null:join$1(homedir$1(),".devflow","telemetry-cache")),this.database=t?.database??null,this.ownsDatabase=!t?.database;let n=t?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(n)&&n>=0?n:100;}async sendEvent(t){let n={...t,input:this.truncateInput(t.input)};return this.commitOrCache("tool_call",n)?(this.postHttp("/api/telemetry/tool-call",n),t.eventId):null}async sendExecutionStart(t,n,o,r,i=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:t,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(t,n="completed",o=Date.now(),r){let i={executionId:t,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(t,n,o){let r={id:t,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(t){let n=this.commitOrCache("complete_event",t);return n&&(this.postHttp("/api/telemetry/tool-call/output",t),this.scheduleMetricAggregation()),n}async endSession(t,n=Date.now()){let o={sessionId:t,finishedAt:n},r=this.commitOrCache("session_end",o);return r&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:n})),r}async flushCache(){try{let o=this.getDatabase(),r=o.listTelemetryFailures({unresolvedOnly:!0,limit:De}).reverse();for(let i of r)try{this.applyOperation(i.operation,i.payload),o.resolveTelemetryFailure(i.id);}catch{}o.trimTelemetryFailures(De);}catch{}let n=[...new Set([this.cacheDir,this.legacyCacheDir].filter(o=>!!o))].filter(o=>existsSync$1(o)).flatMap(o=>readdirSync(o).filter(r=>r.endsWith(".json")).map(r=>{let i=join$1(o,r);try{return {cacheFile:i,envelope:Ri(JSON.parse(readFileSync(i,"utf8")),r)}}catch{return null}})).filter(o=>o!==null).sort((o,r)=>o.envelope.timestamp-r.envelope.timestamp||Mn(o.envelope.operation)-Mn(r.envelope.operation));for(let{cacheFile:o,envelope:r}of n)try{let i=this.getDatabase();i.insertTelemetryFailure({id:r.id,operation:r.operation,payload:r.payload,error:r.failure,createdAt:r.timestamp}),this.applyOperation(r.operation,r.payload),i.resolveTelemetryFailure(r.id),unlinkSync(o);}catch{}this.database?.aggregatePendingToolMetrics();}aggregateMetrics(){return this.getDatabase().aggregatePendingToolMetrics()}async flushAndAggregate(){await this.flushCache(),this.aggregateMetrics();}close(){this.ownsDatabase&&this.database?.close(),this.database=null;}getDatabase(){return this.database??=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:this.busyTimeoutMs}),this.database}commitOrCache(t,n){try{return this.applyOperation(t,n),!0}catch(o){return this.cacheOperation(t,n,o),false}}applyOperation(t,n){let o=this.getDatabase();switch(t){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:On(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(On(n.sessionId),{status:"completed",finishedAt:n.finishedAt});return}}ensureParentSession(t,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";t.ensureSession({id:o,projectRoot:r,label:r==="unknown"?void 0:r.split("/").pop(),startedAt:Number(n.startedAt??n.timestamp??Date.now())});}cacheOperation(t,n,o){let r=Date.now(),i={id:`failure:${r}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:n,failure:o instanceof Error?o.message:String(o),timestamp:r};try{let s=this.getDatabase();s.insertTelemetryFailure({id:i.id,operation:t,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.trimCompatibilityCache(),this.scheduleRetry();}catch{}}trimCompatibilityCache(){try{let t=readdirSync(this.cacheDir).filter(n=>n.endsWith(".json")).sort();for(let n of t.slice(0,Math.max(0,t.length-De)))unlinkSync(join$1(this.cacheDir,n));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},bi).unref());}scheduleMetricAggregation(){if(this.metricAggregationScheduled||process.env.DEVFLOW_HOOK_DEGRADED==="1")return;this.metricAggregationScheduled=true,setTimeout(()=>{this.metricAggregationScheduled=false;try{this.getDatabase().aggregatePendingToolMetrics(50)===50&&this.scheduleMetricAggregation();}catch{}},25).unref();}postHttp(t,n){G(t,n,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let n=JSON.stringify(t);return n===void 0||n.length<=Dn?t:{_truncated:true,_original_size:n.length,_preview:`${n.substring(0,Dn)}...`}}};function Mn(e){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(e)}function On(e){return `hook-run:${e}`}function Ri(e,t){if(!e||typeof e!="object")throw new Error("Invalid telemetry cache envelope");let n=e;if(typeof n.operation=="string"&&n.payload!==void 0)return n;let o=n.type==="tool_call"?"tool_call":n.type==="execution_start"?"execution_start":null;if(!o)throw new Error("Unknown legacy telemetry cache operation");let r=n.payload??{},i=Number(r.timestamp??r.startedAt??Date.now());return {id:`legacy-cache:${t}`,operation:o,payload:r,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:i}}function Me(e){return e??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function M(e){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(Me(e))}var Ci=2,Di=1;function Mi(){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 Pn(e=Mi()){let t=[join$1(e,"dist","command-registry.json"),join$1(e,"command-registry.json")];for(let n of t)try{if(!existsSync$1(n))continue;let o=JSON.parse(readFileSync(n,"utf8"));if(o.version!==Ci&&o.version!==Di||!Oi(o.commands)){emitSemanticControlLog({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){emitSemanticControlLog({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 Oi(e){return !e||typeof e!="object"||Array.isArray(e)?false:Object.values(e).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return false;let n=t;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||Pi(n.hostTools))&&(n.evidenceMode===void 0||["static","runtime","mixed"].includes(n.evidenceMode))})}function Pi(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&Object.entries(e).every(([t,n])=>t.length>0&&Oe(n))}function Oe(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0)}function jn(e){let t=Pn();return t?t[e]?.mcpTools??[]:[]}function Fn(e,t,n){return formatSkillRuntimeOverlay(createSkillRuntimeOverlay(e,t,{prompt:n}))}var pt=join$1(homedir$1(),".devflow"),ft=join$1(pt,"server-refs.json"),Bi=600*1e3,Ji=500;function Gi(){existsSync$1(pt)||mkdirSync(pt,{recursive:true});}function Pe(){try{if(existsSync$1(ft))return JSON.parse(readFileSync(ft,"utf-8"))}catch{}return {sessions:[],lastActivity:0}}function $n(e){Gi(),writeFileSync(ft,JSON.stringify(e));}var Fe=class{constructor(t){this.process=null;this.idleTimer=null;this.onShutdown=null;this.ownerToken=null;this.projectRoot=t;}setOnShutdown(t){this.onShutdown=t;}addRef(t){let n=Pe();n.sessions.includes(t)||n.sessions.push(t),n.lastActivity=Date.now(),$n(n),this.resetIdleTimer();}removeRef(t){let n=Pe();n.sessions=n.sessions.filter(o=>o!==t),n.lastActivity=Date.now(),$n(n),n.sessions.length===0&&this.resetIdleTimer();}get activeSessions(){return Pe().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 t=readRuntimeEndpointState();t&&t.ownerToken===this.ownerToken&&updateRuntimeEndpointStatus("stopped");}}async startServer(){let t=Ki(this.projectRoot);this.ownerToken=randomUUID$1();let n=resolveRuntimeEndpoint();this.process=spawn(process.execPath,[t,"--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 t=Date.now()+3e4;for(;Date.now()<t;){if(await this.healthCheck())return true;await new Promise(n=>setTimeout(n,Ji));}return false}healthCheck(){return new Promise(t=>{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(),t(s);});r.on("error",()=>t(false)),r.on("timeout",()=>{r.destroy(),t(false);}),r.end();})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),!(Pe().sessions.length>0)&&(this.idleTimer=setTimeout(()=>{this.stop();},Bi).unref());}};function Ki(e){let t=createRequire(import.meta.url),n=[()=>t.resolve("@devflow-tools/server/dist/main.js"),()=>join$1(e,"node_modules","@devflow-tools","server","dist","main.js"),()=>join$1(e,"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 $e(e){if(!e||typeof e!="object"||Array.isArray(e))return {};let t=e,n={};for(let o of ["lastMcpCall","bypassCount"])if(o in t){let r=t[o];if(r==null)continue;n[o]=typeof r=="number"&&Number.isFinite(r)&&r>=0?r:0;}return n}function Qi(e,t){return e.lastMcpCall===t.lastMcpCall&&e.bypassCount===t.bypassCount}function Xi(e){try{return existsSync$1(e)?$e(JSON.parse(readFileSync(e,"utf-8"))):{}}catch{return {}}}function Zi(e,t,n){let o=n instanceof Error?n.message:String(n);emitSemanticControlLog({event:"hook.runtime.degraded",identity:{projectRoot:e},level:"warn",timestamp:Date.now(),data:{stage:"enforcement_receipt",operation:t,reason:o,fallback:"fail_open"}});}function Hn(e){let t=M(e);for(let n of ["receipt.json","receipt-lock.sqlite","receipt-lock.sqlite-shm","receipt-lock.sqlite-wal"])try{existsSync$1(join$1(t,n))&&unlinkSync(join$1(t,n));}catch{}}function es(e,t){if(e.getHookReceipt(t)){Hn(t);return}let n=join$1(M(t),"receipt.json");if(!existsSync$1(n))return;let o=Xi(n);e.updateHookReceipt(t,()=>o),Hn(t);}function Ln(e,t,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),es(o,e);let r={},i=o.updateHookReceipt(e,a=>(r=$e(a),$e(t(r)))),s=$e(i);return {receipt:s,applied:!0,changed:!Qi(r,s)}}catch(r){return Zi(e,n,r),{receipt:{},applied:false,changed:false}}finally{try{o?.close();}catch{}}}function He(e,t){return Ln(e,()=>t,"write").applied}function _t(e,t){return Ln(e,t,"update")}var Nn={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},ts=new Set(["Write","Edit","NotebookEdit"]),ns=new Set(["failed","timeout","unavailable"]);function os(e){switch(e){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var te=class{constructor(t,n,o){this.projectRoot=t;this.sessionId=n;this.executionId=o;}getPhase(){if(!this.sessionId||!this.executionId)return "idle";let t;try{t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let n=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(n&&n.expiresAt>Date.now())return "context_ready";n&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId);}catch{}finally{try{t?.close();}catch{}}return "context_gathering"}getContextReceipt(){if(!this.sessionId||!this.executionId)return null;let t;try{t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let n=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);return n&&n.expiresAt>Date.now()?n:(n&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId),null)}catch{return null}finally{try{t?.close();}catch{}}}evaluate(t,n){let o=this.getPhase();if(n||t==="Skill")return {permissionDecision:"allow"};if(o==="context_gathering"&&Nn[t])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_REQUIRED",reason:`DevFlow context required. Call mcp__devflow__get_project_context, then retry ${t}.`};if(o==="context_ready"){if(ts.has(t)){let c=this.evaluateRequiredAction();if(c)return c}return {permissionDecision:"allow"}}let r=Nn[t];if(!r)return {permissionDecision:"allow"};let i=_t(this.projectRoot,c=>({...c,bypassCount:(c.bypassCount??0)+1}));if(!i.applied)return {permissionDecision:"allow"};let s=i.receipt.bypassCount??0,a=os(t);return s>=a?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \u6B21\u76F4\u63A5\u4F7F\u7528 ${t}\uFF0C\u5EFA\u8BAE\u7528 mcp__devflow__${r} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){He(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}recordDomainActionOutcome(t,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!==t)return !1;let a=Date.now(),c=r?.trim()?`${r.trim()}:${n}`:`${t}:${n}:${a}`,d=s.actionAttempts??[];return i.upsertContextReceipt({...s,actionAttempts:d.some(l=>l.id===c||r&&l.toolUseId===r&&l.status===n)?d:[...d,{id:c,tool:t,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 t=this.getContextReceipt(),n=t?.canonicalAction;if(!t||!n||!n.required||n.status!=="required")return null;let o=n.binding;if(o.requiredContextReceipt!==t.contextHash||o.projectRoot!==this.projectRoot||o.sessionId!==this.sessionId||o.requestId!==t.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(t.actionSatisfiedAt)return null;if(t.actionDegradation?.authorizedByContextReceipt===t.contextHash)return {permissionDecision:"allow",additionalContext:`DevFlow degraded fallback authorized by context receipt ${t.contextHash}: ${t.actionDegradation.reason}`};let r=(t.actionAttempts??[]).filter(i=>i.tool===n.tool&&ns.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:t.contextHash,authorizedAt:Date.now()};return this.persistDegradation(t,s),{permissionDecision:"allow",additionalContext:`DevFlow canonical tool mcp__devflow__${n.tool} ${i.status}; degraded direct write authorized by context receipt ${t.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 ${t.contextHash}, then retry the write. Direct fallback is allowed only after unavailable, failed, or timeout evidence.`}}persistDegradation(t,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let r=o.getContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!r||r.contextHash!==t.contextHash||r.actionDegradation)return;o.upsertContextReceipt({...r,actionDegradation:n});let i=o.getSkillExecution(t.executionId);if(!i)return;let s=i.metadata&&typeof i.metadata=="object"?i.metadata:{},a=Array.isArray(s.requiredActionDegradations)?s.requiredActionDegradations:[];o.updateSkillExecution(t.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 ds=10,ls=5e3,us=3e4,ms=new Int32Array(new SharedArrayBuffer(4)),Jn=0;function ps(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.rootPath=="string"&&t.rootPath.length>0&&typeof t.projectHash=="string"&&t.projectHash.length>0&&typeof t.pid=="number"&&Number.isInteger(t.pid)&&t.pid>0&&typeof t.startedAt=="number"&&Number.isFinite(t.startedAt)&&t.startedAt>=0}function Gn(e){if(!existsSync(e))return {entries:[],needsRepair:false};try{let t=JSON.parse(readFileSync$1(e,"utf8"));if(!Array.isArray(t))return {entries:[],needsRepair:!0};let n=t.filter(ps);return {entries:n,needsRepair:n.length!==t.length}}catch{return {entries:[],needsRepair:true}}}function Kn(e,t){mkdirSync$1(dirname$1(e),{recursive:true});let n=`${e}.${process.pid}.${Date.now()}.${Jn++}.tmp`,o;try{o=openSync$1(n,"wx"),writeFileSync$1(o,JSON.stringify(t,null,2)),closeSync$1(o),o=void 0,renameSync(n,e);}finally{try{o!==void 0&&closeSync$1(o);}finally{rmSync$1(n,{force:true});}}}function Vn(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function Yn(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.pid=="number"&&Number.isInteger(t.pid)&&t.pid>0&&typeof t.createdAt=="number"&&Number.isFinite(t.createdAt)&&typeof t.token=="string"&&t.token.length>0}function Wn(e,t){try{return readFileSync$1(e,"utf8")!==t?!1:(rmSync$1(e),!0)}catch(n){return n.code==="ENOENT"}}function fs(e){try{let t=readFileSync$1(e,"utf8"),n;try{let r=JSON.parse(t);Yn(r)&&(n=r);}catch{}return n?Vn(n.pid)?!1:Wn(e,t):Date.now()-statSync(e).mtimeMs>us&&Wn(e,t)}catch(t){return t.code==="ENOENT"}}function gs(e){mkdirSync$1(dirname$1(e),{recursive:true});let t=`${e}.lock`,n=Date.now()+ls;for(;;){let o=`${process.pid}:${Date.now()}:${Jn++}`,r;try{return r=openSync$1(t,"wx"),writeFileSync$1(r,JSON.stringify({pid:process.pid,createdAt:Date.now(),token:o})),closeSync$1(r),r=void 0,{path:t,token:o}}catch(i){if(r!==void 0)try{closeSync$1(r);}finally{rmSync$1(t,{force:true});}if(i.code!=="EEXIST")throw i}if(!fs(t)){if(Date.now()>=n)throw new Error(`Timed out acquiring daemon registry lock: ${t}`);Atomics.wait(ms,0,0,ds);}}}function hs(e){try{let t=readFileSync$1(e.path,"utf8"),n=JSON.parse(t);Yn(n)&&n.token===e.token&&rmSync$1(e.path);}catch(t){if(t.code!=="ENOENT")throw t}}function Qn(e){let t=getDaemonRegistryPath(),n=gs(t);try{return e(t)}finally{hs(n);}}function Xn(e,t){Qn(n=>{let o=Gn(n).entries.filter(r=>r.rootPath!==e&&Vn(r.pid));o.push({rootPath:e,projectHash:getProjectHash(e),pid:t,startedAt:Date.now()}),Kn(n,o);});}function Zn(e,t){Qn(n=>{let o=Gn(n).entries.filter(r=>r.rootPath!==e||t!==void 0&&r.pid!==t);Kn(n,o);});}async function he(e){let t=!e.memory,n=e.memory??new MemoryGate(e.projectRoot),o=0,r=0;try{await n.forceWarmUp(),e.trigger==="session_end"&&(o=await n.releasePendingDistillLeases(e.sessionId)),r=n.getPendingEventCount(e.sessionId,e.trigger!=="session_end");}finally{t&&n.close();}let i=Date.now(),s=e.trigger==="session_end"&&e.sessionId?`distill:session_end:${createHash("sha256").update(`${e.projectRoot}\0${e.sessionId}`).digest("hex").slice(0,24)}`:`distill:${i}:${Math.random().toString(36).slice(2,10)}`,a={id:s,pendingEvents:r,releasedLeases:o,trigger:e.trigger,sessionId:e.sessionId,details:e.details};try{let c=openGlobalDevFlowDatabase();try{c.recordMemoryDistillCheckpoint({id:s,projectRoot:e.projectRoot,sessionId:e.sessionId,trigger:e.trigger,pendingEvents:r,releasedLeases:o,details:e.details,createdAt:i}),c.insertEvent({kind:"memory_distill_requested",timestamp:i,success:!0,metadata:{...a,projectRoot:e.projectRoot}});}finally{c.close();}}catch(c){if(e.strictPersistence)throw c}return a}function eo(e){if(e.pendingEvents===0)return "";let t=e.sessionId?`\uFF0CsessionId=${e.sessionId}`:"";return `Memory distill checkpoint: ${e.pendingEvents} \u4E2A\u4E8B\u4EF6\u5F85\u63D0\u70BC${t}\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 ro(e){return Buffer.from(e,"utf8").toString("base64url")}function bs(e,t,n){let o=t?.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 `${e}:${r}`}return `${e}:legacy-${n}-${randomUUID().slice(0,8)}`}function uo(e){return `${e}:legacy-journal`}var L=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(M(t),"hook-sessions");}registerSession(t){let n=t.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(t,n,o){let r=this.registerSession(t);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(t,n){let o=this.registerSession(t);return o.activeTurnId=n.turnId,o.activeRequestId=n.requestId,o.intentArtifactHash=n.intentArtifactHash,o.lastActivityAt=Date.now(),this.persist(o),o}get(t){let n=t.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=io(i.evidenceObligations),i.evidenceDegradations=so(i.evidenceDegradations),i.evidenceOutcomes=ao(i.evidenceOutcomes),this.replayEvidenceJournal(i),this.sessions.set(n,i),i)}catch{return null}}completeExecution(t){let n=this.get(t);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(t,n,o=Date.now(),r){let i=this.registerSession(t),a=(r?void 0:i.evidenceObligations.find(d=>d.contractId===n.id))?.obligationId??bs(n.id,r,o);this.appendEvidenceEvent(t,{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(t){return (this.get(t)?.evidenceObligations??[]).map(n=>structuredClone(n))}markEvidenceCorrection(t,n,o,r,i=Date.now()){let s=this.get(t),a=s?.evidenceObligations.find(l=>l.obligationId===n);if(!s||!a)return null;let c=/^[a-f0-9]{64}$/.test(r)?r:"";if(!c)return null;this.appendEvidenceEvent(t,{kind:"correction",obligationId:n,contractId:a.contractId,at:i,fingerprint:c,violations:o.slice(0,16).map(l=>l.slice(0,240))},`correction\0${n}\0${c}`),this.replayEvidenceJournal(s),s.lastActivityAt=i,this.persist(s);let d=s.evidenceObligations.find(l=>l.obligationId===n);return d?structuredClone(d):null}resolveEvidenceObligation(t,n){let o=this.get(t);if(!o)return false;let r=o.evidenceObligations.find(s=>s.obligationId===n);if(!r)return false;let i=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:n,contractId:r.contractId,at:i},`resolve\0${n}`),this.replayEvidenceJournal(o),o.lastActivityAt=i,this.persist(o),true}resolveDegradedEvidence(t,n){let o=this.get(t),r=o?.evidenceDegradations.find(s=>s.obligationId===n);if(!o||!r)return false;let i=Date.now();return this.appendEvidenceEvent(t,{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(t,n,o,r=Date.now()){let i=this.get(t),s=i?.evidenceObligations.find(c=>c.obligationId===n);if(!i||!s)return false;let a=o.slice(0,240);return this.appendEvidenceEvent(t,{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(t){let n=t.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(t){return join$1(this.sessionsDir,`${ro(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",ro(t))}appendEvidenceEvent(t,n,o){let r=this.evidenceJournalDir(t);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(t){t.evidenceObligations=io(t.evidenceObligations),t.evidenceDegradations=so(t.evidenceDegradations),t.evidenceOutcomes=ao(t.evidenceOutcomes);let n=this.evidenceJournalDir(t.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=Rs(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||co(i.kind)-co(s.kind));for(let i of r)this.applyEvidenceEvent(t,i);t.evidenceObligations=t.evidenceObligations.slice(-8),t.evidenceDegradations=t.evidenceDegradations.slice(-20),t.evidenceOutcomes=t.evidenceOutcomes.slice(-20);}applyEvidenceEvent(t,n){let o=t.evidenceOutcomes.find(s=>s.obligationId===n.obligationId);if(n.kind==="add"){if(o)return;let s=t.evidenceObligations.find(a=>a.obligationId===n.obligationId);s?(s.contract=n.contract,s.promptedAt=Math.min(s.promptedAt,n.at)):t.evidenceObligations.push({obligationId:n.obligationId,contractId:n.contractId,contract:n.contract,promptedAt:n.at,attempt:0,correctionRequested:false,violations:[]});return}let r=t.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")t.evidenceOutcomes=t.evidenceOutcomes.filter(s=>s.obligationId!==n.obligationId),t.evidenceDegradations=t.evidenceDegradations.filter(s=>s.obligationId!==n.obligationId);else if(o)return;n.kind==="degrade"?(t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==n.obligationId),t.evidenceDegradations.push({obligationId:n.obligationId,contractId:n.contractId,reason:n.reason,degradedAt:n.at,attempt:i,contract:r?.contract})):t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==n.obligationId),t.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(t){mkdirSync(this.sessionsDir,{recursive:true,mode:448});let n=this.snapshotPath(t.sessionId),o=`${n}.${process.pid}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(t),{mode:384}),renameSync$1(o,n);}};function io(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object")return [];let n=t;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)||!mo(n.contract))return [];let o=typeof n.obligationId=="string"&&n.obligationId.length>0&&n.obligationId.length<=384?n.obligationId:uo(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 so(e){return Array.isArray(e)?e.filter(t=>{if(!t||typeof t!="object")return false;let n=t;return typeof n.obligationId=="string"&&typeof n.contractId=="string"&&typeof n.reason=="string"&&typeof n.degradedAt=="number"&&typeof n.attempt=="number"}).slice(-20):[]}function ao(e){return Array.isArray(e)?e.filter(t=>{if(!t||typeof t!="object")return false;let n=t;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 Rs(e){if(!e||typeof e!="object")return null;let t=e,n=t.kind;if(n!=="add"&&n!=="correction"&&n!=="resolve"&&n!=="degrade"||typeof t.contractId!="string"||t.contractId.length>128||typeof t.at!="number")return null;let r={obligationId:typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:uo(t.contractId),contractId:t.contractId,at:t.at};if(n==="add")return mo(t.contract)?{kind:n,...r,contract:t.contract}:null;if(n==="correction"){let i=typeof t.fingerprint=="string"?t.fingerprint:t.transcriptHash;return typeof i=="string"&&/^[a-f0-9]{64}$/.test(i)&&Array.isArray(t.violations)&&t.violations.every(s=>typeof s=="string"&&s.length<=240)?{kind:n,...r,fingerprint:i,violations:t.violations}:null}return n==="resolve"?{kind:n,...r}:typeof t.reason=="string"&&t.reason.length<=240?{kind:n,...r,reason:t.reason}:null}function co(e){return e==="add"?0:e==="correction"?1:2}function mo(e){if(!e||typeof e!="object")return false;let t=e,n=t.requiredSections,o=t.prohibitedClaims;return t.version==="1.0"&&typeof t.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(t.id)&&typeof t.runtimeProfilingOccurred=="boolean"&&typeof t.samplingEvidenceOccurred=="boolean"&&Array.isArray(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 t.canonicalReport=="string"&&Buffer.byteLength(t.canonicalReport,"utf8")<=48*1024&&!!t.correctionPolicy&&t.correctionPolicy.maxAttempts===1&&t.correctionPolicy.repeatedViolation==="fail_open"}function go(e,t){let n=vo(e);mkdirSync$1(n,{recursive:true,mode:448});let o=join(n,`${t.receiptId}.json`);if(existsSync(o))return t.receiptId;let r=`${o}.${process.pid}.tmp`;writeFileSync$1(r,JSON.stringify(t),{mode:384});try{renameSync(r,o);}catch(i){try{unlinkSync$1(r);}catch{}if(!existsSync(o))throw i}return t.receiptId}function ho(e){let t=vo(e);mkdirSync$1(t,{recursive:true,mode:448});let n=readdirSync$1(t).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(t,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 yo(e){unlinkSync$1(e.path);}function _o(e){try{renameSync(e.path,e.path.replace(/\.claim-\d+$/u,""));}catch{}}function vo(e){return join(M(e),"session-finalize-pending")}function C(e){let t=Ms(e.projectRoot),n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let o=Os(n,{...e,projectRoot:t});return o?appendTaskRuntimeBoundary({projectRoot:o.projectRoot,taskSpec:taskSpecFromImmutableIntent(Ps(o)),kind:e.kind,payload:e.payload,dedupeKey:e.dedupeKey,producer:e.producer,database:n})?.snapshot??null:null}catch(o){return emitSemanticControlLog({event:"task.runtime.shadow_mismatch",identity:{projectRoot:t,sessionId:e.sessionId,...e.turnId?{turnId:e.turnId}:{},...e.requestId?{requestId:e.requestId}:{}},level:"warn",timestamp:Date.now(),data:{stage:e.kind,reason:$s(o),authority:"legacy"}}),null}finally{n.close();}}function Ms(e){try{return realpathSync(e)}catch{return e}}function wo(e){if(!js(e.legacyState))return;let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100});try{let n=t.getTaskRuntimeSnapshot(e.artifact.projectRoot,e.artifact.sessionId,e.artifact.turnId);if(!n)return;let o=Fs(e.legacyState);if(n.terminal===o)return;emitSemanticControlLog({event:"task.runtime.shadow_mismatch",identity:ko(e.artifact),level:"warn",timestamp:Date.now(),data:{stage:"terminal_projection",legacyState:e.legacyState,shadowTerminal:n.terminal,expectedTerminal:o,authority:"legacy"}});}catch{}finally{t.close();}}function Os(e,t){return e.listLatestTaskIntentArtifacts(t.projectRoot,t.sessionId).find(n=>t.turnId?n.turnId===t.turnId:t.requestId?n.requestId===t.requestId:true)}function Ps(e){return {identity:ko(e),version:e.version,...e.supersedesHash?{supersedesHash:e.supersedesHash}:{},rawPrompt:e.rawPrompt,normalizedPrompt:e.normalizedPrompt,...e.command?{command:e.command}:{},slashArgs:e.slashArgs,...e.activeSkill?{activeSkill:e.activeSkill}:{},intent:e.intent,action:e.action,entities:e.entities,targetAnchors:e.targetAnchors,policyConstraints:e.policyConstraints,classificationEvidence:e.classificationEvidence,sourceEventIds:e.sourceEventIds,sourceHash:e.sourceHash,artifactHash:e.artifactHash,createdAt:e.createdAt}}function ko(e){return {projectRoot:e.projectRoot,projectId:e.projectId,hostId:e.hostId,sessionId:e.sessionId,turnId:e.turnId,requestId:e.requestId,...e.executionId?{executionId:e.executionId}:{}}}function js(e){return e==="action_failed"||e==="closed"||e==="closed_with_degradation"||e==="closed_with_retry_work"}function Fs(e){return e==="closed"?"completed":e==="closed_with_degradation"?"completed_with_degradation":e==="closed_with_retry_work"?"retry_pending":"failed"}function $s(e){return e instanceof Error?e.message:String(e)}var zs=256*1024,Bs=48*1024,Js=512*1024,Gs=500,Ks=5,ye=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function Vs(e){return e==="react_audit_performance"||e.endsWith("__react_audit_performance")}function Ys(e){let t=_e(e,0,new Set);return t?aa(t.contract,t.canonicalReport):null}function So(e){if(!e.sessionId||!Vs(e.toolName))return null;let t=Ys(e.toolResponse);if(!t)return null;let n=Date.now(),o=e.runtimeStore.addEvidenceObligation(e.sessionId,t,n,e.toolUseId),r=e.runtimeStore.get(e.sessionId);if(o&&r){let i=openGlobalDevFlowDatabase();try{i.upsertSessionObligation({obligationId:`evidence:${o.obligationId}`,projectRoot:r.projectRoot,sessionId:e.sessionId,executionId:r.executionId,kind:"evidence_contract",state:"open",payload:{contract:t,runtimeObligationId:o.obligationId},createdAt:n,updatedAt:n});}finally{i.close();}emitSemanticControlLog({event:"verification.completed",identity:{projectRoot:r.projectRoot,sessionId:e.sessionId,executionId:r.executionId},level:"info",timestamp:n,data:{stage:"performance_detector_coverage",status:"obligation_opened",contractId:t.id,obligationId:o.obligationId,detectorCoverage:Be(e.toolResponse),runtimeProfilingOccurred:t.runtimeProfilingOccurred,samplingEvidenceOccurred:t.samplingEvidenceOccurred,toolUseId:e.toolUseId}});}return Qs(t)}function Qs(e){return [`DevFlow performance evidence contract ${e.id} is active.`,`The final performance answer MUST contain these three sections exactly: ${e.requiredSections.join(" / ")}.`,e.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=${e.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.",e.canonicalReport].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,getDaemonSocketPath,getDaemonPidPath,resolveCapabilityRollout,loadConfig,readRuntimeEndpointState,updateRuntimeEndpointStatus,resolveRuntimeEndpoint,writeRuntimeEndpointState,appendTaskRuntimeBoundary,taskSpecFromImmutableIntent,selectHostAdapter,getProjectStateDir,formatSkillRuntimeOverlay,createSkillRuntimeOverlay,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,claudeCodeRuntimeAdapter,resolveSemanticResolutionMode,projectSemanticFrameToLegacyIntent,getDaemonRegistryPath,getProjectHash,createDefaultHostAdapterRegistry}from'@devflow-tools/sdk';import {homedir as homedir$1}from'os';import {openGlobalDevFlowDatabase,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,realpathSync,appendFileSync,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 {homedir}from'node:os';import {fileURLToPath}from'url';import {emitSemanticControlLog}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 {GraderRegistry}from'@devflow-tools/benchmark';import {createManagedWorktree,createWorkerArtifacts,launchWorker,readWorkerHandoff,verifyWorkerOutput,SerializedWorkerMergeQueue,cleanupManagedWorktree,workerCoordinationRoot,writeJsonAtomic}from'@devflow-tools/workflow-engine';import {buildRetrievalTaskPlan,parseIntent,extractStructuralSemanticEvidence,createProvisionalSemanticFrame,buildChannelQueryPlan}from'@devflow-tools/context-engine';function X(e,t,n){try{let o=openGlobalDevFlowDatabase();try{o.insertEvent({kind:e,timestamp:Date.now(),duration:n,success:t.success!==!1,metadata:t});}finally{o.close();}}catch{}}var vi=getLocalApiKey(),ut=join(homedir(),".devflow","errors");async function G(e,t,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,e);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 _i(o,e,t,r),a&&registerRuntimeHttpSuccess(o,e).transitioned&&X("http_circuit_transition",{endpoint:o,path:new URL(e,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 Ii(Math.min(100*2**l,1e3));}if(!d)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return Sn(e,d),{delivered:false,suppressed:false,fallbackReason:d.message};let u=registerRuntimeHttpFailure(o,e,n.fallbackReason??(i?"local_durable_mirror":"http_delivery_failed"));return u.transitioned&&(Sn(e,d),X("http_circuit_transition",{endpoint:o,path:new URL(e,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 _i(e,t,n,o){return new Promise((r,i)=>{let s=JSON.stringify(n),a=new URL(t,e),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":vi,"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 Sn(e,t){try{existsSync(ut)||mkdirSync$1(ut,{recursive:!0}),appendFileSync(join(ut,"http-errors.log"),`${new Date().toISOString()} | ${e} | ${t.message}
2
+ `);}catch{}}function Ii(e){return new Promise(t=>setTimeout(t,e))}var Dn=1e4,Si=3e4,De=500,ee=class{constructor(t){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=t?.apiUrl,this.cacheDir=t?.cacheDir??join$1(process.env.DEVFLOW_STATE_DIR??join$1(homedir$1(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=t?.legacyCacheDir??(t?.cacheDir?null:join$1(homedir$1(),".devflow","telemetry-cache")),this.database=t?.database??null,this.ownsDatabase=!t?.database;let n=t?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(n)&&n>=0?n:100;}async sendEvent(t){let n={...t,input:this.truncateInput(t.input)};return this.commitOrCache("tool_call",n)?(this.postHttp("/api/telemetry/tool-call",n),t.eventId):null}async sendExecutionStart(t,n,o,r,i=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:t,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(t,n="completed",o=Date.now(),r){let i={executionId:t,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(t,n,o){let r={id:t,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(t){let n=this.commitOrCache("complete_event",t);return n&&(this.postHttp("/api/telemetry/tool-call/output",t),this.scheduleMetricAggregation()),n}async endSession(t,n=Date.now()){let o={sessionId:t,finishedAt:n},r=this.commitOrCache("session_end",o);return r&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:n})),r}async flushCache(){try{let o=this.getDatabase(),r=o.listTelemetryFailures({unresolvedOnly:!0,limit:De}).reverse();for(let i of r)try{this.applyOperation(i.operation,i.payload),o.resolveTelemetryFailure(i.id);}catch{}o.trimTelemetryFailures(De);}catch{}let n=[...new Set([this.cacheDir,this.legacyCacheDir].filter(o=>!!o))].filter(o=>existsSync$1(o)).flatMap(o=>readdirSync(o).filter(r=>r.endsWith(".json")).map(r=>{let i=join$1(o,r);try{return {cacheFile:i,envelope:xi(JSON.parse(readFileSync(i,"utf8")),r)}}catch{return null}})).filter(o=>o!==null).sort((o,r)=>o.envelope.timestamp-r.envelope.timestamp||Mn(o.envelope.operation)-Mn(r.envelope.operation));for(let{cacheFile:o,envelope:r}of n)try{let i=this.getDatabase();i.insertTelemetryFailure({id:r.id,operation:r.operation,payload:r.payload,error:r.failure,createdAt:r.timestamp}),this.applyOperation(r.operation,r.payload),i.resolveTelemetryFailure(r.id),unlinkSync(o);}catch{}this.database?.aggregatePendingToolMetrics();}aggregateMetrics(){return this.getDatabase().aggregatePendingToolMetrics()}async flushAndAggregate(){await this.flushCache(),this.aggregateMetrics();}close(){this.ownsDatabase&&this.database?.close(),this.database=null;}getDatabase(){return this.database??=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:this.busyTimeoutMs}),this.database}commitOrCache(t,n){try{return this.applyOperation(t,n),!0}catch(o){return this.cacheOperation(t,n,o),false}}applyOperation(t,n){let o=this.getDatabase();switch(t){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:On(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(On(n.sessionId),{status:"completed",finishedAt:n.finishedAt});return}}ensureParentSession(t,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";t.ensureSession({id:o,projectRoot:r,label:r==="unknown"?void 0:r.split("/").pop(),startedAt:Number(n.startedAt??n.timestamp??Date.now())});}cacheOperation(t,n,o){let r=Date.now(),i={id:`failure:${r}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:n,failure:o instanceof Error?o.message:String(o),timestamp:r};try{let s=this.getDatabase();s.insertTelemetryFailure({id:i.id,operation:t,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.trimCompatibilityCache(),this.scheduleRetry();}catch{}}trimCompatibilityCache(){try{let t=readdirSync(this.cacheDir).filter(n=>n.endsWith(".json")).sort();for(let n of t.slice(0,Math.max(0,t.length-De)))unlinkSync(join$1(this.cacheDir,n));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},Si).unref());}scheduleMetricAggregation(){if(this.metricAggregationScheduled||process.env.DEVFLOW_HOOK_DEGRADED==="1")return;this.metricAggregationScheduled=true,setTimeout(()=>{this.metricAggregationScheduled=false;try{this.getDatabase().aggregatePendingToolMetrics(50)===50&&this.scheduleMetricAggregation();}catch{}},25).unref();}postHttp(t,n){G(t,n,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let n=JSON.stringify(t);return n===void 0||n.length<=Dn?t:{_truncated:true,_original_size:n.length,_preview:`${n.substring(0,Dn)}...`}}};function Mn(e){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(e)}function On(e){return `hook-run:${e}`}function xi(e,t){if(!e||typeof e!="object")throw new Error("Invalid telemetry cache envelope");let n=e;if(typeof n.operation=="string"&&n.payload!==void 0)return n;let o=n.type==="tool_call"?"tool_call":n.type==="execution_start"?"execution_start":null;if(!o)throw new Error("Unknown legacy telemetry cache operation");let r=n.payload??{},i=Number(r.timestamp??r.startedAt??Date.now());return {id:`legacy-cache:${t}`,operation:o,payload:r,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:i}}function Me(e){return e??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function O(e){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(Me(e))}var Mi=2,Oi=1;function Pi(){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 Pn(e=Pi()){let t=[join$1(e,"dist","command-registry.json"),join$1(e,"command-registry.json")];for(let n of t)try{if(!existsSync$1(n))continue;let o=JSON.parse(readFileSync(n,"utf8"));if(o.version!==Mi&&o.version!==Oi||!ji(o.commands)){emitSemanticControlLog({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){emitSemanticControlLog({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 ji(e){return !e||typeof e!="object"||Array.isArray(e)?false:Object.values(e).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return false;let n=t;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||Fi(n.hostTools))&&(n.evidenceMode===void 0||["static","runtime","mixed"].includes(n.evidenceMode))})}function Fi(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&Object.entries(e).every(([t,n])=>t.length>0&&Oe(n))}function Oe(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0)}function jn(e){let t=Pn();return t?t[e]?.mcpTools??[]:[]}function Fn(e,t,n){return formatSkillRuntimeOverlay(createSkillRuntimeOverlay(e,t,{prompt:n}))}var pt=join$1(homedir$1(),".devflow"),ft=join$1(pt,"server-refs.json"),Gi=600*1e3,Ki=500;function Vi(){existsSync$1(pt)||mkdirSync(pt,{recursive:true});}function Pe(){try{if(existsSync$1(ft))return JSON.parse(readFileSync(ft,"utf-8"))}catch{}return {sessions:[],lastActivity:0}}function $n(e){Vi(),writeFileSync(ft,JSON.stringify(e));}var Fe=class{constructor(t){this.process=null;this.idleTimer=null;this.onShutdown=null;this.ownerToken=null;this.projectRoot=t;}setOnShutdown(t){this.onShutdown=t;}addRef(t){let n=Pe();n.sessions.includes(t)||n.sessions.push(t),n.lastActivity=Date.now(),$n(n),this.resetIdleTimer();}removeRef(t){let n=Pe();n.sessions=n.sessions.filter(o=>o!==t),n.lastActivity=Date.now(),$n(n),n.sessions.length===0&&this.resetIdleTimer();}get activeSessions(){return Pe().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 t=readRuntimeEndpointState();t&&t.ownerToken===this.ownerToken&&updateRuntimeEndpointStatus("stopped");}}async startServer(){let t=Yi(this.projectRoot);this.ownerToken=randomUUID$1();let n=resolveRuntimeEndpoint();this.process=spawn(process.execPath,[t,"--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 t=Date.now()+3e4;for(;Date.now()<t;){if(await this.healthCheck())return true;await new Promise(n=>setTimeout(n,Ki));}return false}healthCheck(){return new Promise(t=>{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(),t(s);});r.on("error",()=>t(false)),r.on("timeout",()=>{r.destroy(),t(false);}),r.end();})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),!(Pe().sessions.length>0)&&(this.idleTimer=setTimeout(()=>{this.stop();},Gi).unref());}};function Yi(e){let t=createRequire(import.meta.url),n=[()=>t.resolve("@devflow-tools/server/dist/main.js"),()=>join$1(e,"node_modules","@devflow-tools","server","dist","main.js"),()=>join$1(e,"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 $e(e){if(!e||typeof e!="object"||Array.isArray(e))return {};let t=e,n={};for(let o of ["lastMcpCall","bypassCount"])if(o in t){let r=t[o];if(r==null)continue;n[o]=typeof r=="number"&&Number.isFinite(r)&&r>=0?r:0;}return n}function Zi(e,t){return e.lastMcpCall===t.lastMcpCall&&e.bypassCount===t.bypassCount}function es(e){try{return existsSync$1(e)?$e(JSON.parse(readFileSync(e,"utf-8"))):{}}catch{return {}}}function ts(e,t,n){let o=n instanceof Error?n.message:String(n);emitSemanticControlLog({event:"hook.runtime.degraded",identity:{projectRoot:e},level:"warn",timestamp:Date.now(),data:{stage:"enforcement_receipt",operation:t,reason:o,fallback:"fail_open"}});}function Hn(e){let t=O(e);for(let n of ["receipt.json","receipt-lock.sqlite","receipt-lock.sqlite-shm","receipt-lock.sqlite-wal"])try{existsSync$1(join$1(t,n))&&unlinkSync(join$1(t,n));}catch{}}function ns(e,t){if(e.getHookReceipt(t)){Hn(t);return}let n=join$1(O(t),"receipt.json");if(!existsSync$1(n))return;let o=es(n);e.updateHookReceipt(t,()=>o),Hn(t);}function Ln(e,t,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),ns(o,e);let r={},i=o.updateHookReceipt(e,a=>(r=$e(a),$e(t(r)))),s=$e(i);return {receipt:s,applied:!0,changed:!Zi(r,s)}}catch(r){return ts(e,n,r),{receipt:{},applied:false,changed:false}}finally{try{o?.close();}catch{}}}function He(e,t){return Ln(e,()=>t,"write").applied}function vt(e,t){return Ln(e,t,"update")}var Nn={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},os=new Set(["Write","Edit","NotebookEdit"]),rs=new Set(["failed","timeout","unavailable"]);function is(e){switch(e){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var te=class{constructor(t,n,o){this.projectRoot=t;this.sessionId=n;this.executionId=o;}getPhase(){if(!this.sessionId||!this.executionId)return "idle";let t;try{t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let n=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(n&&n.expiresAt>Date.now())return "context_ready";n&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId);}catch{}finally{try{t?.close();}catch{}}return "context_gathering"}getContextReceipt(){if(!this.sessionId||!this.executionId)return null;let t;try{t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let n=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);return n&&n.expiresAt>Date.now()?n:(n&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId),null)}catch{return null}finally{try{t?.close();}catch{}}}evaluate(t,n){let o=this.getPhase();if(n||t==="Skill")return {permissionDecision:"allow"};if(o==="context_gathering"&&Nn[t])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_REQUIRED",reason:`DevFlow context required. Call mcp__devflow__get_project_context, then retry ${t}.`};if(o==="context_ready"){if(os.has(t)){let c=this.evaluateRequiredAction();if(c)return c}return {permissionDecision:"allow"}}let r=Nn[t];if(!r)return {permissionDecision:"allow"};let i=vt(this.projectRoot,c=>({...c,bypassCount:(c.bypassCount??0)+1}));if(!i.applied)return {permissionDecision:"allow"};let s=i.receipt.bypassCount??0,a=is(t);return s>=a?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \u6B21\u76F4\u63A5\u4F7F\u7528 ${t}\uFF0C\u5EFA\u8BAE\u7528 mcp__devflow__${r} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){He(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}recordDomainActionOutcome(t,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!==t)return !1;let a=Date.now(),c=r?.trim()?`${r.trim()}:${n}`:`${t}:${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:t,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 t=this.getContextReceipt(),n=t?.canonicalAction;if(!t||!n||!n.required||n.status!=="required")return null;let o=n.binding;if(o.requiredContextReceipt!==t.contextHash||o.projectRoot!==this.projectRoot||o.sessionId!==this.sessionId||o.requestId!==t.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(t.actionSatisfiedAt)return null;if(t.actionDegradation?.authorizedByContextReceipt===t.contextHash)return {permissionDecision:"allow",additionalContext:`DevFlow degraded fallback authorized by context receipt ${t.contextHash}: ${t.actionDegradation.reason}`};let r=(t.actionAttempts??[]).filter(i=>i.tool===n.tool&&rs.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:t.contextHash,authorizedAt:Date.now()};return this.persistDegradation(t,s),{permissionDecision:"allow",additionalContext:`DevFlow canonical tool mcp__devflow__${n.tool} ${i.status}; degraded direct write authorized by context receipt ${t.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 ${t.contextHash}, then retry the write. Direct fallback is allowed only after unavailable, failed, or timeout evidence.`}}persistDegradation(t,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let r=o.getContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!r||r.contextHash!==t.contextHash||r.actionDegradation)return;o.upsertContextReceipt({...r,actionDegradation:n});let i=o.getSkillExecution(t.executionId);if(!i)return;let s=i.metadata&&typeof i.metadata=="object"?i.metadata:{},a=Array.isArray(s.requiredActionDegradations)?s.requiredActionDegradations:[];o.updateSkillExecution(t.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 us=10,ms=5e3,ps=3e4,fs=new Int32Array(new SharedArrayBuffer(4)),Jn=0;function gs(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.rootPath=="string"&&t.rootPath.length>0&&typeof t.projectHash=="string"&&t.projectHash.length>0&&typeof t.pid=="number"&&Number.isInteger(t.pid)&&t.pid>0&&typeof t.startedAt=="number"&&Number.isFinite(t.startedAt)&&t.startedAt>=0}function Gn(e){if(!existsSync(e))return {entries:[],needsRepair:false};try{let t=JSON.parse(readFileSync$1(e,"utf8"));if(!Array.isArray(t))return {entries:[],needsRepair:!0};let n=t.filter(gs);return {entries:n,needsRepair:n.length!==t.length}}catch{return {entries:[],needsRepair:true}}}function Kn(e,t){mkdirSync$1(dirname$1(e),{recursive:true});let n=`${e}.${process.pid}.${Date.now()}.${Jn++}.tmp`,o;try{o=openSync$1(n,"wx"),writeFileSync$1(o,JSON.stringify(t,null,2)),closeSync$1(o),o=void 0,renameSync(n,e);}finally{try{o!==void 0&&closeSync$1(o);}finally{rmSync$1(n,{force:true});}}}function Vn(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function Yn(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.pid=="number"&&Number.isInteger(t.pid)&&t.pid>0&&typeof t.createdAt=="number"&&Number.isFinite(t.createdAt)&&typeof t.token=="string"&&t.token.length>0}function Wn(e,t){try{return readFileSync$1(e,"utf8")!==t?!1:(rmSync$1(e),!0)}catch(n){return n.code==="ENOENT"}}function hs(e){try{let t=readFileSync$1(e,"utf8"),n;try{let r=JSON.parse(t);Yn(r)&&(n=r);}catch{}return n?Vn(n.pid)?!1:Wn(e,t):Date.now()-statSync(e).mtimeMs>ps&&Wn(e,t)}catch(t){return t.code==="ENOENT"}}function ys(e){mkdirSync$1(dirname$1(e),{recursive:true});let t=`${e}.lock`,n=Date.now()+ms;for(;;){let o=`${process.pid}:${Date.now()}:${Jn++}`,r;try{return r=openSync$1(t,"wx"),writeFileSync$1(r,JSON.stringify({pid:process.pid,createdAt:Date.now(),token:o})),closeSync$1(r),r=void 0,{path:t,token:o}}catch(i){if(r!==void 0)try{closeSync$1(r);}finally{rmSync$1(t,{force:true});}if(i.code!=="EEXIST")throw i}if(!hs(t)){if(Date.now()>=n)throw new Error(`Timed out acquiring daemon registry lock: ${t}`);Atomics.wait(fs,0,0,us);}}}function vs(e){try{let t=readFileSync$1(e.path,"utf8"),n=JSON.parse(t);Yn(n)&&n.token===e.token&&rmSync$1(e.path);}catch(t){if(t.code!=="ENOENT")throw t}}function Qn(e){let t=getDaemonRegistryPath(),n=ys(t);try{return e(t)}finally{vs(n);}}function Xn(e,t){Qn(n=>{let o=Gn(n).entries.filter(r=>r.rootPath!==e&&Vn(r.pid));o.push({rootPath:e,projectHash:getProjectHash(e),pid:t,startedAt:Date.now()}),Kn(n,o);});}function Zn(e,t){Qn(n=>{let o=Gn(n).entries.filter(r=>r.rootPath!==e||t!==void 0&&r.pid!==t);Kn(n,o);});}async function he(e){let t=!e.memory,n=e.memory??new MemoryGate(e.projectRoot),o=0,r=0;try{await n.forceWarmUp(),e.trigger==="session_end"&&(o=await n.releasePendingDistillLeases(e.sessionId)),r=n.getPendingEventCount(e.sessionId,e.trigger!=="session_end");}finally{t&&n.close();}let i=Date.now(),s=e.trigger==="session_end"&&e.sessionId?`distill:session_end:${createHash("sha256").update(`${e.projectRoot}\0${e.sessionId}`).digest("hex").slice(0,24)}`:`distill:${i}:${Math.random().toString(36).slice(2,10)}`,a={id:s,pendingEvents:r,releasedLeases:o,trigger:e.trigger,sessionId:e.sessionId,details:e.details};try{let c=openGlobalDevFlowDatabase();try{c.recordMemoryDistillCheckpoint({id:s,projectRoot:e.projectRoot,sessionId:e.sessionId,trigger:e.trigger,pendingEvents:r,releasedLeases:o,details:e.details,createdAt:i}),c.insertEvent({kind:"memory_distill_requested",timestamp:i,success:!0,metadata:{...a,projectRoot:e.projectRoot}});}finally{c.close();}}catch(c){if(e.strictPersistence)throw c}return a}function eo(e){if(e.pendingEvents===0)return "";let t=e.sessionId?`\uFF0CsessionId=${e.sessionId}`:"";return `Memory distill checkpoint: ${e.pendingEvents} \u4E2A\u4E8B\u4EF6\u5F85\u63D0\u70BC${t}\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 ro(e){return Buffer.from(e,"utf8").toString("base64url")}function Ss(e,t,n){let o=t?.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 `${e}:${r}`}return `${e}:legacy-${n}-${randomUUID().slice(0,8)}`}function uo(e){return `${e}:legacy-journal`}var L=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(O(t),"hook-sessions");}registerSession(t){let n=t.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(t,n,o){let r=this.registerSession(t);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(t,n){let o=this.registerSession(t);return o.activeTurnId=n.turnId,o.activeRequestId=n.requestId,o.intentArtifactHash=n.intentArtifactHash,o.lastActivityAt=Date.now(),this.persist(o),o}get(t){let n=t.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=io(i.evidenceObligations),i.evidenceDegradations=so(i.evidenceDegradations),i.evidenceOutcomes=ao(i.evidenceOutcomes),this.replayEvidenceJournal(i),this.sessions.set(n,i),i)}catch{return null}}completeExecution(t){let n=this.get(t);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(t,n,o=Date.now(),r){let i=this.registerSession(t),a=(r?void 0:i.evidenceObligations.find(d=>d.contractId===n.id))?.obligationId??Ss(n.id,r,o);this.appendEvidenceEvent(t,{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(t){return (this.get(t)?.evidenceObligations??[]).map(n=>structuredClone(n))}markEvidenceCorrection(t,n,o,r,i=Date.now()){let s=this.get(t),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(t,{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(t,n){let o=this.get(t);if(!o)return false;let r=o.evidenceObligations.find(s=>s.obligationId===n);if(!r)return false;let i=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:n,contractId:r.contractId,at:i},`resolve\0${n}`),this.replayEvidenceJournal(o),o.lastActivityAt=i,this.persist(o),true}resolveDegradedEvidence(t,n){let o=this.get(t),r=o?.evidenceDegradations.find(s=>s.obligationId===n);if(!o||!r)return false;let i=Date.now();return this.appendEvidenceEvent(t,{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(t,n,o,r=Date.now()){let i=this.get(t),s=i?.evidenceObligations.find(c=>c.obligationId===n);if(!i||!s)return false;let a=o.slice(0,240);return this.appendEvidenceEvent(t,{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(t){let n=t.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(t){return join$1(this.sessionsDir,`${ro(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",ro(t))}appendEvidenceEvent(t,n,o){let r=this.evidenceJournalDir(t);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(t){t.evidenceObligations=io(t.evidenceObligations),t.evidenceDegradations=so(t.evidenceDegradations),t.evidenceOutcomes=ao(t.evidenceOutcomes);let n=this.evidenceJournalDir(t.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=xs(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||co(i.kind)-co(s.kind));for(let i of r)this.applyEvidenceEvent(t,i);t.evidenceObligations=t.evidenceObligations.slice(-8),t.evidenceDegradations=t.evidenceDegradations.slice(-20),t.evidenceOutcomes=t.evidenceOutcomes.slice(-20);}applyEvidenceEvent(t,n){let o=t.evidenceOutcomes.find(s=>s.obligationId===n.obligationId);if(n.kind==="add"){if(o)return;let s=t.evidenceObligations.find(a=>a.obligationId===n.obligationId);s?(s.contract=n.contract,s.promptedAt=Math.min(s.promptedAt,n.at)):t.evidenceObligations.push({obligationId:n.obligationId,contractId:n.contractId,contract:n.contract,promptedAt:n.at,attempt:0,correctionRequested:false,violations:[]});return}let r=t.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")t.evidenceOutcomes=t.evidenceOutcomes.filter(s=>s.obligationId!==n.obligationId),t.evidenceDegradations=t.evidenceDegradations.filter(s=>s.obligationId!==n.obligationId);else if(o)return;n.kind==="degrade"?(t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==n.obligationId),t.evidenceDegradations.push({obligationId:n.obligationId,contractId:n.contractId,reason:n.reason,degradedAt:n.at,attempt:i,contract:r?.contract})):t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==n.obligationId),t.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(t){mkdirSync(this.sessionsDir,{recursive:true,mode:448});let n=this.snapshotPath(t.sessionId),o=`${n}.${process.pid}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(t),{mode:384}),renameSync$1(o,n);}};function io(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object")return [];let n=t;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)||!mo(n.contract))return [];let o=typeof n.obligationId=="string"&&n.obligationId.length>0&&n.obligationId.length<=384?n.obligationId:uo(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 so(e){return Array.isArray(e)?e.filter(t=>{if(!t||typeof t!="object")return false;let n=t;return typeof n.obligationId=="string"&&typeof n.contractId=="string"&&typeof n.reason=="string"&&typeof n.degradedAt=="number"&&typeof n.attempt=="number"}).slice(-20):[]}function ao(e){return Array.isArray(e)?e.filter(t=>{if(!t||typeof t!="object")return false;let n=t;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 xs(e){if(!e||typeof e!="object")return null;let t=e,n=t.kind;if(n!=="add"&&n!=="correction"&&n!=="resolve"&&n!=="degrade"||typeof t.contractId!="string"||t.contractId.length>128||typeof t.at!="number")return null;let r={obligationId:typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:uo(t.contractId),contractId:t.contractId,at:t.at};if(n==="add")return mo(t.contract)?{kind:n,...r,contract:t.contract}:null;if(n==="correction"){let i=typeof t.fingerprint=="string"?t.fingerprint:t.transcriptHash;return typeof i=="string"&&/^[a-f0-9]{64}$/.test(i)&&Array.isArray(t.violations)&&t.violations.every(s=>typeof s=="string"&&s.length<=240)?{kind:n,...r,fingerprint:i,violations:t.violations}:null}return n==="resolve"?{kind:n,...r}:typeof t.reason=="string"&&t.reason.length<=240?{kind:n,...r,reason:t.reason}:null}function co(e){return e==="add"?0:e==="correction"?1:2}function mo(e){if(!e||typeof e!="object")return false;let t=e,n=t.requiredSections,o=t.prohibitedClaims;return t.version==="1.0"&&typeof t.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(t.id)&&typeof t.runtimeProfilingOccurred=="boolean"&&typeof t.samplingEvidenceOccurred=="boolean"&&Array.isArray(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 t.canonicalReport=="string"&&Buffer.byteLength(t.canonicalReport,"utf8")<=48*1024&&!!t.correctionPolicy&&t.correctionPolicy.maxAttempts===1&&t.correctionPolicy.repeatedViolation==="fail_open"}function go(e,t){let n=_o(e);mkdirSync$1(n,{recursive:true,mode:448});let o=join(n,`${t.receiptId}.json`);if(existsSync(o))return t.receiptId;let r=`${o}.${process.pid}.tmp`;writeFileSync$1(r,JSON.stringify(t),{mode:384});try{renameSync(r,o);}catch(i){try{unlinkSync$1(r);}catch{}if(!existsSync(o))throw i}return t.receiptId}function ho(e){let t=_o(e);mkdirSync$1(t,{recursive:true,mode:448});let n=readdirSync$1(t).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(t,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 yo(e){unlinkSync$1(e.path);}function vo(e){try{renameSync(e.path,e.path.replace(/\.claim-\d+$/u,""));}catch{}}function _o(e){return join(O(e),"session-finalize-pending")}function D(e){let t=Ps(e.projectRoot),n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let o=js(n,{...e,projectRoot:t});return o?appendTaskRuntimeBoundary({projectRoot:o.projectRoot,taskSpec:taskSpecFromImmutableIntent(Fs(o)),kind:e.kind,payload:e.payload,dedupeKey:e.dedupeKey,producer:e.producer,database:n})?.snapshot??null:null}catch(o){return emitSemanticControlLog({event:"task.runtime.shadow_mismatch",identity:{projectRoot:t,sessionId:e.sessionId,...e.turnId?{turnId:e.turnId}:{},...e.requestId?{requestId:e.requestId}:{}},level:"warn",timestamp:Date.now(),data:{stage:e.kind,reason:Ns(o),authority:"legacy"}}),null}finally{n.close();}}function Ps(e){try{return realpathSync(e)}catch{return e}}function wo(e){if(!$s(e.legacyState))return;let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100});try{let n=t.getTaskRuntimeSnapshot(e.artifact.projectRoot,e.artifact.sessionId,e.artifact.turnId);if(!n)return;let o=Hs(e.legacyState);if(n.terminal===o)return;emitSemanticControlLog({event:"task.runtime.shadow_mismatch",identity:ko(e.artifact),level:"warn",timestamp:Date.now(),data:{stage:"terminal_projection",legacyState:e.legacyState,shadowTerminal:n.terminal,expectedTerminal:o,authority:"legacy"}});}catch{}finally{t.close();}}function js(e,t){return e.listLatestTaskIntentArtifacts(t.projectRoot,t.sessionId).find(n=>t.turnId?n.turnId===t.turnId:t.requestId?n.requestId===t.requestId:true)}function Fs(e){return {identity:ko(e),version:e.version,...e.supersedesHash?{supersedesHash:e.supersedesHash}:{},rawPrompt:e.rawPrompt,normalizedPrompt:e.normalizedPrompt,...e.command?{command:e.command}:{},slashArgs:e.slashArgs,...e.activeSkill?{activeSkill:e.activeSkill}:{},intent:e.intent,action:e.action,entities:e.entities,targetAnchors:e.targetAnchors,policyConstraints:e.policyConstraints,classificationEvidence:e.classificationEvidence,sourceEventIds:e.sourceEventIds,sourceHash:e.sourceHash,artifactHash:e.artifactHash,createdAt:e.createdAt}}function ko(e){return {projectRoot:e.projectRoot,projectId:e.projectId,hostId:e.hostId,sessionId:e.sessionId,turnId:e.turnId,requestId:e.requestId,...e.executionId?{executionId:e.executionId}:{}}}function $s(e){return e==="action_failed"||e==="closed"||e==="closed_with_degradation"||e==="closed_with_retry_work"}function Hs(e){return e==="closed"?"completed":e==="closed_with_degradation"?"completed_with_degradation":e==="closed_with_retry_work"?"retry_pending":"failed"}function Ns(e){return e instanceof Error?e.message:String(e)}var Js=256*1024,Gs=48*1024,Ks=512*1024,Vs=500,Ys=5,ye=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function Qs(e){return e==="react_audit_performance"||e.endsWith("__react_audit_performance")}function Xs(e){let t=ve(e,0,new Set);return t?da(t.contract,t.canonicalReport):null}function So(e){if(!e.sessionId||!Qs(e.toolName))return null;let t=Xs(e.toolResponse);if(!t)return null;let n=Date.now(),o=e.runtimeStore.addEvidenceObligation(e.sessionId,t,n,e.toolUseId),r=e.runtimeStore.get(e.sessionId);if(o&&r){let i=openGlobalDevFlowDatabase();try{i.upsertSessionObligation({obligationId:`evidence:${o.obligationId}`,projectRoot:r.projectRoot,sessionId:e.sessionId,executionId:r.executionId,kind:"evidence_contract",state:"open",payload:{contract:t,runtimeObligationId:o.obligationId},createdAt:n,updatedAt:n});}finally{i.close();}emitSemanticControlLog({event:"verification.completed",identity:{projectRoot:r.projectRoot,sessionId:e.sessionId,executionId:r.executionId},level:"info",timestamp:n,data:{stage:"performance_detector_coverage",status:"obligation_opened",contractId:t.id,obligationId:o.obligationId,detectorCoverage:Be(e.toolResponse),runtimeProfilingOccurred:t.runtimeProfilingOccurred,samplingEvidenceOccurred:t.samplingEvidenceOccurred,toolUseId:e.toolUseId}});}return Zs(t)}function Zs(e){return [`DevFlow performance evidence contract ${e.id} is active.`,`The final performance answer MUST contain these three sections exactly: ${e.requiredSections.join(" / ")}.`,e.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=${e.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.",e.canonicalReport].join(`
3
3
 
4
- `)}function xo(e){let t=e.runtimeStore??new L(e.projectRoot),n=t.listEvidenceObligations(e.sessionId);if(n.length===0)return Xs(e,t),null;let o=Rt(e.transcriptPath,n);if(!o.answer){let s=o.degradationReason??"transcript_answer_unavailable";for(let a of n)t.degradeEvidenceObligation(e.sessionId,a.obligationId,s);return null}let r=o.fingerprint;if(!r){for(let s of n)t.degradeEvidenceObligation(e.sessionId,s.obligationId,"transcript_identity_unavailable");return null}let i=[];for(let s of n){let a=Eo(o.answer,[s]);if(a.length===0){t.resolveEvidenceObligation(e.sessionId,s.obligationId),ze(e,s,"satisfied",r);continue}if(!s.correctionFingerprint){t.markEvidenceCorrection(e.sessionId,s.obligationId,a,r),i.push({obligation:s,violations:a}),ze(e,s,"correction_requested",r,a);continue}if(s.correctionFingerprint===r){i.push({obligation:s,violations:a});continue}t.degradeEvidenceObligation(e.sessionId,s.obligationId,"evidence_contract_unresolved"),ze(e,s,"degraded",r,a);}return i.length===0?null:Zs(i)}function Xs(e,t){let n=(t.get(e.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=Rt(e.transcriptPath,o);if(!(!r.answer||!r.fingerprint))for(let i of o)Eo(r.answer,[i]).length>0||t.resolveDegradedEvidence(e.sessionId,i.obligationId)&&ze(e,i,"satisfied",r.fingerprint);}function ze(e,t,n,o,r=[]){n!=="correction_requested"&&C({projectRoot:e.projectRoot,sessionId:e.sessionId,kind:n==="satisfied"?"verification.succeeded":"verification.failed",payload:{receiptId:t.obligationId,reasonCode:n==="satisfied"?"performance_evidence_satisfied":"performance_evidence_unresolved"},dedupeKey:`${t.obligationId}:${n}:${t.attempt}`,producer:"devflow-evidence-contract"}),emitSemanticControlLog({event:"verification.completed",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId},level:n==="satisfied"?"info":n==="degraded"?"error":"warn",timestamp:Date.now(),data:{stage:"performance_evidence_transition",status:n,contractId:t.contractId,obligationId:t.obligationId,attempt:t.attempt,answerFingerprint:o,violations:r,supersedesDegradation:n==="satisfied"&&t.attempt>0}});}function Be(e,t=0){if(t>6||e==null)return [];if(typeof e=="string")try{return Be(JSON.parse(e),t+1)}catch{return []}if(Array.isArray(e)){for(let o of e){let r=Be(o,t+1);if(r.length>0)return r}return []}if(typeof e!="object")return [];let n=e;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=Be(o,t+1);if(r.length>0)return r}return []}function Zs(e){let t=[...new Set(e.flatMap(o=>o.violations))],n=[...new Map(e.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: ${t.join("; ")}`,"Use this canonical report (you may add clearly labeled hypotheses or runtime verification steps, but no unsupported measured claims):",n.join(`
4
+ `)}function xo(e){let t=e.runtimeStore??new L(e.projectRoot),n=t.listEvidenceObligations(e.sessionId);if(n.length===0)return ea(e,t),null;let o=Rt(e.transcriptPath,n);if(!o.answer){let s=o.degradationReason??"transcript_answer_unavailable";for(let a of n)t.degradeEvidenceObligation(e.sessionId,a.obligationId,s);return null}let r=o.fingerprint;if(!r){for(let s of n)t.degradeEvidenceObligation(e.sessionId,s.obligationId,"transcript_identity_unavailable");return null}let i=[];for(let s of n){let a=Eo(o.answer,[s]);if(a.length===0){t.resolveEvidenceObligation(e.sessionId,s.obligationId),ze(e,s,"satisfied",r);continue}if(!s.correctionFingerprint){t.markEvidenceCorrection(e.sessionId,s.obligationId,a,r),i.push({obligation:s,violations:a}),ze(e,s,"correction_requested",r,a);continue}if(s.correctionFingerprint===r){i.push({obligation:s,violations:a});continue}t.degradeEvidenceObligation(e.sessionId,s.obligationId,"evidence_contract_unresolved"),ze(e,s,"degraded",r,a);}return i.length===0?null:ta(i)}function ea(e,t){let n=(t.get(e.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=Rt(e.transcriptPath,o);if(!(!r.answer||!r.fingerprint))for(let i of o)Eo(r.answer,[i]).length>0||t.resolveDegradedEvidence(e.sessionId,i.obligationId)&&ze(e,i,"satisfied",r.fingerprint);}function ze(e,t,n,o,r=[]){n!=="correction_requested"&&D({projectRoot:e.projectRoot,sessionId:e.sessionId,kind:n==="satisfied"?"verification.succeeded":"verification.failed",payload:{receiptId:t.obligationId,reasonCode:n==="satisfied"?"performance_evidence_satisfied":"performance_evidence_unresolved"},dedupeKey:`${t.obligationId}:${n}:${t.attempt}`,producer:"devflow-evidence-contract"}),emitSemanticControlLog({event:"verification.completed",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId},level:n==="satisfied"?"info":n==="degraded"?"error":"warn",timestamp:Date.now(),data:{stage:"performance_evidence_transition",status:n,contractId:t.contractId,obligationId:t.obligationId,attempt:t.attempt,answerFingerprint:o,violations:r,supersedesDegradation:n==="satisfied"&&t.attempt>0}});}function Be(e,t=0){if(t>6||e==null)return [];if(typeof e=="string")try{return Be(JSON.parse(e),t+1)}catch{return []}if(Array.isArray(e)){for(let o of e){let r=Be(o,t+1);if(r.length>0)return r}return []}if(typeof e!="object")return [];let n=e;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=Be(o,t+1);if(r.length>0)return r}return []}function ta(e){let t=[...new Set(e.flatMap(o=>o.violations))],n=[...new Map(e.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: ${t.join("; ")}`,"Use this canonical report (you may add clearly labeled hypotheses or runtime verification steps, but no unsupported measured claims):",n.join(`
5
5
 
6
6
  ---
7
7
 
8
8
  `)].join(`
9
9
 
10
- `)}}function Eo(e,t){let n=new Set,o=new Set(t.flatMap(c=>c.contract.requiredSections)),r=To(e.split(/\r?\n/)),i=Ao(r.headingLines);for(let c of o)i.found.has(c)||n.add(`missing_section:${c}`);if(t.every(c=>c.contract.runtimeProfilingOccurred))return [...n];let a=t.every(c=>c.contract.samplingEvidenceOccurred);for(let c=0;c<r.claimLines.length;c++){let d=r.claimLines[c].trim();if(!d||ta(d))continue;let l=i.byLine.get(c);for(let u of sa(d))oa(u,l,a,n);}return [...n]}function To(e){let t=false,n=[],o=[];for(let r of e){if(/^\s*```/.test(r)){t=!t,n.push(""),o.push(r.replace(/^\s*```+[^\s`]*/,"").replace(/```+\s*$/,"").trim());continue}n.push(t?"":r.replace(/`[^`]*`/g,"").trim()),o.push(r.replace(/`([^`]*)`/g,(i,s)=>ea(s)?"":s).trim());}return {headingLines:n,claimLines:o}}function ea(e){let t=e.trim().slice(0,256);return !t||/\s/.test(t)||e.trim().length>256?false:/^[A-Za-z_$][\w$.-]*$/.test(t)||/^(['"])[^'"`]*\1$/.test(t)}function ta(e){if(e.length>2048)return false;let t=e.replace(/^\s*(?:[-*+]|\d+[.)])\s+/,"").trim();return t?na(t)||/^(?:\/\/|\/\*|\*\/|\*\s|#!)/.test(t)||/^(?:import|export|const|let|var|function|class|type|interface|enum|namespace|declare)\b/.test(t)||/^(?:async\s+)?(?:function\s+)?[A-Za-z_$][\w$]*\s*=\s*/.test(t)||/^[A-Za-z_$][\w$.[\]'"-]*\s*(?:=|\+=|-=|\*=|\/=|\?\?=|&&=|\|\|=)\s*/.test(t)||/^[A-Za-z_$'"-][\w$.'"-]*\s*:\s*[^:]+[,}]?$/.test(t)||/=>/.test(t)||/^(?:await\s+|return\s+|throw\s+|new\s+)?[A-Za-z_$][\w$.]*\s*\([^)]*\)\s*;?$/.test(t)||/^(['"])[\s\S]*\1[;,]?$/.test(t)?true:/[{}()[\]=<>]\s*;?$/.test(t)&&/(?:;|=>|\b(?:return|new|await)\b)/.test(t):false}function na(e){if(e.length>1024)return false;let t="(?:--[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(`^${t}\\s*:\\s*\\S[^;]{0,960};$`,"i").test(e)}function oa(e,t,n,o){let r=/\bP0\b/gi;for(let f of e.matchAll(r))Ro(e,f.index??0,f[0],"p0")||o.add("unsupported_p0_severity");let i=/(?:中高|高)(?:风险|优先级)|严重(?:问题|风险)|\bhigh[- ](?:risk|severity|priority)\b/gi;for(let f of e.matchAll(i))Ro(e,f.index??0,f[0],"high")||o.add("unsupported_high_severity");let s=/(?:性能)?瓶颈|卡顿|掉帧|CPU\s*(?:热点|尖峰)|\bbottleneck\b|\bjank\b|\bdropped frames?\b|\bCPU hotspot\b/gi;for(let f of e.matchAll(s))ia(e,f.index??0,f[0])||(/(?:瓶颈|bottleneck)/i.test(f[0])?o.add("unsupported_confirmed_bottleneck"):o.add("unsupported_runtime_effect"));let a=/\b\d{1,3}(?:\.\d+)?\s*%/.test(e),c=/(?:预计|预期|估计|提升|降低|减少|节省|改善|收益|加速|improve|reduce|faster|gain|benefit|speedup|expected|estimated)/i.test(e),d=/\b\d+(?:\.\d+)?\s*[x×]\b/i.test(e);(a||d)&&c&&o.add(a?"unsupported_benefit_percentage":"unsupported_performance_number");let l=/\b\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:ms|fps|hz)\b/i.test(e)||/\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:毫秒|次\s*\/\s*秒|帧)/.test(e),u=t==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&/(?:采集|记录|测量|收集|collect|measure|record)/i.test(e)&&!/(?:预计|预期|估计|约|大约|通常|平均|每(?:隔)?|达到|提升|降低|减少|节省|改善|improve|reduce|faster|expected|estimated|average|typically|every)/i.test(e);a&&!c&&!u&&o.add("unsupported_benefit_percentage"),l&&!u&&o.add("unsupported_performance_number");let p=/(?:requestAnimationFrame|\bRAF\b)/i.test(e),g=/(?:建议|应该|应当|使用|添加|采用|切换|包裹|优化|节流|\buse\b|\badopt\b|\brecommend\b|\bswitch\b|\bwrap\b|\bthrottl(?:e|ing)\b)/i.test(e),m=/(?:不要|不得|不能|不应|避免|不建议|不推荐).{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(e);p&&g&&!m&&!n&&o.add("raf_without_sampling_evidence");}function Ro(e,t,n,o){let r=e.slice(Math.max(0,t-64),t),i=e.slice(t+n.length,t+n.length+28),s=ra(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 ra(e){if(/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?|不是|并非|未被)\s*(?:任何|明确的)?\s*(?:(?:问题|发现|证据|项|内容)\s*)?(?:(?:属于|(?:被)?(?:评|判定|认定|标记|列|视|定|归(?:类)?)为)\s*)?$/i.test(e)||/\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(e))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(e)||o.test(e)}function ia(e,t,n){let o=e.slice(Math.max(0,t-40),t),r=e.slice(t+n.length,t+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 sa(e){return e.split(/(?:[。!?;;,,]|\b(?:but|however|yet|nevertheless|nonetheless)\b|但是|但|然而|却|不过|可是)/i).map(t=>t.trim()).filter(Boolean)}function _e(e,t,n){if(t>Ks||e===null||e===void 0)return null;if(typeof e=="string"){if(Buffer.byteLength(e,"utf8")>zs)return null;try{return _e(JSON.parse(e),t+1,n)}catch{return null}}if(typeof e!="object"||n.has(e))return null;if(n.add(e),Array.isArray(e)){for(let r of e.slice(0,16)){let i=_e(r,t+1,n);if(i)return i}return null}let o=e;if("evidenceContract"in o)return {contract:o.evidenceContract,canonicalReport:o.canonicalReport};for(let r of ["structuredContent","data","result"])if(r in o){let i=_e(o[r],t+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=_e(i,t+1,n);if(s)return s}return null}function aa(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;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!==ye.length)return null;let o=n.requiredSections.filter(c=>typeof c=="string");if(o.length!==ye.length||ye.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:t;return typeof a!="string"||Buffer.byteLength(a,"utf8")>Bs||ye.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 Rt(e,t){if(!e||e.length>4096)return {degradationReason:"transcript_path_missing"};let n;try{let o=lstatSync$1(e);if(!o.isFile()||o.isSymbolicLink())return {degradationReason:"transcript_path_unsafe"};n=openSync$1(e,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,Js),s=Buffer.alloc(i),a=0;for(;a<i;){let m=readSync(n,s,a,i-a,r.size-i+a);if(m===0)break;a+=m;}let c=s.subarray(0,a).toString("utf8");r.size>i&&(c=c.slice(Math.max(0,c.indexOf(`
11
- `)+1)));let d=c.split(/\r?\n/).slice(-Gs),l=t.length>0?Math.min(...t.map(m=>m.promptedAt)):0,u=da(d,l),g=[...u].reverse().find(m=>ca(m.text,t))??u.at(-1);return g?.text?{answer:g.text,fingerprint:g.fingerprint}:{degradationReason:"transcript_answer_unavailable"}}catch{return {degradationReason:"transcript_unreadable"}}finally{n!==void 0&&closeSync$1(n);}}function ca(e,t){let n=new Set(t.flatMap(r=>r.contract.requiredSections)),o=Ao(To(e.split(/\r?\n/u)).headingLines);return [...n].every(r=>o.found.has(r))}function Je(e){return Rt(e,[]).answer}function da(e,t){let n=[];for(let o=0;o<e.length;o++){let r=e[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=la(i.timestamp);if(c>0&&c+5e3<t)continue;let d=s.content,l=typeof d=="string"?d:Array.isArray(d)?d.filter(u=>u&&typeof u=="object"&&u.type==="text").map(u=>u.text).filter(u=>typeof u=="string").join(`
12
- `):"";if(l.trim()){let u=l.trim(),p=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")}`,g=createHash("sha256").update(u).digest("hex"),m=createHash("sha256").update(`${p}\0${g}`).digest("hex");n.push({text:u,timestamp:c,fingerprint:m});}}catch{continue}}return n}function la(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string")return 0;let t=Date.parse(e);return Number.isFinite(t)?t:0}function Ao(e){let t=new Set,n=new Map,o;for(let r=0;r<e.length;r++){let i=e[r].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=ye.find(a=>i===a);s&&(o=s,t.add(s)),n.set(r,o);}return {found:t,byLine:n}}function Oo(e){let t;try{if(ha(e.toolResponse))return null;t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let n=t.getActiveContextReceipt(e.projectRoot,e.sessionId,e.executionId);if(!n)return null;let o=ma(e.toolInput,e.toolResponse);if(o.length===0)return null;let r=e.toolName==="Read"?pa(e.toolInput):void 0,i=r?n.selectedFiles?.find(l=>fa(e.projectRoot,l,r)):void 0,s=ga(e.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 l=[n.contextHash,n.requestId??"",a,c,e.toolUseId??`${e.sessionId}:${e.executionId??n.executionId}`].join("\0");t.recordContextSelectionEvent({id:`ctxsel:${createHash("sha256").update(l).digest("hex").slice(0,32)}`,projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n.executionId,requestId:n.requestId,selectionType:a,candidateId:c,toolName:e.toolName,toolUseId:e.toolUseId,selectedAt:Date.now()});}let d=t.listRetrievalLedgerEvents({projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n.executionId,requestId:n.requestId}).filter(l=>l.stage==="selected"&&o.includes(l.sourceId));for(let l of d)t.appendRetrievalLedgerEvent({...l,id:xt(l.id,"consumed",e.toolUseId??e.toolName),stage:"consumed",toolEvidence:[e.toolUseId??e.toolName],evidenceIds:o,actor:e.toolName,reasonCode:"structural_evidence_ref",payload:{...l.payload,consumedByTool:e.toolName},createdAt:Date.now()});return d.length>0&&Et({event:"retrieval.attribution.transitioned",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n.executionId,requestId:n.requestId,contextReceipt:n.contextHash},level:"info",timestamp:Date.now(),data:{stage:"consumed",actor:e.toolName,consumedCount:d.length,evidenceRefCount:o.length}}),a}catch(n){return Et({event:"hook.runtime.degraded",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,requestId:e.requestId},level:"warn",timestamp:Date.now(),data:{stage:"retrieval_attribution",actor:e.toolName,reason:n instanceof Error?n.message:String(n)}}),null}finally{try{t?.close();}catch{}}}function Po(e){let t=openGlobalDevFlowDatabase();try{let n=t.listRetrievalLedgerEvents(e),o=new Map(n.filter(d=>d.stage==="selected").map(d=>[Co(d),d])),r=new Map(n.filter(d=>d.stage==="consumed").map(d=>[Co(d),d])),i=0,s=0,a=0;for(let[d,l]of o){let u=r.get(d);u&&e.verificationReceipt&&t.appendRetrievalLedgerEvent({...u,id:xt(u.id,"verified",e.verificationReceipt),stage:"verified",verificationReceipt:e.verificationReceipt,reasonCode:"same_task_verification_receipt",createdAt:e.finishedAt??Date.now()});let p=u&&e.verificationReceipt&&e.outcome!=="unknown"?e.outcome:"unknown",g=p==="positive"?"positive_outcome":p==="negative"?"negative_outcome":"unknown_outcome";t.appendRetrievalLedgerEvent({...l,id:xt(l.id,g,e.verificationReceipt??e.sessionId),stage:g,reason:u?e.outcomeReason:"selected_not_adopted",toolEvidence:u?.toolEvidence??[],verificationReceipt:p==="unknown"?void 0:e.verificationReceipt,payload:{...l.payload,adopted:!!u},createdAt:e.finishedAt??Date.now()}),g==="positive_outcome"?i+=1:g==="negative_outcome"?s+=1:a+=1;}let c={adopted:r.size,positive:i,negative:s,unknown:a,adoptedSources:[...r.values()].map(d=>({sourceType:d.sourceType,sourceId:d.sourceId}))};return Et({event:"retrieval.attribution.transitioned",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,requestId:e.requestId},level:a>0?"warn":"info",timestamp:e.finishedAt??Date.now(),data:{stage:"session_outcome",selectedCount:o.size,consumedCount:r.size,verifiedCount:e.verificationReceipt?r.size:0,positiveCount:i,negativeCount:s,unknownCount:a}}),c}finally{t.close();}}function ma(...e){let t=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()&&t.add(a.trim());else n(s,r+1);}};for(let o of e)n(o);return [...t]}function pa(e){for(let t of ["file_path","path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n.trim()}}function fa(e,t,n){let o=resolve(e,t),r=isAbsolute(n)?resolve(n):resolve(e,n);return o===r}function ga(e){return e.startsWith("mcp__")?e.split("__").at(-1)??e:e}function ha(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return t.ok===false||t.success===false||t.isError===true||!!t.error||["failed","rejected","unavailable"].includes(String(t.status??""))}function xt(e,t,n){return `retrieval:${createHash("sha256").update(`${e}\0${t}\0${n}`).digest("hex")}`}function Co(e){return [e.requestId,e.contextReceipt,e.sourceType,e.sourceId].join("\0")}function Et(e){try{emitSemanticControlLog(e);}catch{}}var Ra=8*1024*1024;function $o(e){if(!e.transcriptPath||!existsSync(e.transcriptPath))return {status:"unavailable",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:"transcript_path_unavailable"};let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=t.getLatestTranscriptCheckpoint({projectRoot:e.projectRoot,hostId:"claude-code",sessionId:e.sessionId,sourcePath:e.transcriptPath}),o=statSync(e.transcriptPath).size,r=Math.min(n?.byteOffset??0,o),i=Math.min(Ra,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(e.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=t.listLatestTaskIntentArtifacts(e.projectRoot,e.sessionId),l=new Map,u=new Set,p=0,g=0;for(let k of c){let I;try{I=JSON.parse(k);}catch{continue}for(let S of Tt(I,l)){let b=claudeCodeRuntimeAdapter.normalizeToolResult(S,{projectRoot:e.projectRoot});if(b.success||!b.error)continue;let $=b.toolUseId??b.sourceHash;if(u.has($))continue;u.add($),p++;let T=b.toolUseId?t.getToolCallEventByToolUseId(e.sessionId,b.toolUseId):null,D=Fo(T?.input,"_devflow_turn_id"),H=Fo(T?.input,"_devflow_request_id"),R=D?d.find(E=>E.turnId===D):[...d].reverse().find(E=>(!T?.executionId||E.executionId===T.executionId)&&E.createdAt<=(T?.timestamp??b.timestamp))??d.at(-1),A=`host-failure:${b.sourceHash}`;t.insertEvent({kind:"host_transcript_tool_failure",timestamp:b.timestamp,success:!1,toolName:b.canonicalName??b.requestedName,metadata:{projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:D??R?.turnId,requestId:H??R?.requestId,sourceId:A,toolUseId:b.toolUseId,correlatedEventId:T?.eventId,requestedName:b.requestedName,canonicalName:b.canonicalName,failureCategory:b.failureCategory,error:b.error.slice(0,1e3)}}),emitSemanticControlLog({event:"host.tool.result.reconciled",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:D??R?.turnId,requestId:H??R?.requestId,executionId:T?.executionId},level:"warn",timestamp:Date.now(),data:{toolUseId:b.toolUseId,toolName:b.canonicalName??b.requestedName,failureCategory:b.failureCategory,correlation:T?"tool_use_id":"timestamp_fallback"}}),g++;}}let m=createHash("sha256").update(s).digest("hex"),f=`transcript:${createHash("sha256").update(`${e.projectRoot}\0${e.sessionId}\0${e.transcriptPath}\0${r+i}\0${m}`).digest("hex").slice(0,24)}`;return t.appendTranscriptCheckpoint({id:f,projectRoot:e.projectRoot,hostId:"claude-code",sessionId:e.sessionId,sourcePath:e.transcriptPath,sourceHash:m,byteOffset:r+i,eventCount:c.length,createdAt:Date.now()}),emitSemanticControlLog({event:"session.reconciled",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId},level:p>0?"warn":"info",timestamp:Date.now(),data:{stage:"transcript",eventsRead:c.length,failuresFound:p,failuresRecorded:g,checkpointId:f}}),{status:"completed",eventsRead:c.length,failuresFound:p,failuresRecorded:g,checkpointId:f}}catch(n){return {status:"degraded",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:n instanceof Error?n.message:String(n)}}finally{t.close();}}function Fo(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function Tt(e,t,n=0){if(n>7||e===null||e===void 0)return [];if(Array.isArray(e))return e.flatMap(s=>Tt(s,t,n+1));if(typeof e!="object")return [];let o=e,r=typeof o.type=="string"?o.type:"";r==="tool_use"&&typeof o.id=="string"&&typeof o.name=="string"&&t.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?t.get(s)??"unknown":"unknown",tool_use_id:s,tool_response:o.content,is_error:o.is_error===true,...o.is_error===true?{error:At(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(...Tt(a,t,n+1));return i}function At(e){if(typeof e=="string")return e.slice(0,4e3);if(Array.isArray(e))return e.map(At).filter(Boolean).join(`
10
+ `)}}function Eo(e,t){let n=new Set,o=new Set(t.flatMap(c=>c.contract.requiredSections)),r=To(e.split(/\r?\n/)),i=Ao(r.headingLines);for(let c of o)i.found.has(c)||n.add(`missing_section:${c}`);if(t.every(c=>c.contract.runtimeProfilingOccurred))return [...n];let a=t.every(c=>c.contract.samplingEvidenceOccurred);for(let c=0;c<r.claimLines.length;c++){let d=r.claimLines[c].trim();if(!d||oa(d))continue;let u=i.byLine.get(c);for(let l of ca(d))ia(l,u,a,n);}return [...n]}function To(e){let t=false,n=[],o=[];for(let r of e){if(/^\s*```/.test(r)){t=!t,n.push(""),o.push(r.replace(/^\s*```+[^\s`]*/,"").replace(/```+\s*$/,"").trim());continue}n.push(t?"":r.replace(/`[^`]*`/g,"").trim()),o.push(r.replace(/`([^`]*)`/g,(i,s)=>na(s)?"":s).trim());}return {headingLines:n,claimLines:o}}function na(e){let t=e.trim().slice(0,256);return !t||/\s/.test(t)||e.trim().length>256?false:/^[A-Za-z_$][\w$.-]*$/.test(t)||/^(['"])[^'"`]*\1$/.test(t)}function oa(e){if(e.length>2048)return false;let t=e.replace(/^\s*(?:[-*+]|\d+[.)])\s+/,"").trim();return t?ra(t)||/^(?:\/\/|\/\*|\*\/|\*\s|#!)/.test(t)||/^(?:import|export|const|let|var|function|class|type|interface|enum|namespace|declare)\b/.test(t)||/^(?:async\s+)?(?:function\s+)?[A-Za-z_$][\w$]*\s*=\s*/.test(t)||/^[A-Za-z_$][\w$.[\]'"-]*\s*(?:=|\+=|-=|\*=|\/=|\?\?=|&&=|\|\|=)\s*/.test(t)||/^[A-Za-z_$'"-][\w$.'"-]*\s*:\s*[^:]+[,}]?$/.test(t)||/=>/.test(t)||/^(?:await\s+|return\s+|throw\s+|new\s+)?[A-Za-z_$][\w$.]*\s*\([^)]*\)\s*;?$/.test(t)||/^(['"])[\s\S]*\1[;,]?$/.test(t)?true:/[{}()[\]=<>]\s*;?$/.test(t)&&/(?:;|=>|\b(?:return|new|await)\b)/.test(t):false}function ra(e){if(e.length>1024)return false;let t="(?:--[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(`^${t}\\s*:\\s*\\S[^;]{0,960};$`,"i").test(e)}function ia(e,t,n,o){let r=/\bP0\b/gi;for(let g of e.matchAll(r))Ro(e,g.index??0,g[0],"p0")||o.add("unsupported_p0_severity");let i=/(?:中高|高)(?:风险|优先级)|严重(?:问题|风险)|\bhigh[- ](?:risk|severity|priority)\b/gi;for(let g of e.matchAll(i))Ro(e,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 e.matchAll(s))aa(e,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(e),c=/(?:预计|预期|估计|提升|降低|减少|节省|改善|收益|加速|improve|reduce|faster|gain|benefit|speedup|expected|estimated)/i.test(e),d=/\b\d+(?:\.\d+)?\s*[x×]\b/i.test(e);(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(e)||/\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:毫秒|次\s*\/\s*秒|帧)/.test(e),l=t==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&/(?:采集|记录|测量|收集|collect|measure|record)/i.test(e)&&!/(?:预计|预期|估计|约|大约|通常|平均|每(?:隔)?|达到|提升|降低|减少|节省|改善|improve|reduce|faster|expected|estimated|average|typically|every)/i.test(e);a&&!c&&!l&&o.add("unsupported_benefit_percentage"),u&&!l&&o.add("unsupported_performance_number");let m=/(?:requestAnimationFrame|\bRAF\b)/i.test(e),f=/(?:建议|应该|应当|使用|添加|采用|切换|包裹|优化|节流|\buse\b|\badopt\b|\brecommend\b|\bswitch\b|\bwrap\b|\bthrottl(?:e|ing)\b)/i.test(e),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(e);m&&f&&!p&&!n&&o.add("raf_without_sampling_evidence");}function Ro(e,t,n,o){let r=e.slice(Math.max(0,t-64),t),i=e.slice(t+n.length,t+n.length+28),s=sa(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 sa(e){if(/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?|不是|并非|未被)\s*(?:任何|明确的)?\s*(?:(?:问题|发现|证据|项|内容)\s*)?(?:(?:属于|(?:被)?(?:评|判定|认定|标记|列|视|定|归(?:类)?)为)\s*)?$/i.test(e)||/\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(e))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(e)||o.test(e)}function aa(e,t,n){let o=e.slice(Math.max(0,t-40),t),r=e.slice(t+n.length,t+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 ca(e){return e.split(/(?:[。!?;;,,]|\b(?:but|however|yet|nevertheless|nonetheless)\b|但是|但|然而|却|不过|可是)/i).map(t=>t.trim()).filter(Boolean)}function ve(e,t,n){if(t>Ys||e===null||e===void 0)return null;if(typeof e=="string"){if(Buffer.byteLength(e,"utf8")>Js)return null;try{return ve(JSON.parse(e),t+1,n)}catch{return null}}if(typeof e!="object"||n.has(e))return null;if(n.add(e),Array.isArray(e)){for(let r of e.slice(0,16)){let i=ve(r,t+1,n);if(i)return i}return null}let o=e;if("evidenceContract"in o)return {contract:o.evidenceContract,canonicalReport:o.canonicalReport};for(let r of ["structuredContent","data","result"])if(r in o){let i=ve(o[r],t+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=ve(i,t+1,n);if(s)return s}return null}function da(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;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!==ye.length)return null;let o=n.requiredSections.filter(c=>typeof c=="string");if(o.length!==ye.length||ye.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:t;return typeof a!="string"||Buffer.byteLength(a,"utf8")>Gs||ye.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 Rt(e,t){if(!e||e.length>4096)return {degradationReason:"transcript_path_missing"};let n;try{let o=lstatSync$1(e);if(!o.isFile()||o.isSymbolicLink())return {degradationReason:"transcript_path_unsafe"};n=openSync$1(e,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,Ks),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(`
11
+ `)+1)));let d=c.split(/\r?\n/).slice(-Vs),u=t.length>0?Math.min(...t.map(p=>p.promptedAt)):0,l=ua(d,u),f=[...l].reverse().find(p=>la(p.text,t))??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 la(e,t){let n=new Set(t.flatMap(r=>r.contract.requiredSections)),o=Ao(To(e.split(/\r?\n/u)).headingLines);return [...n].every(r=>o.found.has(r))}function Je(e){return Rt(e,[]).answer}function ua(e,t){let n=[];for(let o=0;o<e.length;o++){let r=e[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=ma(i.timestamp);if(c>0&&c+5e3<t)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(`
12
+ `):"";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 ma(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string")return 0;let t=Date.parse(e);return Number.isFinite(t)?t:0}function Ao(e){let t=new Set,n=new Map,o;for(let r=0;r<e.length;r++){let i=e[r].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=ye.find(a=>i===a);s&&(o=s,t.add(s)),n.set(r,o);}return {found:t,byLine:n}}function Oo(e){let t;try{if(va(e.toolResponse))return null;t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let n=t.getActiveContextReceipt(e.projectRoot,e.sessionId,e.executionId);if(!n)return null;let o=fa(e.toolInput,e.toolResponse);if(o.length===0)return null;let r=e.toolName==="Read"?ga(e.toolInput):void 0,i=r?n.selectedFiles?.find(u=>ha(e.projectRoot,u,r)):void 0,s=ya(e.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,e.toolUseId??`${e.sessionId}:${e.executionId??n.executionId}`].join("\0");t.recordContextSelectionEvent({id:`ctxsel:${createHash("sha256").update(u).digest("hex").slice(0,32)}`,projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n.executionId,requestId:n.requestId,selectionType:a,candidateId:c,toolName:e.toolName,toolUseId:e.toolUseId,selectedAt:Date.now()});}let d=t.listRetrievalLedgerEvents({projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n.executionId,requestId:n.requestId}).filter(u=>u.stage==="selected"&&o.includes(u.sourceId));for(let u of d)t.appendRetrievalLedgerEvent({...u,id:xt(u.id,"consumed",e.toolUseId??e.toolName),stage:"consumed",toolEvidence:[e.toolUseId??e.toolName],evidenceIds:o,actor:e.toolName,reasonCode:"structural_evidence_ref",payload:{...u.payload,consumedByTool:e.toolName},createdAt:Date.now()});return d.length>0&&Et({event:"retrieval.attribution.transitioned",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n.executionId,requestId:n.requestId,contextReceipt:n.contextHash},level:"info",timestamp:Date.now(),data:{stage:"consumed",actor:e.toolName,consumedCount:d.length,evidenceRefCount:o.length}}),a}catch(n){return Et({event:"hook.runtime.degraded",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,requestId:e.requestId},level:"warn",timestamp:Date.now(),data:{stage:"retrieval_attribution",actor:e.toolName,reason:n instanceof Error?n.message:String(n)}}),null}finally{try{t?.close();}catch{}}}function Po(e){let t=openGlobalDevFlowDatabase();try{let n=t.listRetrievalLedgerEvents(e),o=new Map(n.filter(d=>d.stage==="selected").map(d=>[Co(d),d])),r=new Map(n.filter(d=>d.stage==="consumed").map(d=>[Co(d),d])),i=0,s=0,a=0;for(let[d,u]of o){let l=r.get(d);l&&e.verificationReceipt&&t.appendRetrievalLedgerEvent({...l,id:xt(l.id,"verified",e.verificationReceipt),stage:"verified",verificationReceipt:e.verificationReceipt,reasonCode:"same_task_verification_receipt",createdAt:e.finishedAt??Date.now()});let m=l&&e.verificationReceipt&&e.outcome!=="unknown"?e.outcome:"unknown",f=m==="positive"?"positive_outcome":m==="negative"?"negative_outcome":"unknown_outcome";t.appendRetrievalLedgerEvent({...u,id:xt(u.id,f,e.verificationReceipt??e.sessionId),stage:f,reason:l?e.outcomeReason:"selected_not_adopted",toolEvidence:l?.toolEvidence??[],verificationReceipt:m==="unknown"?void 0:e.verificationReceipt,payload:{...u.payload,adopted:!!l},createdAt:e.finishedAt??Date.now()}),f==="positive_outcome"?i+=1:f==="negative_outcome"?s+=1:a+=1;}let c={adopted:r.size,positive:i,negative:s,unknown:a,adoptedSources:[...r.values()].map(d=>({sourceType:d.sourceType,sourceId:d.sourceId}))};return Et({event:"retrieval.attribution.transitioned",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,requestId:e.requestId},level:a>0?"warn":"info",timestamp:e.finishedAt??Date.now(),data:{stage:"session_outcome",selectedCount:o.size,consumedCount:r.size,verifiedCount:e.verificationReceipt?r.size:0,positiveCount:i,negativeCount:s,unknownCount:a}}),c}finally{t.close();}}function fa(...e){let t=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()&&t.add(a.trim());else n(s,r+1);}};for(let o of e)n(o);return [...t]}function ga(e){for(let t of ["file_path","path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n.trim()}}function ha(e,t,n){let o=resolve(e,t),r=isAbsolute(n)?resolve(n):resolve(e,n);return o===r}function ya(e){return e.startsWith("mcp__")?e.split("__").at(-1)??e:e}function va(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return t.ok===false||t.success===false||t.isError===true||!!t.error||["failed","rejected","unavailable"].includes(String(t.status??""))}function xt(e,t,n){return `retrieval:${createHash("sha256").update(`${e}\0${t}\0${n}`).digest("hex")}`}function Co(e){return [e.requestId,e.contextReceipt,e.sourceType,e.sourceId].join("\0")}function Et(e){try{emitSemanticControlLog(e);}catch{}}var xa=8*1024*1024;function $o(e){if(!e.transcriptPath||!existsSync(e.transcriptPath))return {status:"unavailable",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:"transcript_path_unavailable"};let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=t.getLatestTranscriptCheckpoint({projectRoot:e.projectRoot,hostId:"claude-code",sessionId:e.sessionId,sourcePath:e.transcriptPath}),o=statSync(e.transcriptPath).size,r=Math.min(n?.byteOffset??0,o),i=Math.min(xa,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(e.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=t.listLatestTaskIntentArtifacts(e.projectRoot,e.sessionId),u=new Map,l=new Set,m=0,f=0;for(let b of c){let h;try{h=JSON.parse(b);}catch{continue}for(let R of Tt(h,u)){let w=claudeCodeRuntimeAdapter.normalizeToolResult(R,{projectRoot:e.projectRoot});if(w.success||!w.error)continue;let x=w.toolUseId??w.sourceHash;if(l.has(x))continue;l.add(x),m++;let A=w.toolUseId?t.getToolCallEventByToolUseId(e.sessionId,w.toolUseId):null,M=Fo(A?.input,"_devflow_turn_id"),H=Fo(A?.input,"_devflow_request_id"),S=M?d.find(T=>T.turnId===M):[...d].reverse().find(T=>(!A?.executionId||T.executionId===A.executionId)&&T.createdAt<=(A?.timestamp??w.timestamp))??d.at(-1),C=`host-failure:${w.sourceHash}`;t.insertEvent({kind:"host_transcript_tool_failure",timestamp:w.timestamp,success:!1,toolName:w.canonicalName??w.requestedName,metadata:{projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:M??S?.turnId,requestId:H??S?.requestId,sourceId:C,toolUseId:w.toolUseId,correlatedEventId:A?.eventId,requestedName:w.requestedName,canonicalName:w.canonicalName,failureCategory:w.failureCategory,error:w.error.slice(0,1e3)}}),emitSemanticControlLog({event:"host.tool.result.reconciled",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:M??S?.turnId,requestId:H??S?.requestId,executionId:A?.executionId},level:"warn",timestamp:Date.now(),data:{toolUseId:w.toolUseId,toolName:w.canonicalName??w.requestedName,failureCategory:w.failureCategory,correlation:A?"tool_use_id":"timestamp_fallback"}}),f++;}}let p=createHash("sha256").update(s).digest("hex"),g=`transcript:${createHash("sha256").update(`${e.projectRoot}\0${e.sessionId}\0${e.transcriptPath}\0${r+i}\0${p}`).digest("hex").slice(0,24)}`;return t.appendTranscriptCheckpoint({id:g,projectRoot:e.projectRoot,hostId:"claude-code",sessionId:e.sessionId,sourcePath:e.transcriptPath,sourceHash:p,byteOffset:r+i,eventCount:c.length,createdAt:Date.now()}),emitSemanticControlLog({event:"session.reconciled",identity:{projectRoot:e.projectRoot,sessionId:e.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{t.close();}}function Fo(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function Tt(e,t,n=0){if(n>7||e===null||e===void 0)return [];if(Array.isArray(e))return e.flatMap(s=>Tt(s,t,n+1));if(typeof e!="object")return [];let o=e,r=typeof o.type=="string"?o.type:"";r==="tool_use"&&typeof o.id=="string"&&typeof o.name=="string"&&t.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?t.get(s)??"unknown":"unknown",tool_use_id:s,tool_response:o.content,is_error:o.is_error===true,...o.is_error===true?{error:At(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(...Tt(a,t,n+1));return i}function At(e){if(typeof e=="string")return e.slice(0,4e3);if(Array.isArray(e))return e.map(At).filter(Boolean).join(`
13
13
  `).slice(0,4e3);if(!e||typeof e!="object")return "";let t=e;return [t.text,t.content,t.message].map(At).filter(Boolean).join(`
14
- `).slice(0,4e3)}var Ea={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 Ho(e){let t=Ta(e);return wo({artifact:e.artifact,legacyState:t.toState}),t}function Ta(e){let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=Ma(t,e.artifact);if(Oa(n.toState))return n;let o=t.getContextReceiptForRequest(e.artifact.projectRoot,e.artifact.sessionId,e.artifact.requestId),r=e.artifact.intent==="memory";if(!o&&!r)return n;let i=o?Aa(e.artifact,o):"context_ready";n.toState==="intent_bound"&&(n=P(t,n,e,i,r?"task_context_not_required":i==="context_ready"?"canonical_context_receipt_ready":"canonical_context_receipt_degraded"));let s=o?Ca(e.artifact,o):"action_not_required";if((n.toState==="context_ready"||n.toState==="context_degraded")&&(s==="action_not_required"?n=P(t,n,e,"action_not_required","task_action_not_required"):n=P(t,n,e,"action_required","canonical_action_obligation_present")),n.toState==="action_required"){if(s==="action_required")return n;if(s==="action_failed")return P(t,n,e,"action_failed","canonical_action_attempt_failed");s==="action_degraded"?n=P(t,n,e,"action_degraded","canonical_action_unavailable_or_degraded"):s==="action_satisfied"&&(n=P(t,n,e,"action_satisfied","canonical_action_succeeded"));}if(n.toState==="action_failed")if(s==="action_satisfied")n=P(t,n,e,"action_satisfied","canonical_action_retry_succeeded");else if(s==="action_degraded")n=P(t,n,e,"action_degraded","canonical_action_retry_degraded");else return n;let a=i==="context_degraded"||s==="action_degraded";return ["action_not_required","action_satisfied","action_degraded"].includes(n.toState)&&(n=P(t,n,e,e.memoryStatus==="pending"?"memory_quarantined":"memory_decided",e.memoryStatus==="pending"?e.reason:`canonical_memory_${e.memoryStatus}`)),n.toState==="memory_decided"?P(t,n,e,a?"closed_with_degradation":"closed",e.reason):n.toState==="memory_quarantined"?P(t,n,e,e.retryOwned?"closed_with_retry_work":"closed_with_degradation",e.retryOwned?"durable_retry_owner_confirmed":"terminal_obligation_unowned"):n}finally{t.close();}}function Aa(e,t){return e.intent==="memory"||e.intent==="knowledge"||(t.selectedFiles?.length??0)>0?"context_ready":"context_degraded"}function Ca(e,t){let n=t.canonicalAction,r=(n?(t.actionAttempts??[]).filter(i=>i.tool===n.tool):[]).at(-1);return t.actionSatisfiedAt||r?.status==="succeeded"?"action_satisfied":r&&["failed","timeout","unavailable"].includes(r.status)?"action_failed":t.actionDegradation||n?.status==="degraded"||n?.status==="unsupported"?"action_degraded":n?.required||Da(e)?"action_required":"action_not_required"}function Da(e){return ["create","modify","debug","test","format"].includes(e.action)||["feature","refactor","performance"].includes(e.intent)}function Ma(e,t){let n=e.getLatestTerminalTransition(t.projectRoot,t.sessionId,t.turnId);if(!n)throw new Error(`TERMINAL_INTENT_STATE_MISSING:${t.turnId}`);return n}function P(e,t,n,o,r){if(!Ea[t.toState]?.includes(o))throw new Error(`TERMINAL_PATH_UNAVAILABLE:${t.toState}->${o}`);let i=t.sequence+1,s=`terminal:${createHash("sha256").update(`${n.artifact.artifactHash}\0${i}\0${o}`).digest("hex").slice(0,24)}`,a=e.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:t.toState,toState:o,receiptId:s,sourceReceiptId:n.memoryReceiptId??t.receiptId,reason:r,payload:{memoryStatus:n.memoryStatus,retryOwned:n.retryOwned??false,sourceIntentHash:n.artifact.artifactHash},createdAt:Date.now()});return emitSemanticControlLog({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:t.toState,nextState:o,receiptId:s,reason:r}}),a}function Oa(e){return e==="closed"||e==="closed_with_degradation"||e==="closed_with_retry_work"}function Ct(e){let t={committed:0,skipped:0,pending:0},n=[];for(let o of e)t[o.status]+=1,o.receiptId&&n.push(o.receiptId);return {memoryReceiptIds:[...new Set(n)],missingMemoryDecisionCount:t.pending,memoryTurnOutcomes:t}}function j(e){return (e instanceof Error?e.message:String(e)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var V=class extends Error{constructor(t,n){super(`session_finalize_${t}:${n}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${t}`;}};function ve(e){let t;try{t=openGlobalDevFlowDatabase();let n=(e.executionId?t.getSkillExecution(e.executionId):null)??t.getLatestSkillExecutionForSession(e.sessionId),o={stage:e.stage,reason:e.reason,degradedAt:Date.now()};n&&t.mergeSkillExecutionMetadata(n.executionId,{...e.metadata,sessionFinalizationDegradations:[o]}),t.insertEvent({kind:"session_finalize_degraded",timestamp:o.degradedAt,success:!1,metadata:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n?.executionId,...o}}),emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n?.executionId},level:"warn",timestamp:o.degradedAt,data:{stage:e.stage,reason:e.reason}});}catch{}finally{t?.close();}}function Ge(e,t=Me(),n=true,o,r=true){let i;try{i=JSON.parse(e);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${t}\0${s}`).digest("hex").slice(0,24)}`,c={inputJson:e,sessionId:s,cleanupSharedState:n,executionId:o},d;try{d=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let l=d.requestSessionClosure({receiptId:a,projectRoot:t,sessionId:s,payload:c}),u=d.getWorkByIdempotencyKey(a),p={status:l.state==="closed"||l.state==="closed_with_pending_work"?"completed":"accepted",receiptId:a,workState:u?.state??"pending",closureState:l.state,pendingWorkCount:l.pendingWorkCount,...u?.id?{workItemId:u.id}:{}};return emitSemanticControlLog({event:"hook.session_end.completed",identity:{projectRoot:t,sessionId:s,executionId:o,terminalReceipt:a},level:p.status==="completed"?"info":"debug",timestamp:Date.now(),data:{stage:"enqueue",...p}}),p}catch(l){if(!r)throw l;return go(t,{receiptId:a,...c}),emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:s,executionId:o,terminalReceipt:a},level:"warn",timestamp:Date.now(),data:{stage:"enqueue",reason:j(l),fallback:"durable_spool"}}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{d?.close();}}async function Lo(e,t=Me(),n=true,o){let r;try{r=JSON.parse(e);}catch{return}let i=r.session_id?.trim();if(!i)return;let s=new L(t),a=s.get(i),c=$o({projectRoot:t,sessionId:i,transcriptPath:r.transcript_path}),d={evidenceDegradations:a?.evidenceDegradations??[],evidenceContractOutcomes:a?.evidenceOutcomes??[],pendingEvidenceContractIds:a?.evidenceObligations.map(m=>m.contractId)??[],transcriptReconciliation:c},l=o?.telemetry??new ee,u=!o?.telemetry,p=false,g;try{try{await l.flushAndAggregate();}catch{}let m=Date.now(),f=o?.executionId??a?.executionId,k;try{let _=openGlobalDevFlowDatabase();try{k=_.listSessionMemoryTurnsForReconciliation(t,i);for(let y of k){let w=`memory:${y.turnId}`,v=_.getSessionObligation(t,i,w);v?v.state==="open"&&y.status!=="pending"&&_.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:w,state:"satisfied",receiptId:y.receiptId,reason:y.reason,resolvedAt:y.decidedAt}):_.upsertSessionObligation({obligationId:w,projectRoot:t,sessionId:i,turnId:y.turnId,kind:"memory_decision",state:y.status==="pending"?"open":"satisfied",payload:{eventId:y.eventId,promptHash:y.promptHash},receiptId:y.receiptId,reason:y.reason,createdAt:y.createdAt,updatedAt:y.decidedAt??y.createdAt,resolvedAt:y.decidedAt});}}finally{_.close();}}catch(_){let y=j(_),w={...d,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:y,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ve({projectRoot:t,sessionId:i,executionId:f,stage:"turn_load",reason:y,metadata:w}),new V("turn_load",y)}let I=Ct(k),S=o?.memory??(g=new MemoryGate(t)),b={status:"completed"};try{b=typeof S.reconcileTurnObservationLineage=="function"?{status:"completed",...await S.reconcileTurnObservationLineage(k)}:{status:"unsupported_adapter",committed:0,skipped:0,quarantined:0,unlinked:0};}catch(_){let y=j(_);throw b={status:"degraded",reason:y},ve({projectRoot:t,sessionId:i,executionId:f,stage:"memory_lineage",reason:y,metadata:{...I,...d,memoryLineageReconciliation:b}}),new V("memory_lineage",y)}let $={status:"unknown",selected:0,adopted:0,unknown:0,positive:0,negative:0};try{let _=Je(r.transcript_path),y=openGlobalDevFlowDatabase(),w="unknown",v="no_terminal_host_action_evidence",le,U,N,z=[];try{let B=y.listHostActionsForSession(t,i,f),In=B.filter(F=>F.state==="verified"),dt=B.filter(F=>["failed","cancelled","degraded"].includes(F.state));dt.length>0?(w="negative",v=`terminal_host_action_${dt[0].state}`):In.length>0&&(w="positive",v="host_action_verified");let Ce=dt[0]??In.at(-1);if(le=Ce?.runId,U=Ce?.contextReceipt,N=Ce?.evidenceHash,z=B.flatMap(F=>{let Q=F.report.toolUseIds;return Array.isArray(Q)?Q.filter(ue=>typeof ue=="string"):[]}),!Ce&&f){let F=y.getSkillExecution(f),Q=F?.metadata&&typeof F.metadata=="object"&&Array.isArray(F.metadata.policyVerificationOutcomes)?F.metadata.policyVerificationOutcomes:[],ue=Q.find(J=>J.status==="failed"),lt=Q.filter(J=>J.status==="passed");ue?(w="negative",v="policy_verification_failed",N=typeof ue.receiptId=="string"?ue.receiptId:void 0):lt.length>0&&(w="positive",v="policy_verification_passed",N=typeof lt.at(-1)?.receiptId=="string"?String(lt.at(-1).receiptId):void 0),U=y.getActiveContextReceipt(t,i,f)?.contextHash,z=Q.map(J=>J.command).filter(J=>typeof J=="string");}}finally{y.close();}let vn=Po({projectRoot:t,sessionId:i,executionId:f,outcome:w,outcomeReason:v,verificationReceipt:N,finishedAt:m}),ci=await S.attributeRetrievalBenefits({sessionId:i,executionId:f,finalAnswer:_,outcome:w,outcomeReason:v,workflowRunId:le,contextReceipt:U,toolEvidence:z,verificationReceipt:N,adoptedSourceIds:vn.adoptedSources.filter(B=>B.sourceType==="memory").map(B=>B.sourceId)});$={status:_?"evaluated":"unknown",...ci,retrievalLedger:vn};}catch(_){$={...$,status:"degraded",reason:j(_)};}let T;try{T=await S.reconcileDecidedTurnEventWindows(i,k,m);}catch(_){let y=j(_),w={...I,...d,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:y,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ve({projectRoot:t,sessionId:i,executionId:f,stage:"event_reconciliation",reason:y,metadata:w}),new V("event_reconciliation",y)}let D;try{D=await he({projectRoot:t,sessionId:i,trigger:"session_end",memory:S,details:{eventReconciliation:T},strictPersistence:!0});}catch(_){let y=j(_),w={...I,...d,memoryEventReconciliation:{status:"completed",...T,checkpointPending:null},memoryCheckpointDegradation:y};throw ve({projectRoot:t,sessionId:i,executionId:f,stage:"checkpoint",reason:y,metadata:w}),new V("checkpoint",y)}let H={memoryLineageReconciliation:b,memoryBenefitAttribution:$,memoryEventReconciliation:{status:"completed",...T,checkpointPending:D.pendingEvents},memoryDistillCheckpoint:D};try{let _=openGlobalDevFlowDatabase();try{let y=`session-finalize:${i}:events`,w=Math.max(Number(D.pendingEvents??0),Number(T.remainingUndecided??0)),v=_.getSessionObligation(t,i,y);w>0?_.upsertSessionObligation({obligationId:y,projectRoot:t,sessionId:i,executionId:f,kind:"session_finalize",state:"open",payload:{pendingEvents:w,reconciliation:T,checkpointId:D.id},reason:"active_unprocessed_session_events",createdAt:v?.createdAt??m,updatedAt:m}):v?.state==="open"&&_.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:y,state:"satisfied",reason:"session_events_reconciled",resolvedAt:m});}finally{_.close();}}catch(_){emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:f},level:"warn",timestamp:Date.now(),data:{stage:"obligation_persistence",reason:j(_)}});}try{await S.closeSession(i),g&&(g.close(),g=void 0);}catch(_){let y=j(_),w={...I,...d,...H,memorySessionCloseDegradation:y};throw ve({projectRoot:t,sessionId:i,executionId:f,stage:"memory_close",reason:y,metadata:w}),new V("memory_close",y)}let R={...I,...d,...H},A=[];try{let _=openGlobalDevFlowDatabase();try{let y=new Map(_.listLatestTaskIntentArtifacts(t,i).map(w=>[w.turnId,w]));for(let w of k){let v=y.get(w.turnId);if(!v)continue;let U=[_.getWorkByIdempotencyKey(`memory-turn:capture_prompt:${w.turnId}`),_.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${w.turnId}`)].filter(Boolean).some(z=>z.state==="pending"||z.state==="leased"||z.state==="failed"),N=Ho({artifact:v,memoryStatus:w.status,memoryReceiptId:w.receiptId,retryOwned:U,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:j(_)});}R.terminalOutcomes=A,p=!0;let E;try{E=openGlobalDevFlowDatabase();let _=f;if(_)try{E.reconcileSkillExecution(_,"completed",m,R);let v=E.getSkillExecution(_);await G("/api/telemetry/skill-execution/complete",{executionId:_,finishedAt:m,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:R},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let y=E.reconcileRunningSkillExecutionsForSession(i,m,{closureReason:"session_finalize",...R});for(let v of y)await G("/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:R},{fallbackReason:"skill_execution_already_reconciled_locally"});let w=E.getLatestSkillExecutionForSession(i);if(w&&!y.some(v=>v.executionId===w.executionId)&&E.mergeSkillExecutionMetadata(w.executionId,R),n){E.deleteHookReceipt(t);let v=M(t),le=createHash("sha256").update(t).digest("hex").slice(0,12);for(let U of [`session-id-${le}`,"current-execution-id","current-skill.json","event-map.json"])rmSync$1(join(v,U),{force:!0});}E.deleteContextReceipt(t,i);}catch(_){emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:f},level:"warn",timestamp:Date.now(),data:{stage:"lifecycle_telemetry",reason:j(_),fallback:"fail_open"}});}finally{E?.close();}try{await l.endSession(i),await l.flushAndAggregate();}catch(_){emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:f},level:"warn",timestamp:Date.now(),data:{stage:"telemetry_flush",reason:j(_),fallback:"local_state_authoritative"}});}}finally{if(g)try{g.close();}catch{}u&&l.close(),p&&s.removeSession(i),emitSemanticControlLog({event:p?"hook.session_end.completed":"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:o?.executionId??a?.executionId},level:p?"info":"warn",timestamp:Date.now(),data:{stage:"finalize",criticalStagesCompleted:p,transcriptStatus:c.status}});}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let e=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n;}),process.stdin.on("end",async()=>{let n=Ge(t.trim()||process.argv[2]||"");n&&e(JSON.stringify(n)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var Ua=/^\/(?:devflow:)?[\w-]+\b\s*/iu,za=/\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,Ba=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,Ja=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function Ie(e){let t=e.trim().replace(Ua,"").trim();return !t||za.test(t)?null:(Ja.exec(t)??Ba.exec(t))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}function Ga(e){let t=createHash("sha256").update(e).digest("hex").slice(0,16),n=process.env.DEVFLOW_STATE_DIR||join(homedir(),".devflow","state",t);return join(n,"memory-intents.jsonl")}function Ka(e){try{return readFileSync$1(e,"utf8").split(`
15
- `).filter(Boolean).flatMap(t=>{try{let n=JSON.parse(t);return typeof n.content=="string"&&typeof n.createdAt=="number"?[n]:[]}catch{return []}})}catch{return []}}function zo(e){let t=Ga(e),n=`${t}.claim-`,o=`${basename(t)}.claim-`,r=(()=>{try{return readdirSync$1(dirname$1(t)).filter(a=>a.startsWith(o)&&!a.includes(".tmp-")).sort()[0]}catch{return}})(),i=r?join(dirname$1(t),r):`${n}${Date.now()}-${process.pid}`;if(!r)try{renameSync(t,i);}catch{return null}let s=Ka(i);if(s.length===0){try{unlinkSync$1(i);}catch{}return null}return {path:i,intents:s}}function Mt(e){if(e.intents.shift(),e.intents.length===0){try{unlinkSync$1(e.path);}catch{}return}let t=`${e.path}.tmp-${process.pid}`;writeFileSync$1(t,e.intents.map(n=>JSON.stringify(n)).join(`
14
+ `).slice(0,4e3)}var Aa={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 Ho(e){let t=Ca(e);return wo({artifact:e.artifact,legacyState:t.toState}),t}function Ca(e){let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=Pa(t,e.artifact);if(ja(n.toState))return n;let o=t.getContextReceiptForRequest(e.artifact.projectRoot,e.artifact.sessionId,e.artifact.requestId),r=e.artifact.intent==="memory";if(!o&&!r)return n;let i=o?Da(e.artifact,o):"context_ready";n.toState==="intent_bound"&&(n=j(t,n,e,i,r?"task_context_not_required":i==="context_ready"?"canonical_context_receipt_ready":"canonical_context_receipt_degraded"));let s=o?Ma(e.artifact,o):"action_not_required";if((n.toState==="context_ready"||n.toState==="context_degraded")&&(s==="action_not_required"?n=j(t,n,e,"action_not_required","task_action_not_required"):n=j(t,n,e,"action_required","canonical_action_obligation_present")),n.toState==="action_required"){if(s==="action_required")return n;if(s==="action_failed")return j(t,n,e,"action_failed","canonical_action_attempt_failed");s==="action_degraded"?n=j(t,n,e,"action_degraded","canonical_action_unavailable_or_degraded"):s==="action_satisfied"&&(n=j(t,n,e,"action_satisfied","canonical_action_succeeded"));}if(n.toState==="action_failed")if(s==="action_satisfied")n=j(t,n,e,"action_satisfied","canonical_action_retry_succeeded");else if(s==="action_degraded")n=j(t,n,e,"action_degraded","canonical_action_retry_degraded");else return n;let a=i==="context_degraded"||s==="action_degraded";return ["action_not_required","action_satisfied","action_degraded"].includes(n.toState)&&(n=j(t,n,e,e.memoryStatus==="pending"?"memory_quarantined":"memory_decided",e.memoryStatus==="pending"?e.reason:`canonical_memory_${e.memoryStatus}`)),n.toState==="memory_decided"?j(t,n,e,a?"closed_with_degradation":"closed",e.reason):n.toState==="memory_quarantined"?j(t,n,e,e.retryOwned?"closed_with_retry_work":"closed_with_degradation",e.retryOwned?"durable_retry_owner_confirmed":"terminal_obligation_unowned"):n}finally{t.close();}}function Da(e,t){return e.intent==="memory"||e.intent==="knowledge"||(t.selectedFiles?.length??0)>0?"context_ready":"context_degraded"}function Ma(e,t){let n=t.canonicalAction,r=(n?(t.actionAttempts??[]).filter(i=>i.tool===n.tool):[]).at(-1);return t.actionSatisfiedAt||r?.status==="succeeded"?"action_satisfied":r&&["failed","timeout","unavailable"].includes(r.status)?"action_failed":t.actionDegradation||n?.status==="degraded"||n?.status==="unsupported"?"action_degraded":n?.required||Oa(e)?"action_required":"action_not_required"}function Oa(e){return ["create","modify","debug","test","format"].includes(e.action)||["feature","refactor","performance"].includes(e.intent)}function Pa(e,t){let n=e.getLatestTerminalTransition(t.projectRoot,t.sessionId,t.turnId);if(!n)throw new Error(`TERMINAL_INTENT_STATE_MISSING:${t.turnId}`);return n}function j(e,t,n,o,r){if(!Aa[t.toState]?.includes(o))throw new Error(`TERMINAL_PATH_UNAVAILABLE:${t.toState}->${o}`);let i=t.sequence+1,s=`terminal:${createHash("sha256").update(`${n.artifact.artifactHash}\0${i}\0${o}`).digest("hex").slice(0,24)}`,a=e.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:t.toState,toState:o,receiptId:s,sourceReceiptId:n.memoryReceiptId??t.receiptId,reason:r,payload:{memoryStatus:n.memoryStatus,retryOwned:n.retryOwned??false,sourceIntentHash:n.artifact.artifactHash},createdAt:Date.now()});return emitSemanticControlLog({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:t.toState,nextState:o,receiptId:s,reason:r}}),a}function ja(e){return e==="closed"||e==="closed_with_degradation"||e==="closed_with_retry_work"}function Ct(e){let t={committed:0,skipped:0,pending:0},n=[];for(let o of e)t[o.status]+=1,o.receiptId&&n.push(o.receiptId);return {memoryReceiptIds:[...new Set(n)],missingMemoryDecisionCount:t.pending,memoryTurnOutcomes:t}}function F(e){return (e instanceof Error?e.message:String(e)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var V=class extends Error{constructor(t,n){super(`session_finalize_${t}:${n}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${t}`;}};function _e(e){let t;try{t=openGlobalDevFlowDatabase();let n=(e.executionId?t.getSkillExecution(e.executionId):null)??t.getLatestSkillExecutionForSession(e.sessionId),o={stage:e.stage,reason:e.reason,degradedAt:Date.now()};n&&t.mergeSkillExecutionMetadata(n.executionId,{...e.metadata,sessionFinalizationDegradations:[o]}),t.insertEvent({kind:"session_finalize_degraded",timestamp:o.degradedAt,success:!1,metadata:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n?.executionId,...o}}),emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n?.executionId},level:"warn",timestamp:o.degradedAt,data:{stage:e.stage,reason:e.reason}});}catch{}finally{t?.close();}}function Ge(e,t=Me(),n=true,o,r=true){let i;try{i=JSON.parse(e);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${t}\0${s}`).digest("hex").slice(0,24)}`,c={inputJson:e,sessionId:s,cleanupSharedState:n,executionId:o},d;try{d=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let u=d.requestSessionClosure({receiptId:a,projectRoot:t,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 emitSemanticControlLog({event:"hook.session_end.completed",identity:{projectRoot:t,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 go(t,{receiptId:a,...c}),emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:s,executionId:o,terminalReceipt:a},level:"warn",timestamp:Date.now(),data:{stage:"enqueue",reason:F(u),fallback:"durable_spool"}}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{d?.close();}}async function Lo(e,t=Me(),n=true,o){let r;try{r=JSON.parse(e);}catch{return}let i=r.session_id?.trim();if(!i)return;let s=new L(t),a=s.get(i),c=$o({projectRoot:t,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 ee,l=!o?.telemetry,m=false,f;try{try{await u.flushAndAggregate();}catch{}let p=Date.now(),g=o?.executionId??a?.executionId,b;try{let _=openGlobalDevFlowDatabase();try{b=_.listSessionMemoryTurnsForReconciliation(t,i);for(let v of b){let k=`memory:${v.turnId}`,I=_.getSessionObligation(t,i,k);I?I.state==="open"&&v.status!=="pending"&&_.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:k,state:"satisfied",receiptId:v.receiptId,reason:v.reason,resolvedAt:v.decidedAt}):_.upsertSessionObligation({obligationId:k,projectRoot:t,sessionId:i,turnId:v.turnId,kind:"memory_decision",state:v.status==="pending"?"open":"satisfied",payload:{eventId:v.eventId,promptHash:v.promptHash},receiptId:v.receiptId,reason:v.reason,createdAt:v.createdAt,updatedAt:v.decidedAt??v.createdAt,resolvedAt:v.decidedAt});}}finally{_.close();}}catch(_){let v=F(_),k={...d,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:v,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw _e({projectRoot:t,sessionId:i,executionId:g,stage:"turn_load",reason:v,metadata:k}),new V("turn_load",v)}let h=Ct(b),R=o?.memory??(f=new MemoryGate(t)),w={status:"completed"};try{w=typeof R.reconcileTurnObservationLineage=="function"?{status:"completed",...await R.reconcileTurnObservationLineage(b)}:{status:"unsupported_adapter",committed:0,skipped:0,quarantined:0,unlinked:0};}catch(_){let v=F(_);throw w={status:"degraded",reason:v},_e({projectRoot:t,sessionId:i,executionId:g,stage:"memory_lineage",reason:v,metadata:{...h,...d,memoryLineageReconciliation:w}}),new V("memory_lineage",v)}let x={status:"unknown",selected:0,adopted:0,unknown:0,positive:0,negative:0};try{let _=Je(r.transcript_path),v=openGlobalDevFlowDatabase(),k="unknown",I="no_terminal_host_action_evidence",le,U,N,z=[];try{let B=v.listHostActionsForSession(t,i,g),In=B.filter($=>$.state==="verified"),dt=B.filter($=>["failed","cancelled","degraded"].includes($.state));dt.length>0?(k="negative",I=`terminal_host_action_${dt[0].state}`):In.length>0&&(k="positive",I="host_action_verified");let Ce=dt[0]??In.at(-1);if(le=Ce?.runId,U=Ce?.contextReceipt,N=Ce?.evidenceHash,z=B.flatMap($=>{let Q=$.report.toolUseIds;return Array.isArray(Q)?Q.filter(ue=>typeof ue=="string"):[]}),!Ce&&g){let $=v.getSkillExecution(g),Q=$?.metadata&&typeof $.metadata=="object"&&Array.isArray($.metadata.policyVerificationOutcomes)?$.metadata.policyVerificationOutcomes:[],ue=Q.find(J=>J.status==="failed"),lt=Q.filter(J=>J.status==="passed");ue?(k="negative",I="policy_verification_failed",N=typeof ue.receiptId=="string"?ue.receiptId:void 0):lt.length>0&&(k="positive",I="policy_verification_passed",N=typeof lt.at(-1)?.receiptId=="string"?String(lt.at(-1).receiptId):void 0),U=v.getActiveContextReceipt(t,i,g)?.contextHash,z=Q.map(J=>J.command).filter(J=>typeof J=="string");}}finally{v.close();}let _n=Po({projectRoot:t,sessionId:i,executionId:g,outcome:k,outcomeReason:I,verificationReceipt:N,finishedAt:p}),li=await R.attributeRetrievalBenefits({sessionId:i,executionId:g,finalAnswer:_,outcome:k,outcomeReason:I,workflowRunId:le,contextReceipt:U,toolEvidence:z,verificationReceipt:N,adoptedSourceIds:_n.adoptedSources.filter(B=>B.sourceType==="memory").map(B=>B.sourceId)});x={status:_?"evaluated":"unknown",...li,retrievalLedger:_n};}catch(_){x={...x,status:"degraded",reason:F(_)};}let A;try{A=await R.reconcileDecidedTurnEventWindows(i,b,p);}catch(_){let v=F(_),k={...h,...d,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:v,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw _e({projectRoot:t,sessionId:i,executionId:g,stage:"event_reconciliation",reason:v,metadata:k}),new V("event_reconciliation",v)}let M;try{M=await he({projectRoot:t,sessionId:i,trigger:"session_end",memory:R,details:{eventReconciliation:A},strictPersistence:!0});}catch(_){let v=F(_),k={...h,...d,memoryEventReconciliation:{status:"completed",...A,checkpointPending:null},memoryCheckpointDegradation:v};throw _e({projectRoot:t,sessionId:i,executionId:g,stage:"checkpoint",reason:v,metadata:k}),new V("checkpoint",v)}let H={memoryLineageReconciliation:w,memoryBenefitAttribution:x,memoryEventReconciliation:{status:"completed",...A,checkpointPending:M.pendingEvents},memoryDistillCheckpoint:M};try{let _=openGlobalDevFlowDatabase();try{let v=`session-finalize:${i}:events`,k=Math.max(Number(M.pendingEvents??0),Number(A.remainingUndecided??0)),I=_.getSessionObligation(t,i,v);k>0?_.upsertSessionObligation({obligationId:v,projectRoot:t,sessionId:i,executionId:g,kind:"session_finalize",state:"open",payload:{pendingEvents:k,reconciliation:A,checkpointId:M.id},reason:"active_unprocessed_session_events",createdAt:I?.createdAt??p,updatedAt:p}):I?.state==="open"&&_.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:v,state:"satisfied",reason:"session_events_reconciled",resolvedAt:p});}finally{_.close();}}catch(_){emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"obligation_persistence",reason:F(_)}});}try{await R.closeSession(i),f&&(f.close(),f=void 0);}catch(_){let v=F(_),k={...h,...d,...H,memorySessionCloseDegradation:v};throw _e({projectRoot:t,sessionId:i,executionId:g,stage:"memory_close",reason:v,metadata:k}),new V("memory_close",v)}let S={...h,...d,...H},C=[];try{let _=openGlobalDevFlowDatabase();try{let v=new Map(_.listLatestTaskIntentArtifacts(t,i).map(k=>[k.turnId,k]));for(let k of b){let I=v.get(k.turnId);if(!I)continue;let U=[_.getWorkByIdempotencyKey(`memory-turn:capture_prompt:${k.turnId}`),_.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${k.turnId}`)].filter(Boolean).some(z=>z.state==="pending"||z.state==="leased"||z.state==="failed"),N=Ho({artifact:I,memoryStatus:k.status,memoryReceiptId:k.receiptId,retryOwned:U,reason:k.status==="pending"?"session_end_memory_pending":"session_end_reconciled"});C.push({turnId:k.turnId,state:N.toState,receiptId:N.receiptId});}}finally{_.close();}}catch(_){C.push({state:"terminal_integrity_failure",reason:F(_)});}S.terminalOutcomes=C,m=!0;let T;try{T=openGlobalDevFlowDatabase();let _=g;if(_)try{T.reconcileSkillExecution(_,"completed",p,S);let I=T.getSkillExecution(_);await G("/api/telemetry/skill-execution/complete",{executionId:_,finishedAt:p,status:"completed",summary:{totalToolCalls:I?.totalToolCalls??0,mcpToolCalls:I?.mcpToolCalls??0,directToolCalls:I?.directToolCalls??0,subagentCount:I?.subagentCount??0,totalDuration:I?.totalDuration??0,mcpComplianceRate:I?.mcpComplianceRate??0,missedTools:I?.missedMcpTools??[],actualFailureCount:I?.failedToolCalls??0,fallbackCount:I?.fallbackCount??0,fallbackReasons:I?.fallbackReasons??[]},metadata:S},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let v=T.reconcileRunningSkillExecutionsForSession(i,p,{closureReason:"session_finalize",...S});for(let I of v)await G("/api/telemetry/skill-execution/complete",{executionId:I.executionId,finishedAt:I.finishedAt,status:I.status,summary:{totalToolCalls:I.totalToolCalls??0,mcpToolCalls:I.mcpToolCalls??0,directToolCalls:I.directToolCalls??0,subagentCount:I.subagentCount??0,totalDuration:I.totalDuration??0,mcpComplianceRate:I.mcpComplianceRate??0,missedTools:I.missedMcpTools??[],actualFailureCount:I.failedToolCalls??0,fallbackCount:I.fallbackCount??0,fallbackReasons:I.fallbackReasons??[]},metadata:S},{fallbackReason:"skill_execution_already_reconciled_locally"});let k=T.getLatestSkillExecutionForSession(i);if(k&&!v.some(I=>I.executionId===k.executionId)&&T.mergeSkillExecutionMetadata(k.executionId,S),n){T.deleteHookReceipt(t);let I=O(t),le=createHash("sha256").update(t).digest("hex").slice(0,12);for(let U of [`session-id-${le}`,"current-execution-id","current-skill.json","event-map.json"])rmSync$1(join(I,U),{force:!0});}T.deleteContextReceipt(t,i);}catch(_){emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"lifecycle_telemetry",reason:F(_),fallback:"fail_open"}});}finally{T?.close();}try{await u.endSession(i),await u.flushAndAggregate();}catch(_){emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"telemetry_flush",reason:F(_),fallback:"local_state_authoritative"}});}}finally{if(f)try{f.close();}catch{}l&&u.close(),m&&s.removeSession(i),emitSemanticControlLog({event:m?"hook.session_end.completed":"hook.session_end.degraded",identity:{projectRoot:t,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 e=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n;}),process.stdin.on("end",async()=>{let n=Ge(t.trim()||process.argv[2]||"");n&&e(JSON.stringify(n)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var Ba=/^\/(?:devflow:)?[\w-]+\b\s*/iu,Ja=/\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,Ga=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,Ka=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function Ie(e){let t=e.trim().replace(Ba,"").trim();return !t||Ja.test(t)?null:(Ka.exec(t)??Ga.exec(t))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}function Va(e){let t=createHash("sha256").update(e).digest("hex").slice(0,16),n=process.env.DEVFLOW_STATE_DIR||join(homedir(),".devflow","state",t);return join(n,"memory-intents.jsonl")}function Ya(e){try{return readFileSync$1(e,"utf8").split(`
15
+ `).filter(Boolean).flatMap(t=>{try{let n=JSON.parse(t);return typeof n.content=="string"&&typeof n.createdAt=="number"?[n]:[]}catch{return []}})}catch{return []}}function zo(e){let t=Va(e),n=`${t}.claim-`,o=`${basename(t)}.claim-`,r=(()=>{try{return readdirSync$1(dirname$1(t)).filter(a=>a.startsWith(o)&&!a.includes(".tmp-")).sort()[0]}catch{return}})(),i=r?join(dirname$1(t),r):`${n}${Date.now()}-${process.pid}`;if(!r)try{renameSync(t,i);}catch{return null}let s=Ya(i);if(s.length===0){try{unlinkSync$1(i);}catch{}return null}return {path:i,intents:s}}function Mt(e){if(e.intents.shift(),e.intents.length===0){try{unlinkSync$1(e.path);}catch{}return}let t=`${e.path}.tmp-${process.pid}`;writeFileSync$1(t,e.intents.map(n=>JSON.stringify(n)).join(`
16
16
  `)+`
17
- `,{mode:384}),renameSync(t,e.path);}function Ke(e){let t=e.trim().replace(/^\//,"");if(!t.startsWith("devflow:"))return null;let n=t.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(n)?`devflow:${n.toLowerCase()}`:null}function Bo(e){let t=e.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!t)return null;let n=Ke(t[1]);return n?{rawName:t[1],skillName:n}:null}function we(e,t){return t?`evt_tool_${createHash$1("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var be=1,Nt="memory-snapshot-v1.json",or=512*1024,rr=256*1024,ir=2e3,nc=500,oc=10,rc=240,ic=300*1e3,sc=720*60*60*1e3,sr=2147483647,ac=100,Vo=250,cc=3e4,dc=10,Ve=new Map;function ar(e){return e.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:e.ownerUid===e.currentUid,modeSafe:(e.mode&18)===0}}function Y(e){return resolve(e)}function ie(e){return createHash("sha256").update(Y(e)).digest("hex").slice(0,16)}function Lt(e,t={}){let n=ie(e),o=t.stateRoot?join(t.stateRoot,n):getProjectStateDir(Y(e));return join(o,Nt)}function Qe(e,t){let o=(e instanceof Error?e.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return o?`${t}:${o}`:t}function Wt(e,t){return Array.isArray(e)&&e.length<=t&&e.every(n=>typeof n=="string"&&n.length>0&&n.length<=512)}function lc(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return typeof t.id=="string"&&t.id.length>0&&t.id.length<=512&&typeof t.kind=="string"&&t.kind.length>0&&t.kind.length<=128&&(t.family===void 0||typeof t.family=="string"&&t.family.length>0&&t.family.length<=256)&&(t.entity===void 0||typeof t.entity=="string"&&t.entity.length>0&&t.entity.length<=256)&&Wt(t.memoryIds,100)&&(t.status==="withheld"||t.status==="resolved")&&(t.summary===void 0||typeof t.summary=="string"&&t.summary.length<=2e3)}function uc(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return typeof t.reason=="string"&&t.reason.length>0&&t.reason.length<=512&&(t.stale===void 0||typeof t.stale=="boolean")}function qt(e,t,n){if(!e||typeof e!="object"||Array.isArray(e))return null;let o=e,r=Y(t),i=ie(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")>rr||!Wt(o.memoryIds,ir)||!Array.isArray(o.conflicts)||o.conflicts.length>nc||!o.conflicts.every(lc)||typeof o.generatedAt!="number"||!Number.isFinite(o.generatedAt)||o.generatedAt<0||o.generatedAt>n+ic||!Number.isInteger(s)||s<0||s>sr||!["ready","pending","degraded","disabled"].includes(String(o.status))||o.degradation!==void 0&&!uc(o.degradation)?null:{...o,generation:s}}function Ut(e,t,n,o,r=0){let i=Y(e);return {version:be,projectRoot:i,projectHash:ie(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:o,generation:r,status:t,degradation:{reason:n}}}function oe(e,t={}){let n=t.now??Date.now(),o=Lt(e,t),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>or)throw new Error("cache_size_invalid");let s=ar({...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=qt(a,e,n);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&n-c.generatedAt>sc?{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:Ut(e,a?"pending":"degraded",a?"cache_missing":Qe(i,"cache_invalid"),n),source:"none",valid:false,stale:false}}finally{if(r!==void 0)try{closeSync$1(r);}catch{}}}function Yo(e){if(!Number.isInteger(e)||e<0||e>=sr)throw new Error("memory_snapshot_generation_exhausted");return e+1}function mc(e){let t=dirname$1(e);mkdirSync$1(t,{recursive:true,mode:448}),chmodSync(t,448);}function pc(e){mc(e);let t=`${e}.lock`,n={pid:process.pid,createdAt:Date.now(),token:randomUUID$1()},o=JSON.stringify(n),r;try{return r=openSync$1(t,"wx",384),writeFileSync$1(r,o),fsyncSync(r),{fd:r,path:t,contents:o}}catch(i){if(r!==void 0){try{closeSync$1(r);}catch{}try{unlinkSync$1(t);}catch{}}if(i.code==="EEXIST")return null;throw i}}function fc(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return Number.isInteger(t.pid)&&Number(t.pid)>0&&typeof t.createdAt=="number"&&Number.isFinite(t.createdAt)&&typeof t.token=="string"&&t.token.length>0}function gc(e){try{return process.kill(e,0),!1}catch(t){return t.code==="ESRCH"}}function hc(e){return !e.canonicalCachePath||!e.directoryIsSafe||!e.lockIsRegularFile||!e.metadataValid||!e.contentsUnchanged||!e.ownerDead&&!e.stale?false:e.currentUid!==void 0?e.directoryUid===e.currentUid&&e.lockUid===e.currentUid:true}function yc(e){return isAbsolute(e)&&resolve(e)===e&&basename(e)===Nt&&/^[a-f0-9]{16}$/u.test(basename(dirname$1(e)))}function _c(e,t){let n=`${e}.lock`;try{let o=lstatSync$1(dirname$1(e)),r=lstatSync$1(n),i=readFileSync$1(n,"utf8"),s=null;try{let g=JSON.parse(i);fc(g)&&(s=g);}catch{}let a=s?.createdAt??r.mtimeMs,c=Date.now()-a>t,d=s?gc(s.pid):!1,l=readFileSync$1(n,"utf8")===i,u=typeof process.getuid=="function"?process.getuid():void 0,p=ar({...u!==void 0?{currentUid:u}:{},ownerUid:o.uid,mode:o.mode});return hc({canonicalCachePath:yc(e),directoryIsSafe:o.isDirectory()&&!o.isSymbolicLink()&&p.modeSafe,lockIsRegularFile:r.isFile()&&!r.isSymbolicLink(),metadataValid:s!==null,ownerDead:d,stale:c,contentsUnchanged:l,...u!==void 0?{currentUid:u}:{},directoryUid:o.uid,lockUid:r.uid})?(unlinkSync$1(n),!0):!1}catch{return false}}function vc(e){try{closeSync$1(e.fd);}catch{}try{readFileSync$1(e.path,"utf8")===e.contents&&unlinkSync$1(e.path);}catch{}}function Ic(e){return new Promise(t=>setTimeout(t,e))}function Ot(e,t,n,o){let r=Number.isFinite(e)?Math.floor(e):t;return Math.min(o,Math.max(n,r))}async function wc(e,t){let n=Ot(t.lockTimeoutMs,ac,0,Vo),o=Ot(t.lockRetryMs,dc,1,Vo),r=Ot(t.lockStaleMs,cc,0,Number.MAX_SAFE_INTEGER),i=Date.now()+n;for(;;){let s=pc(e);if(s)return s;if(_c(e,r))continue;let a=i-Date.now();if(a<=0)throw new Error("memory_snapshot_cache_lock_timeout");await Ic(Math.min(o,a));}}async function Qo(e,t,n){let o=await wc(e,t);try{return await n()}finally{vc(o);}}function Xo(e,t,n,o){let r=o.now??Date.now(),i=Y(e),s={version:be,projectRoot:i,projectHash:ie(i),markdown:t.markdown,memoryIds:t.memoryIds??[],conflicts:t.conflicts??[],generatedAt:r,generation:n,status:t.status??"ready",...t.degradation?{degradation:t.degradation}:{}};if(!qt(s,e,r))throw new Error("memory_snapshot_payload_invalid");let a=JSON.stringify(s);if(Buffer.byteLength(a,"utf8")>or)throw new Error("memory_snapshot_cache_too_large");let c=Lt(e,o),d=dirname$1(c);mkdirSync$1(d,{recursive:true,mode:448}),chmodSync(d,448);let l=join(d,`.${Nt}.${process.pid}.${randomUUID$1()}.tmp`),u;try{u=openSync$1(l,"wx",384),writeFileSync$1(u,a),fsyncSync(u),closeSync$1(u),u=void 0,chmodSync(l,384),renameSync(l,c),chmodSync(c,384);let p;try{p=openSync$1(d,"r");try{fsyncSync(p);}catch{}}finally{p!==void 0&&closeSync$1(p);}return s}finally{if(u!==void 0)try{closeSync$1(u);}catch{}rmSync$1(l,{force:true});}}function kc(e,t){let o=(Ve.get(e)??Promise.resolve()).catch(()=>{}).then(t),r=o.then(()=>{},()=>{});return Ve.set(e,r),o.finally(()=>{Ve.get(e)===r&&Ve.delete(e);})}function Pt(e,t,n,o,r){return e.valid?e.snapshot.generation>r?{...e,persisted:false}:{...e,snapshot:{...e.snapshot,status:"degraded",degradation:{reason:n,stale:e.stale||void 0}},persisted:false}:{snapshot:Ut(t,"degraded",n,o,r),source:"none",valid:false,stale:false,persisted:false}}async function zt(e){let t=Lt(e.projectRoot,e.cacheOptions);return kc(t,async()=>{let n=oe(e.projectRoot,e.cacheOptions),o=n.valid?n.snapshot.generation:0,r;try{r=await e.load();}catch(i){let s=Qe(i,`refresh_failed:${e.reason}`);try{return await Qo(t,e.cacheOptions??{},()=>{let a=oe(e.projectRoot,e.cacheOptions);if(a.valid)return Pt(a,e.projectRoot,s,e.cacheOptions?.now??Date.now(),o);let c=Yo(o),d=Ut(e.projectRoot,"degraded",s,e.cacheOptions?.now??Date.now(),c);return {snapshot:Xo(e.projectRoot,d,c,e.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(a){let c=oe(e.projectRoot,e.cacheOptions);return Pt(c,e.projectRoot,Qe(a,s),e.cacheOptions?.now??Date.now(),o)}}try{return await Qo(t,e.cacheOptions??{},()=>{let i=oe(e.projectRoot,e.cacheOptions);if(i.valid&&i.snapshot.generation>o)return {...i,persisted:!1};let s=Yo(Math.max(o,i.valid?i.snapshot.generation:0));return {snapshot:Xo(e.projectRoot,r,s,e.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(i){let s=oe(e.projectRoot,e.cacheOptions);return Pt(s,e.projectRoot,Qe(i,`refresh_commit_failed:${e.reason}`),e.cacheOptions?.now??Date.now(),o)}})}async function et(e){return zt({projectRoot:e.projectRoot,reason:e.reason,cacheOptions:e.cacheOptions,load:async()=>{if(e.injectConfig===false)return {status:"disabled",markdown:"",memoryIds:[],conflicts:[]};let t=typeof e.injectConfig=="object"?e.injectConfig:{},n=Number.isFinite(t.topN)?Math.max(0,Math.floor(t.topN)):4,o=Number.isFinite(t.budgetTokens)?Math.max(1,Math.floor(t.budgetTokens)):400,r=await e.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(u=>({id:u.id,kind:u.kind,family:u.family,entity:u.entity,memoryIds:u.memoryIds,status:u.status,...u.summary?{summary:u.summary}:{}})),l=a?`## Project memory
17
+ `,{mode:384}),renameSync(t,e.path);}function Ke(e){let t=e.trim().replace(/^\//,"");if(!t.startsWith("devflow:"))return null;let n=t.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(n)?`devflow:${n.toLowerCase()}`:null}function Bo(e){let t=e.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!t)return null;let n=Ke(t[1]);return n?{rawName:t[1],skillName:n}:null}function we(e,t){return t?`evt_tool_${createHash$1("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var be=1,Nt="memory-snapshot-v1.json",or=512*1024,rr=256*1024,ir=2e3,rc=500,ic=10,sc=240,ac=300*1e3,cc=720*60*60*1e3,sr=2147483647,dc=100,Vo=250,lc=3e4,uc=10,Ve=new Map;function ar(e){return e.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:e.ownerUid===e.currentUid,modeSafe:(e.mode&18)===0}}function Y(e){return resolve(e)}function ie(e){return createHash("sha256").update(Y(e)).digest("hex").slice(0,16)}function Lt(e,t={}){let n=ie(e),o=t.stateRoot?join(t.stateRoot,n):getProjectStateDir(Y(e));return join(o,Nt)}function Qe(e,t){let o=(e instanceof Error?e.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return o?`${t}:${o}`:t}function Wt(e,t){return Array.isArray(e)&&e.length<=t&&e.every(n=>typeof n=="string"&&n.length>0&&n.length<=512)}function mc(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return typeof t.id=="string"&&t.id.length>0&&t.id.length<=512&&typeof t.kind=="string"&&t.kind.length>0&&t.kind.length<=128&&(t.family===void 0||typeof t.family=="string"&&t.family.length>0&&t.family.length<=256)&&(t.entity===void 0||typeof t.entity=="string"&&t.entity.length>0&&t.entity.length<=256)&&Wt(t.memoryIds,100)&&(t.status==="withheld"||t.status==="resolved")&&(t.summary===void 0||typeof t.summary=="string"&&t.summary.length<=2e3)}function pc(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return typeof t.reason=="string"&&t.reason.length>0&&t.reason.length<=512&&(t.stale===void 0||typeof t.stale=="boolean")}function qt(e,t,n){if(!e||typeof e!="object"||Array.isArray(e))return null;let o=e,r=Y(t),i=ie(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")>rr||!Wt(o.memoryIds,ir)||!Array.isArray(o.conflicts)||o.conflicts.length>rc||!o.conflicts.every(mc)||typeof o.generatedAt!="number"||!Number.isFinite(o.generatedAt)||o.generatedAt<0||o.generatedAt>n+ac||!Number.isInteger(s)||s<0||s>sr||!["ready","pending","degraded","disabled"].includes(String(o.status))||o.degradation!==void 0&&!pc(o.degradation)?null:{...o,generation:s}}function Ut(e,t,n,o,r=0){let i=Y(e);return {version:be,projectRoot:i,projectHash:ie(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:o,generation:r,status:t,degradation:{reason:n}}}function oe(e,t={}){let n=t.now??Date.now(),o=Lt(e,t),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>or)throw new Error("cache_size_invalid");let s=ar({...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=qt(a,e,n);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&n-c.generatedAt>cc?{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:Ut(e,a?"pending":"degraded",a?"cache_missing":Qe(i,"cache_invalid"),n),source:"none",valid:false,stale:false}}finally{if(r!==void 0)try{closeSync$1(r);}catch{}}}function Yo(e){if(!Number.isInteger(e)||e<0||e>=sr)throw new Error("memory_snapshot_generation_exhausted");return e+1}function fc(e){let t=dirname$1(e);mkdirSync$1(t,{recursive:true,mode:448}),chmodSync(t,448);}function gc(e){fc(e);let t=`${e}.lock`,n={pid:process.pid,createdAt:Date.now(),token:randomUUID$1()},o=JSON.stringify(n),r;try{return r=openSync$1(t,"wx",384),writeFileSync$1(r,o),fsyncSync(r),{fd:r,path:t,contents:o}}catch(i){if(r!==void 0){try{closeSync$1(r);}catch{}try{unlinkSync$1(t);}catch{}}if(i.code==="EEXIST")return null;throw i}}function hc(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return Number.isInteger(t.pid)&&Number(t.pid)>0&&typeof t.createdAt=="number"&&Number.isFinite(t.createdAt)&&typeof t.token=="string"&&t.token.length>0}function yc(e){try{return process.kill(e,0),!1}catch(t){return t.code==="ESRCH"}}function vc(e){return !e.canonicalCachePath||!e.directoryIsSafe||!e.lockIsRegularFile||!e.metadataValid||!e.contentsUnchanged||!e.ownerDead&&!e.stale?false:e.currentUid!==void 0?e.directoryUid===e.currentUid&&e.lockUid===e.currentUid:true}function _c(e){return isAbsolute(e)&&resolve(e)===e&&basename(e)===Nt&&/^[a-f0-9]{16}$/u.test(basename(dirname$1(e)))}function Ic(e,t){let n=`${e}.lock`;try{let o=lstatSync$1(dirname$1(e)),r=lstatSync$1(n),i=readFileSync$1(n,"utf8"),s=null;try{let f=JSON.parse(i);hc(f)&&(s=f);}catch{}let a=s?.createdAt??r.mtimeMs,c=Date.now()-a>t,d=s?yc(s.pid):!1,u=readFileSync$1(n,"utf8")===i,l=typeof process.getuid=="function"?process.getuid():void 0,m=ar({...l!==void 0?{currentUid:l}:{},ownerUid:o.uid,mode:o.mode});return vc({canonicalCachePath:_c(e),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 wc(e){try{closeSync$1(e.fd);}catch{}try{readFileSync$1(e.path,"utf8")===e.contents&&unlinkSync$1(e.path);}catch{}}function kc(e){return new Promise(t=>setTimeout(t,e))}function Ot(e,t,n,o){let r=Number.isFinite(e)?Math.floor(e):t;return Math.min(o,Math.max(n,r))}async function bc(e,t){let n=Ot(t.lockTimeoutMs,dc,0,Vo),o=Ot(t.lockRetryMs,uc,1,Vo),r=Ot(t.lockStaleMs,lc,0,Number.MAX_SAFE_INTEGER),i=Date.now()+n;for(;;){let s=gc(e);if(s)return s;if(Ic(e,r))continue;let a=i-Date.now();if(a<=0)throw new Error("memory_snapshot_cache_lock_timeout");await kc(Math.min(o,a));}}async function Qo(e,t,n){let o=await bc(e,t);try{return await n()}finally{wc(o);}}function Xo(e,t,n,o){let r=o.now??Date.now(),i=Y(e),s={version:be,projectRoot:i,projectHash:ie(i),markdown:t.markdown,memoryIds:t.memoryIds??[],conflicts:t.conflicts??[],generatedAt:r,generation:n,status:t.status??"ready",...t.degradation?{degradation:t.degradation}:{}};if(!qt(s,e,r))throw new Error("memory_snapshot_payload_invalid");let a=JSON.stringify(s);if(Buffer.byteLength(a,"utf8")>or)throw new Error("memory_snapshot_cache_too_large");let c=Lt(e,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 Rc(e,t){let o=(Ve.get(e)??Promise.resolve()).catch(()=>{}).then(t),r=o.then(()=>{},()=>{});return Ve.set(e,r),o.finally(()=>{Ve.get(e)===r&&Ve.delete(e);})}function Pt(e,t,n,o,r){return e.valid?e.snapshot.generation>r?{...e,persisted:false}:{...e,snapshot:{...e.snapshot,status:"degraded",degradation:{reason:n,stale:e.stale||void 0}},persisted:false}:{snapshot:Ut(t,"degraded",n,o,r),source:"none",valid:false,stale:false,persisted:false}}async function zt(e){let t=Lt(e.projectRoot,e.cacheOptions);return Rc(t,async()=>{let n=oe(e.projectRoot,e.cacheOptions),o=n.valid?n.snapshot.generation:0,r;try{r=await e.load();}catch(i){let s=Qe(i,`refresh_failed:${e.reason}`);try{return await Qo(t,e.cacheOptions??{},()=>{let a=oe(e.projectRoot,e.cacheOptions);if(a.valid)return Pt(a,e.projectRoot,s,e.cacheOptions?.now??Date.now(),o);let c=Yo(o),d=Ut(e.projectRoot,"degraded",s,e.cacheOptions?.now??Date.now(),c);return {snapshot:Xo(e.projectRoot,d,c,e.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(a){let c=oe(e.projectRoot,e.cacheOptions);return Pt(c,e.projectRoot,Qe(a,s),e.cacheOptions?.now??Date.now(),o)}}try{return await Qo(t,e.cacheOptions??{},()=>{let i=oe(e.projectRoot,e.cacheOptions);if(i.valid&&i.snapshot.generation>o)return {...i,persisted:!1};let s=Yo(Math.max(o,i.valid?i.snapshot.generation:0));return {snapshot:Xo(e.projectRoot,r,s,e.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(i){let s=oe(e.projectRoot,e.cacheOptions);return Pt(s,e.projectRoot,Qe(i,`refresh_commit_failed:${e.reason}`),e.cacheOptions?.now??Date.now(),o)}})}async function et(e){return zt({projectRoot:e.projectRoot,reason:e.reason,cacheOptions:e.cacheOptions,load:async()=>{if(e.injectConfig===false)return {status:"disabled",markdown:"",memoryIds:[],conflicts:[]};let t=typeof e.injectConfig=="object"?e.injectConfig:{},n=Number.isFinite(t.topN)?Math.max(0,Math.floor(t.topN)):4,o=Number.isFinite(t.budgetTokens)?Math.max(1,Math.floor(t.budgetTokens)):400,r=await e.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
18
18
  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
19
19
  ${d.length} explicit preference conflict(s) are withheld from automatic guidance; an explicit choice is required.`:r.memories.length===0?`## Project memory
20
20
  \u672C\u9879\u76EE\u6682\u65E0\u8BB0\u5FC6`:`## Project memory (auto-injected, ${r.memories.length} items, ${r.tokenCount} tokens)
21
- ${r.memories.map(u=>`- **${u.title||u.type}**: ${u.content} (confidence ${u.confidence.toFixed(2)}, ${u.source})`).join(`
22
- `)}`;return {status:a?"degraded":"ready",markdown:l,memoryIds:r.memories.map(u=>u.id),conflicts:d,...a?{degradation:{reason:c}}:{}}}})}function bc(e){if(!e)return true;try{return JSON.parse(readFileSync$1(e,"utf8")).sessionStart?.injectMemories??!0}catch{return true}}function Rc(e,t,n){if(!t.trim())return null;try{let o=JSON.parse(t);if(o.status!=="ok"&&o.status!=="degraded")return null;if(o.enabled===!1){let i=Y(e);return {version:be,projectRoot:i,projectHash:ie(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"disabled"}}let r=qt(o.snapshot,e,n);if(r)return r;if(o.status==="ok"&&typeof o.markdown=="string"&&o.markdown.length>0&&Buffer.byteLength(o.markdown,"utf8")<=rr){let i=Y(e);return {version:be,projectRoot:i,projectHash:ie(i),markdown:o.markdown,memoryIds:Wt(o.memoryIds,ir)?o.memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"ready"}}}catch{}return null}function jt(e,t){return [...(e??t).replace(/[\r\n\t|]+/gu," ").trim()||t].slice(0,rc).join("")}function Sc(e){if(e.length===0)return "";let t=e.slice(0,oc),n=t.map(o=>{let r=jt(o.family,"unknown"),i=jt(o.entity,"unknown"),s=jt(o.summary,"Explicit choice required.");return `- family=${r}; entity=${i}; status=${o.status}; summary=${s}`});return e.length>t.length&&n.push(`- ${e.length-t.length} additional conflict(s) omitted from SessionStart output.`),`## Withheld preference conflicts (${e.length})
21
+ ${r.memories.map(l=>`- **${l.title||l.type}**: ${l.content} (confidence ${l.confidence.toFixed(2)}, ${l.source})`).join(`
22
+ `)}`;return {status:a?"degraded":"ready",markdown:u,memoryIds:r.memories.map(l=>l.id),conflicts:d,...a?{degradation:{reason:c}}:{}}}})}function Sc(e){if(!e)return true;try{return JSON.parse(readFileSync$1(e,"utf8")).sessionStart?.injectMemories??!0}catch{return true}}function xc(e,t,n){if(!t.trim())return null;try{let o=JSON.parse(t);if(o.status!=="ok"&&o.status!=="degraded")return null;if(o.enabled===!1){let i=Y(e);return {version:be,projectRoot:i,projectHash:ie(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"disabled"}}let r=qt(o.snapshot,e,n);if(r)return r;if(o.status==="ok"&&typeof o.markdown=="string"&&o.markdown.length>0&&Buffer.byteLength(o.markdown,"utf8")<=rr){let i=Y(e);return {version:be,projectRoot:i,projectHash:ie(i),markdown:o.markdown,memoryIds:Wt(o.memoryIds,ir)?o.memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"ready"}}}catch{}return null}function jt(e,t){return [...(e??t).replace(/[\r\n\t|]+/gu," ").trim()||t].slice(0,sc).join("")}function Ec(e){if(e.length===0)return "";let t=e.slice(0,ic),n=t.map(o=>{let r=jt(o.family,"unknown"),i=jt(o.entity,"unknown"),s=jt(o.summary,"Explicit choice required.");return `- family=${r}; entity=${i}; status=${o.status}; summary=${s}`});return e.length>t.length&&n.push(`- ${e.length-t.length} additional conflict(s) omitted from SessionStart output.`),`## Withheld preference conflicts (${e.length})
23
23
  ${n.join(`
24
- `)}`}function xc(e){let t=e.now??Date.now();if(bc(e.configPath)===false)return "";let n=Rc(e.projectRoot,e.daemonResponse??"",t),o=n?{snapshot:n,source:"daemon"}:oe(e.projectRoot,{...e.cacheOptions,now:t}),{snapshot:r}=o;if(r.status==="disabled")return `## Project memory
25
- 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=Sc(r.conflicts);return r.markdown?[r.markdown,c,a].filter(Boolean).join(`
24
+ `)}`}function Tc(e){let t=e.now??Date.now();if(Sc(e.configPath)===false)return "";let n=xc(e.projectRoot,e.daemonResponse??"",t),o=n?{snapshot:n,source:"daemon"}:oe(e.projectRoot,{...e.cacheOptions,now:t}),{snapshot:r}=o;if(r.status==="disabled")return `## Project memory
25
+ 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=Ec(r.conflicts);return r.markdown?[r.markdown,c,a].filter(Boolean).join(`
26
26
  `):["## Project memory",c,`${a} Memory availability is not yet known; do not conclude that the project has no memories.`].filter(Boolean).join(`
27
- `)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,e,t,n]=process.argv;e!=="session-start"||!t?process.exitCode=2:process.stdout.write(xc({projectRoot:t,configPath:n,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var Tc=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu,Ac=/(?:记住|记下|保存|持久化|跨会话|以后|始终|永远|统一使用|项目约定|团队约定|偏好|决定采用|保留可复用|提炼结论|沉淀|记录(?:下来|为|成)?(?:架构|规则|约定|知识|结论))|\b(?:remember|memorize|persist|across sessions|from now on|always|project convention|team convention|preference|we use|adopt|retain reusable|distill)\b/iu,Cc=/(?:分析|审查|检查|评估|性能|生成|创建|新建|添加|编写|实现|开发|设计|撰写|总结|修改|重构|修复|调试|解释|查看)|\b(?:analy[sz]e|review|inspect|audit|performance|generate|create|add|build|implement|develop|design|write|summarize|modify|refactor|fix|debug|explain)\b/iu;function Dc(e){let t=e.trim();return t.length>0&&!Tc.test(t)}function Mc(e){let t=e.normalize("NFKC").trim();return t.length>=4&&Cc.test(t)&&!Ac.test(t)&&Ie(t)===null}function Oc(e,t,n=Date.now()){let o=createHash("sha256").update(t.trim()).digest("hex"),r=createHash("sha256").update(`${e}\0${n}\0${o}`).digest("hex").slice(0,24);return {turnId:`turn:${r}`,eventId:`memory-turn:${r}`,promptHash:o,createdAt:n}}function xe(e,t,n=[]){return `memory-receipt:${createHash("sha256").update(`${e}\0${t}\0${[...n].sort().join("\0")}`).digest("hex").slice(0,24)}`}function tt(e){return `DevFlow memory decision required for ${e.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. 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(e){let t=e.memoryIds.length>0?e.memoryIds.join(","):"none",n=e.status==="committed"?"accepted":e.status,o=e.status==="committed"?"; indexStatus=pending":"",r=e.memoryIds.some(a=>a.startsWith("raw-memory:")),i=e.status==="committed"&&e.source==="explicit_intent"&&!r?"; memoryOnlyCompleted=true; skipProjectContext=true; hostRefinementRequired=true":e.status==="committed"&&e.source==="explicit_intent"?"; asyncReadiness=queued; hostRefinementRequired=true":"",s=e.status==="committed"&&e.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=${e.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=${e.receiptId??"missing"}; turnId=${e.turnId}; memoryIds=${t}; source=${e.source??"unknown"}${o}${i}.`+s}function Bt(e){if(!Dc(e.prompt))return null;let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let n=e.prompt.trim().slice(0,4e3),o=createHash("sha256").update(n).digest("hex"),r=t.listMemoryTurns(e.projectRoot,e.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}:e.identity??Oc(e.sessionId,n),s=r??t.beginMemoryTurn({...i,projectRoot:e.projectRoot,sessionId:e.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:Re(s),skipSkillRouting:s.source==="explicit_intent"};let a=Ie(n)??void 0;if(!a&&Mc(n)){let l=xe(s.turnId,"skipped"),u=t.skipMemoryTurn({turnId:s.turnId,receiptId:l,source:"automatic_transient_skip",reason:"high_confidence_transient_task"});return C({projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,kind:"memory.skipped",payload:{receiptId:l,reasonCode:"high_confidence_transient_task"},dedupeKey:l,producer:"devflow-memory-turn"}),emitSemanticControlLog({event:"memory.semantic.decided",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId},level:"info",timestamp:Date.now(),data:{status:"semantic_empty",operation:"none",reason:"high_confidence_transient_task"}}),{turn:u,additionalContext:Re(u),skipSkillRouting:!1}}let c=a?"commit_explicit":"capture_prompt",d=t.enqueueWork({idempotencyKey:`memory-turn:${c}:${s.turnId}`,kind:a?"memory.explicit_commit":"memory.turn_capture",projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,payload:{operation:c,turnId:s.turnId,eventId:s.eventId,sessionId:e.sessionId,prompt:n,explicitContent:a,createdAt:s.createdAt}});if(a){let l=`raw-memory:${createHash("sha256").update(`${e.projectRoot}\0${i.turnId}\0${a}`).digest("hex").slice(0,24)}`,u=xe(s.turnId,"committed",[l]),p=t.commitMemoryTurn({turnId:s.turnId,receiptId:u,memoryIds:[l],source:"explicit_intent",reason:"explicit_raw_queued",decidedAt:Date.now()});return C({projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,kind:"durable_work.owned",payload:{workId:d.id,obligation:"memory"},dedupeKey:`${d.id}:owned`,producer:"devflow-memory-turn"}),C({projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,kind:"memory.committed",payload:{receiptId:u,reasonCode:"explicit_raw_queued"},dedupeKey:u,producer:"devflow-memory-turn"}),emitSemanticControlLog({event:"memory.write.completed",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,actionReceipt:u},level:"info",timestamp:Date.now(),data:{stage:"explicit_fast_ack",durable:!0,rawMemoryId:l,receiptLatencyMs:Date.now()-i.createdAt,asyncReadiness:"queued"}}),{turn:p,explicitContent:a,additionalContext:Re(p),skipSkillRouting:!0}}return C({projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,kind:"memory.pending",payload:{reasonCode:"semantic_decision_queued"},dedupeKey:`${s.turnId}:pending`,producer:"devflow-memory-turn"}),C({projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,kind:"durable_work.owned",payload:{workId:d.id,obligation:"memory"},dedupeKey:`${d.id}:owned`,producer:"devflow-memory-turn"}),{turn:s,explicitContent:a,additionalContext:tt(s),skipSkillRouting:!1}}finally{t.close();}}async function Jt(e){let{payload:t,memory:n,projectRoot:o}=e,r=openGlobalDevFlowDatabase();try{let i=r.getMemoryTurn(t.turnId);if(!i)throw new Error(`Memory turn ${t.turnId} does not exist`);let s=t.operation==="commit_explicit"&&i.status==="committed"&&i.source==="explicit_intent"&&i.memoryIds.some(u=>u.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(t.prompt,t.sessionId,t.prompt.slice(0,200)),await n.recordEvent({id:t.eventId,sessionId:t.sessionId,tool:"UserPromptSubmit",kind:"user_message",payload:{prompt:t.prompt,turnId:t.turnId},createdAt:t.createdAt}),t.operation==="capture_prompt"||!t.explicitContent)return {turn:i,additionalContext:tt(i),skipSkillRouting:!1};let a=await n.saveExplicitMemoryIntent(t.explicitContent,t.sessionId,t.eventId),c=[...new Set([a.id,...a.relatedMemoryIds??[]])];emitSemanticControlLog({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),l=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"}),emitSemanticControlLog({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(u){emitSemanticControlLog({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:t.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"lineage_finalize",reason:u.message,fallback:"session_end_reconciliation"}});}try{await n.enrichExplicitMemoryObservation(a.id);}catch(u){emitSemanticControlLog({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:t.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"explicit_enrichment",memoryId:a.id,reason:u.message,fallback:"durable_work_queue"}}),r.enqueueWork({idempotencyKey:`explicit-enrichment:${o}:${a.id}`,kind:"memory.explicit_enrichment",projectRoot:o,sessionId:t.sessionId,turnId:l.turnId,payload:{observationId:a.id},maxAttempts:20});}r.enqueueWork({idempotencyKey:`vector:${o}:${a.id}`,kind:"memory.vector_backfill",projectRoot:o,sessionId:t.sessionId,turnId:l.turnId,payload:{observationId:a.id},maxAttempts:20});try{await et({projectRoot:o,memory:n,injectConfig:loadConfig(o).sessionStart?.injectMemories,reason:"explicit_memory_commit"});}catch(u){emitSemanticControlLog({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:t.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"snapshot_refresh",reason:u.message,fallback:"durable_memory_authoritative"}});}return {turn:l,explicitContent:t.explicitContent,additionalContext:Re(l),skipSkillRouting:!0}}finally{r.close();}}var Fc=new Set(["Write","Edit","NotebookEdit"]),dr="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 fr(e){if(!Fc.has(e.toolName))return null;let t=$c(e.toolInput);if(!t)return null;let n=Hc(t,e.projectRoot),o=resolve(e.projectRoot,".claude");if(lr(n,o)&&basename(n).toLocaleUpperCase("en-US")==="MEMORY.MD")return dr;let r=resolve(e.home??homedir(),".claude","projects");return lr(n,r)&&relative(r,n).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?dr:null}function $c(e){for(let t of ["file_path","notebook_path","path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n.trim()}return null}function Hc(e,t){return resolve(isAbsolute(e)?e:resolve(t,e))}function lr(e,t){let n=relative(t,e);return n===""||!n.startsWith(`..${sep}`)&&n!==".."&&!isAbsolute(n)}var zc=1024*1024;function yr(e){let t=join(getProjectStateDir(e),"session-start-pending");mkdirSync$1(t,{recursive:true,mode:448});let n=readdirSync$1(t).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(t,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")>zc)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 _r(e){unlinkSync$1(e.path);}function vr(e){let t=e.path.replace(/\.claim-\d+$/u,"");try{renameSync(e.path,t);}catch{}}function wr(e,t){let n=Sr(e);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({...t,prompt:t.prompt.trim().slice(0,4e3)}),{mode:384}),renameSync(i,r),o}function kr(e){let t=Sr(e);mkdirSync$1(t,{recursive:true,mode:448});let n=readdirSync$1(t).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(t,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 br(e){unlinkSync$1(e.path);}function Rr(e){try{renameSync(e.path,e.path.replace(/\.claim-\d+$/u,""));}catch{}}function Sr(e){return join(M(e),"memory-turn-pending")}var x=class extends Error{constructor(t,n){super(n),this.name="PermanentWorkError",this.category=t;}},Xc=1e3,Zc=3e4,ed=1,td=5*6e4,ot=class{constructor(t){this.timer=null;this.draining=null;this.stopped=true;this.projectRoot=t.projectRoot,this.handlers=t.handlers,this.pollIntervalMs=Qt(t.pollIntervalMs,Xc),this.leaseMs=Qt(t.leaseMs,Zc),this.batchSize=Qt(t.batchSize,ed),this.owner=t.owner??`hook-daemon:${process.pid}:${randomUUID$1()}`,this.now=t.now??Date.now,this.random=t.random??Math.random,this.openDatabase=t.openDatabase??(()=>openGlobalDevFlowDatabase()),this.afterComplete=t.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(t){return t.trim()?(this.draining&&await this.draining,this.draining=this.performDrain(void 0,new Set([t])).finally(()=>{this.draining=null;}),this.draining):0}schedule(t){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));},t),this.timer.unref());}async performDrain(t,n){let o=Object.keys(this.handlers).filter(i=>!t||t.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(t,n){let o=this.handlers[n.kind];if(!o){t.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(()=>{t.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}),!t.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:t});}catch(i){this.logDegradation("completion_follow_up",i,n);}}catch(i){let s=nd(i);if(i instanceof x||s.permanent){t.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(od(n.attempts,this.random()),s.retryAfterMs??0);if(s.retryWithoutAttempt){t.deferWork(n.id,this.owner,s,a),this.logWorkTransition("deferred",n,{attempt:n.attempts,nextAttemptAt:a,errorCategory:s.category},"warn");return}t.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(t,n,o){emitSemanticControlLog({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_${t}`,workId:o?.id,workKind:o?.kind,reason:xr(n)}});}logWorkTransition(t,n,o,r="info"){try{emitSemanticControlLog({event:"durable.work.transitioned",identity:{projectRoot:this.projectRoot,sessionId:n.sessionId,turnId:n.turnId,executionId:n.executionId},level:r,timestamp:this.now(),data:{stage:t,workId:n.id,workKind:n.kind,...o}});}catch{}}};function Qt(e,t){return Number.isSafeInteger(e)&&e>0?e:t}function nd(e){if(e instanceof x)return {category:e.category,message:e.message};let t=e&&typeof e=="object"?e:null,n=typeof t?.category=="string"?t.category:"runtime_error";return {category:n,message:xr(e),retryAfterMs:typeof t?.retryAfterMs=="number"&&Number.isFinite(t.retryAfterMs)?Math.max(0,t.retryAfterMs):void 0,retryWithoutAttempt:t?.retryWithoutAttempt===true,permanent:n==="policy_verification_failed"||n==="invalid_payload"}}function od(e,t){let n=Math.min(td,500*2**Math.max(0,e-1)),o=Math.floor(n*.2*Math.max(0,Math.min(1,t)));return n+o}function xr(e){return e instanceof Error?e.message:String(e)}var cd=250;function Ar(e,t=process.env){let n=Tr(join(homedir(),".devflow","config.json")),o=Tr(join(e,".devflow","config.json")),r=Xt(t.DEVFLOW_HOOK_PROFILE)??Xt(o.profile)??Xt(n.profile)??"standard",i=Number(t.DEVFLOW_HOOK_ACK_BUDGET_MS??o.acknowledgementBudgetMs??n.acknowledgementBudgetMs),s=Number.isSafeInteger(i)&&i>0?Math.min(i,5e3):cd,a=new Set([...Zt(n.disabledHandlers),...Zt(o.disabledHandlers),...Zt(t.DEVFLOW_DISABLED_HOOK_HANDLERS?.split(","))].map(md).filter(c=>!!c));return {profile:r,acknowledgementBudgetMs:s,disabledHandlers:a}}async function Cr(e,t,n,o,r=process.env.CLAUDE_PROJECT_DIR||process.cwd()){let i,s=new Promise(a=>{i=setTimeout(()=>{emitSemanticControlLog({event:"hook.runtime.degraded",identity:{projectRoot:r},level:"warn",timestamp:Date.now(),data:{stage:"acknowledgement_budget",eventName:e,budgetMs:t,fallback:"timeout_result"}}),a(o());},t),i.unref();});try{return await Promise.race([Promise.resolve().then(n),s])}finally{i&&clearTimeout(i);}}async function Dr(e,t=process.env){let n=t.DEVFLOW_HOST_ADAPTER??(t.CLAUDE_PROJECT_DIR||t.CLAUDE_PLUGIN_ROOT||t.CLAUDE_CODE_ENTRYPOINT?"claude-code":void 0),o=await selectHostAdapter({projectRoot:e,env:t,explicitHost:n});if(o.status==="failed")throw new Error(`host_adapter_selection_failed:${o.code}:${o.reason}`);let r=await o.adapter.capabilities({projectRoot:e,env:t,explicitHost:n});return {hostId:o.adapter.id,capabilities:new Map(r.map(i=>[i.capability,i])),profiles:new Set(o.adapter.hooks?.profileSupport??[])}}function en(e,t,n){let o=ud(e,t.profile);if(!n.profiles.has(t.profile))return {enabled:false,policy:"fail_open",reason:`hook_profile_${t.profile}_unsupported_by_${n.hostId}`,fallback:"host_event_continues_without_devflow_handler"};if(t.disabledHandlers.has(e))return {enabled:false,policy:"fail_open",reason:"hook_handler_disabled",fallback:"host_event_continues_without_devflow_handler"};if(t.profile==="minimal"&&!dd.has(e))return {enabled:false,policy:"fail_open",reason:"hook_handler_not_in_minimal_profile",fallback:"critical_receipts_only"};let r=ld[e];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 dd=new Set(["session-start","user-prompt-submit","stop","session-end","memory-snapshot"]),ld={"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 ud(e,t){return e==="user-prompt-submit"||e==="stop"||e==="session-end"?"enqueue_and_open":e==="pre-tool-use"&&t==="strict"?"fail_closed":"fail_open"}function Tr(e){if(!existsSync(e))return {};try{let n=JSON.parse(readFileSync$1(e,"utf8")).hooks;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return {}}}function Xt(e){return e==="minimal"||e==="standard"||e==="strict"?e:void 0}function Zt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function md(e){let t=e.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"}[t.replace(/-/g,"")]??t)||void 0}function Mr(e){let t=Object.keys(e.handlers).map(n=>{let o=fd[n];return [n,{requestType:n,eventName:o,capability:gd[n],failurePolicy:e.failurePolicy(n),acknowledgeWithinBudget:pd.has(n),handler:e.handlers[n],timeoutResult:()=>hd(n)}]});return new Map(t)}async function Or(e){let t=e.registry.get(e.requestType);if(!t)return {status:"degraded",reason:"unknown_hook_handler",fallback:"host_event_continues"};let n=()=>Promise.resolve(t.handler(e.rawInput));return t.acknowledgeWithinBudget?Cr(t.eventName,e.acknowledgementBudgetMs,n,t.timeoutResult,e.projectRoot):n()}var pd=new Set(["stop","session-end","user-prompt-submit"]),fd={"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"},gd={"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 hd(e){return e==="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:e==="session-end"?"durable_session_recovery":"background_processing"}}var it=class{constructor(t){this.records=new Map;this.path=join(M(t),"hook-handler-health.json"),this.load();}recordSuccess(t,n,o=Date.now()){let r={handler:t,host:n,status:"healthy",consecutiveFailures:0,lastSuccessAt:o,updatedAt:o};return this.records.set(rt(t,n),r),this.persist(),r}recordFailure(t,n,o,r,i=Date.now()){let s=this.records.get(rt(t,n)),a=(s?.consecutiveFailures??0)+1,c=Math.min(5*6e4,1e3*2**Math.min(8,a-1)),d={handler:t,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(t,n),d),this.persist(),d}list(){return [...this.records.values()].sort((t,n)=>t.handler.localeCompare(n.handler))}load(){try{let t=JSON.parse(readFileSync$1(this.path,"utf8"));for(let n of t)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 t=`${this.path}.${process.pid}.tmp`;writeFileSync$1(t,JSON.stringify(this.list(),null,2),{mode:384}),renameSync(t,this.path);}catch{}}};function rt(e,t){return `${t}\0${e}`}function Pr(e,t){return t||(e==="post-tool-use"||e==="post-tool-use-failure"?{status:"ok"}:{status:"ok"})}function jr(e){let t=e instanceof Error?e.message:String(e??"hook_handler_failed");return {category:/timeout|budget|deadline/iu.test(t)?"timeout":/sqlite|database|locked|busy/iu.test(t)?"storage":/socket|connect|unreachable/iu.test(t)?"transport":/json|parse|schema|invalid/iu.test(t)?"protocol":"handler",reason:t}}function Fr(e){let t=xo({projectRoot:e.projectRoot,sessionId:e.sessionId,transcriptPath:e.transcriptPath,runtimeStore:e.runtimeStore}),n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{Ed(e.runtimeStore,e.sessionId,n);let o=n.getPendingMemoryTurn(e.projectRoot,e.sessionId),r=o?n.markMemoryTurnStopPrompted(o.turnId):!1,i=[];t&&i.push(t.reason),o&&r&&i.push(tt(o)),o&&!r&&Sd(n,o.turnId)&&xd(Je(e.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(e.projectRoot,e.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(`
27
+ `)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,e,t,n]=process.argv;e!=="session-start"||!t?process.exitCode=2:process.stdout.write(Tc({projectRoot:t,configPath:n,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var Dc=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu,Mc=/(?:记住|记下|保存|持久化|跨会话|以后|始终|永远|统一使用|项目约定|团队约定|偏好|决定采用|保留可复用|提炼结论|沉淀|记录(?:下来|为|成)?(?:架构|规则|约定|知识|结论))|\b(?:remember|memorize|persist|across sessions|from now on|always|project convention|team convention|preference|we use|adopt|retain reusable|distill)\b/iu,Oc=/(?:分析|审查|检查|评估|性能|生成|创建|新建|添加|编写|实现|开发|设计|撰写|总结|修改|重构|修复|调试|解释|查看)|\b(?:analy[sz]e|review|inspect|audit|performance|generate|create|add|build|implement|develop|design|write|summarize|modify|refactor|fix|debug|explain)\b/iu;function Pc(e){let t=e.trim();return t.length>0&&!Dc.test(t)}function jc(e){let t=e.normalize("NFKC").trim();return t.length>=4&&Oc.test(t)&&!Mc.test(t)&&Ie(t)===null}function Fc(e,t,n=Date.now()){let o=createHash("sha256").update(t.trim()).digest("hex"),r=createHash("sha256").update(`${e}\0${n}\0${o}`).digest("hex").slice(0,24);return {turnId:`turn:${r}`,eventId:`memory-turn:${r}`,promptHash:o,createdAt:n}}function xe(e,t,n=[]){return `memory-receipt:${createHash("sha256").update(`${e}\0${t}\0${[...n].sort().join("\0")}`).digest("hex").slice(0,24)}`}function tt(e){return `DevFlow memory decision required for ${e.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. 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(e){let t=e.memoryIds.length>0?e.memoryIds.join(","):"none",n=e.status==="committed"?"accepted":e.status,o=e.status==="committed"?"; indexStatus=pending":"",r=e.memoryIds.some(a=>a.startsWith("raw-memory:")),i=e.status==="committed"&&e.source==="explicit_intent"&&!r?"; memoryOnlyCompleted=true; skipProjectContext=true; hostRefinementRequired=true":e.status==="committed"&&e.source==="explicit_intent"?"; asyncReadiness=queued; hostRefinementRequired=true":"",s=e.status==="committed"&&e.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=${e.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=${e.receiptId??"missing"}; turnId=${e.turnId}; memoryIds=${t}; source=${e.source??"unknown"}${o}${i}.`+s}function Bt(e){if(!Pc(e.prompt))return null;let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let n=e.prompt.trim().slice(0,4e3),o=createHash("sha256").update(n).digest("hex"),r=t.listMemoryTurns(e.projectRoot,e.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}:e.identity??Fc(e.sessionId,n),s=r??t.beginMemoryTurn({...i,projectRoot:e.projectRoot,sessionId:e.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:Re(s),skipSkillRouting:s.source==="explicit_intent"};let a=resolveSemanticResolutionMode(e.projectRoot),c=a==="off"||a==="shadow"?Ie(n)??void 0:void 0;if(!c&&jc(n)){let l=xe(s.turnId,"skipped"),m=t.skipMemoryTurn({turnId:s.turnId,receiptId:l,source:"automatic_transient_skip",reason:"high_confidence_transient_task"});return D({projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,kind:"memory.skipped",payload:{receiptId:l,reasonCode:"high_confidence_transient_task"},dedupeKey:l,producer:"devflow-memory-turn"}),emitSemanticControlLog({event:"memory.semantic.decided",identity:{projectRoot:e.projectRoot,sessionId:e.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=t.enqueueWork({idempotencyKey:`memory-turn:${d}:${s.turnId}`,kind:c?"memory.explicit_commit":"memory.turn_capture",projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,payload:{operation:d,turnId:s.turnId,eventId:s.eventId,sessionId:e.sessionId,prompt:n,explicitContent:c,createdAt:s.createdAt}});if(c){let l=`raw-memory:${createHash("sha256").update(`${e.projectRoot}\0${i.turnId}\0${c}`).digest("hex").slice(0,24)}`,m=xe(s.turnId,"committed",[l]),f=t.commitMemoryTurn({turnId:s.turnId,receiptId:m,memoryIds:[l],source:"explicit_intent",reason:"explicit_raw_queued",decidedAt:Date.now()});return D({projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,kind:"durable_work.owned",payload:{workId:u.id,obligation:"memory"},dedupeKey:`${u.id}:owned`,producer:"devflow-memory-turn"}),D({projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,kind:"memory.committed",payload:{receiptId:m,reasonCode:"explicit_raw_queued"},dedupeKey:m,producer:"devflow-memory-turn"}),emitSemanticControlLog({event:"memory.write.completed",identity:{projectRoot:e.projectRoot,sessionId:e.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 D({projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,kind:"memory.pending",payload:{reasonCode:"semantic_decision_queued"},dedupeKey:`${s.turnId}:pending`,producer:"devflow-memory-turn"}),D({projectRoot:e.projectRoot,sessionId:e.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:tt(s),skipSkillRouting:!1}}finally{t.close();}}async function Jt(e){let{payload:t,memory:n,projectRoot:o}=e,r=openGlobalDevFlowDatabase();try{let i=r.getMemoryTurn(t.turnId);if(!i)throw new Error(`Memory turn ${t.turnId} does not exist`);let s=t.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(t.prompt,t.sessionId,t.prompt.slice(0,200)),await n.recordEvent({id:t.eventId,sessionId:t.sessionId,tool:"UserPromptSubmit",kind:"user_message",payload:{prompt:t.prompt,turnId:t.turnId},createdAt:t.createdAt}),t.operation==="capture_prompt"||!t.explicitContent)return {turn:i,additionalContext:tt(i),skipSkillRouting:!1};let a=await n.saveExplicitMemoryIntent(t.explicitContent,t.sessionId,t.eventId),c=[...new Set([a.id,...a.relatedMemoryIds??[]])];emitSemanticControlLog({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"});D({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"}),emitSemanticControlLog({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){emitSemanticControlLog({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:t.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){emitSemanticControlLog({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:t.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:t.sessionId,turnId:u.turnId,payload:{observationId:a.id},maxAttempts:20});}r.enqueueWork({idempotencyKey:`vector:${o}:${a.id}`,kind:"memory.vector_backfill",projectRoot:o,sessionId:t.sessionId,turnId:u.turnId,payload:{observationId:a.id},maxAttempts:20});try{await et({projectRoot:o,memory:n,injectConfig:loadConfig(o).sessionStart?.injectMemories,reason:"explicit_memory_commit"});}catch(l){emitSemanticControlLog({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:t.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"snapshot_refresh",reason:l.message,fallback:"durable_memory_authoritative"}});}return {turn:u,explicitContent:t.explicitContent,additionalContext:Re(u),skipSkillRouting:!0}}finally{r.close();}}var Nc=new Set(["Write","Edit","NotebookEdit"]),dr="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 fr(e){if(!Nc.has(e.toolName))return null;let t=Lc(e.toolInput);if(!t)return null;let n=Wc(t,e.projectRoot),o=resolve(e.projectRoot,".claude");if(lr(n,o)&&basename(n).toLocaleUpperCase("en-US")==="MEMORY.MD")return dr;let r=resolve(e.home??homedir(),".claude","projects");return lr(n,r)&&relative(r,n).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?dr:null}function Lc(e){for(let t of ["file_path","notebook_path","path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n.trim()}return null}function Wc(e,t){return resolve(isAbsolute(e)?e:resolve(t,e))}function lr(e,t){let n=relative(t,e);return n===""||!n.startsWith(`..${sep}`)&&n!==".."&&!isAbsolute(n)}var Gc=1024*1024;function yr(e){let t=join(getProjectStateDir(e),"session-start-pending");mkdirSync$1(t,{recursive:true,mode:448});let n=readdirSync$1(t).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(t,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")>Gc)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 vr(e){unlinkSync$1(e.path);}function _r(e){let t=e.path.replace(/\.claim-\d+$/u,"");try{renameSync(e.path,t);}catch{}}function wr(e,t){let n=Sr(e);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({...t,prompt:t.prompt.trim().slice(0,4e3)}),{mode:384}),renameSync(i,r),o}function kr(e){let t=Sr(e);mkdirSync$1(t,{recursive:true,mode:448});let n=readdirSync$1(t).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(t,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 br(e){unlinkSync$1(e.path);}function Rr(e){try{renameSync(e.path,e.path.replace(/\.claim-\d+$/u,""));}catch{}}function Sr(e){return join(O(e),"memory-turn-pending")}var E=class extends Error{constructor(t,n){super(n),this.name="PermanentWorkError",this.category=t;}},td=1e3,nd=3e4,od=1,rd=5*6e4,ot=class{constructor(t){this.timer=null;this.draining=null;this.stopped=true;this.projectRoot=t.projectRoot,this.handlers=t.handlers,this.pollIntervalMs=Qt(t.pollIntervalMs,td),this.leaseMs=Qt(t.leaseMs,nd),this.batchSize=Qt(t.batchSize,od),this.owner=t.owner??`hook-daemon:${process.pid}:${randomUUID$1()}`,this.now=t.now??Date.now,this.random=t.random??Math.random,this.openDatabase=t.openDatabase??(()=>openGlobalDevFlowDatabase()),this.afterComplete=t.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(t){return t.trim()?(this.draining&&await this.draining,this.draining=this.performDrain(void 0,new Set([t])).finally(()=>{this.draining=null;}),this.draining):0}schedule(t){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));},t),this.timer.unref());}async performDrain(t,n){let o=Object.keys(this.handlers).filter(i=>!t||t.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(t,n){let o=this.handlers[n.kind];if(!o){t.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(()=>{t.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}),!t.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:t});}catch(i){this.logDegradation("completion_follow_up",i,n);}}catch(i){let s=id(i);if(i instanceof E||s.permanent){t.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(sd(n.attempts,this.random()),s.retryAfterMs??0);if(s.retryWithoutAttempt){t.deferWork(n.id,this.owner,s,a),this.logWorkTransition("deferred",n,{attempt:n.attempts,nextAttemptAt:a,errorCategory:s.category},"warn");return}t.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(t,n,o){emitSemanticControlLog({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_${t}`,workId:o?.id,workKind:o?.kind,reason:xr(n)}});}logWorkTransition(t,n,o,r="info"){try{emitSemanticControlLog({event:"durable.work.transitioned",identity:{projectRoot:this.projectRoot,sessionId:n.sessionId,turnId:n.turnId,executionId:n.executionId},level:r,timestamp:this.now(),data:{stage:t,workId:n.id,workKind:n.kind,...o}});}catch{}}};function Qt(e,t){return Number.isSafeInteger(e)&&e>0?e:t}function id(e){if(e instanceof E)return {category:e.category,message:e.message};let t=e&&typeof e=="object"?e:null,n=typeof t?.category=="string"?t.category:"runtime_error";return {category:n,message:xr(e),retryAfterMs:typeof t?.retryAfterMs=="number"&&Number.isFinite(t.retryAfterMs)?Math.max(0,t.retryAfterMs):void 0,retryWithoutAttempt:t?.retryWithoutAttempt===true,permanent:n==="policy_verification_failed"||n==="invalid_payload"}}function sd(e,t){let n=Math.min(rd,500*2**Math.max(0,e-1)),o=Math.floor(n*.2*Math.max(0,Math.min(1,t)));return n+o}function xr(e){return e instanceof Error?e.message:String(e)}var ud=250;function Ar(e,t=process.env){let n=Tr(join(homedir(),".devflow","config.json")),o=Tr(join(e,".devflow","config.json")),r=Xt(t.DEVFLOW_HOOK_PROFILE)??Xt(o.profile)??Xt(n.profile)??"standard",i=Number(t.DEVFLOW_HOOK_ACK_BUDGET_MS??o.acknowledgementBudgetMs??n.acknowledgementBudgetMs),s=Number.isSafeInteger(i)&&i>0?Math.min(i,5e3):ud,a=new Set([...Zt(n.disabledHandlers),...Zt(o.disabledHandlers),...Zt(t.DEVFLOW_DISABLED_HOOK_HANDLERS?.split(","))].map(gd).filter(c=>!!c));return {profile:r,acknowledgementBudgetMs:s,disabledHandlers:a}}async function Cr(e,t,n,o,r=process.env.CLAUDE_PROJECT_DIR||process.cwd()){let i,s=new Promise(a=>{i=setTimeout(()=>{emitSemanticControlLog({event:"hook.runtime.degraded",identity:{projectRoot:r},level:"warn",timestamp:Date.now(),data:{stage:"acknowledgement_budget",eventName:e,budgetMs:t,fallback:"timeout_result"}}),a(o());},t),i.unref();});try{return await Promise.race([Promise.resolve().then(n),s])}finally{i&&clearTimeout(i);}}async function Dr(e,t=process.env){let n=t.DEVFLOW_HOST_ADAPTER??(t.CLAUDE_PROJECT_DIR||t.CLAUDE_PLUGIN_ROOT||t.CLAUDE_CODE_ENTRYPOINT?"claude-code":void 0),o=await selectHostAdapter({projectRoot:e,env:t,explicitHost:n});if(o.status==="failed")throw new Error(`host_adapter_selection_failed:${o.code}:${o.reason}`);let r=await o.adapter.capabilities({projectRoot:e,env:t,explicitHost:n});return {hostId:o.adapter.id,capabilities:new Map(r.map(i=>[i.capability,i])),profiles:new Set(o.adapter.hooks?.profileSupport??[])}}function en(e,t,n){let o=fd(e,t.profile);if(!n.profiles.has(t.profile))return {enabled:false,policy:"fail_open",reason:`hook_profile_${t.profile}_unsupported_by_${n.hostId}`,fallback:"host_event_continues_without_devflow_handler"};if(t.disabledHandlers.has(e))return {enabled:false,policy:"fail_open",reason:"hook_handler_disabled",fallback:"host_event_continues_without_devflow_handler"};if(t.profile==="minimal"&&!md.has(e))return {enabled:false,policy:"fail_open",reason:"hook_handler_not_in_minimal_profile",fallback:"critical_receipts_only"};let r=pd[e];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 md=new Set(["session-start","user-prompt-submit","stop","session-end","memory-snapshot"]),pd={"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 fd(e,t){return e==="user-prompt-submit"||e==="stop"||e==="session-end"?"enqueue_and_open":e==="pre-tool-use"&&t==="strict"?"fail_closed":"fail_open"}function Tr(e){if(!existsSync(e))return {};try{let n=JSON.parse(readFileSync$1(e,"utf8")).hooks;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return {}}}function Xt(e){return e==="minimal"||e==="standard"||e==="strict"?e:void 0}function Zt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function gd(e){let t=e.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"}[t.replace(/-/g,"")]??t)||void 0}function Mr(e){let t=Object.keys(e.handlers).map(n=>{let o=yd[n];return [n,{requestType:n,eventName:o,capability:vd[n],failurePolicy:e.failurePolicy(n),acknowledgeWithinBudget:hd.has(n),handler:e.handlers[n],timeoutResult:()=>_d(n)}]});return new Map(t)}async function Or(e){let t=e.registry.get(e.requestType);if(!t)return {status:"degraded",reason:"unknown_hook_handler",fallback:"host_event_continues"};let n=()=>Promise.resolve(t.handler(e.rawInput));return t.acknowledgeWithinBudget?Cr(t.eventName,e.acknowledgementBudgetMs,n,t.timeoutResult,e.projectRoot):n()}var hd=new Set(["stop","session-end","user-prompt-submit"]),yd={"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"},vd={"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 _d(e){return e==="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:e==="session-end"?"durable_session_recovery":"background_processing"}}var it=class{constructor(t){this.records=new Map;this.path=join(O(t),"hook-handler-health.json"),this.load();}recordSuccess(t,n,o=Date.now()){let r={handler:t,host:n,status:"healthy",consecutiveFailures:0,lastSuccessAt:o,updatedAt:o};return this.records.set(rt(t,n),r),this.persist(),r}recordFailure(t,n,o,r,i=Date.now()){let s=this.records.get(rt(t,n)),a=(s?.consecutiveFailures??0)+1,c=Math.min(5*6e4,1e3*2**Math.min(8,a-1)),d={handler:t,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(t,n),d),this.persist(),d}list(){return [...this.records.values()].sort((t,n)=>t.handler.localeCompare(n.handler))}load(){try{let t=JSON.parse(readFileSync$1(this.path,"utf8"));for(let n of t)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 t=`${this.path}.${process.pid}.tmp`;writeFileSync$1(t,JSON.stringify(this.list(),null,2),{mode:384}),renameSync(t,this.path);}catch{}}};function rt(e,t){return `${t}\0${e}`}function Pr(e,t){return t||(e==="post-tool-use"||e==="post-tool-use-failure"?{status:"ok"}:{status:"ok"})}function jr(e){let t=e instanceof Error?e.message:String(e??"hook_handler_failed");return {category:/timeout|budget|deadline/iu.test(t)?"timeout":/sqlite|database|locked|busy/iu.test(t)?"storage":/socket|connect|unreachable/iu.test(t)?"transport":/json|parse|schema|invalid/iu.test(t)?"protocol":"handler",reason:t}}function Fr(e){let t=xo({projectRoot:e.projectRoot,sessionId:e.sessionId,transcriptPath:e.transcriptPath,runtimeStore:e.runtimeStore}),n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{Cd(e.runtimeStore,e.sessionId,n);let o=n.getPendingMemoryTurn(e.projectRoot,e.sessionId),r=o?n.markMemoryTurnStopPrompted(o.turnId):!1,i=[];t&&i.push(t.reason),o&&r&&i.push(tt(o)),o&&!r&&Td(n,o.turnId)&&Ad(Je(e.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(e.projectRoot,e.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(`
28
28
 
29
- `)}: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 Sd(e,t){return !!e.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${t}`)}function xd(e){if(!e)return false;let t=e.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(t)?false:/(?:已|已经|成功).{0,20}(?:记住|记下|记录|保存|持久化)|跨会话生效|(?:memory|preference).{0,20}(?:saved|remembered|persisted)|status=(?:accepted|committed)/iu.test(t)}function Ed(e,t,n){let o=e.get(t);if(o){for(let r of o.evidenceObligations)n.upsertSessionObligation({obligationId:`evidence:${r.obligationId}`,projectRoot:o.projectRoot,sessionId:t,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,t,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:t,obligationId:i,state:r.status==="resolved"?"satisfied":"degraded",receiptId:a,reason:r.reason,resolvedAt:r.completedAt});}}}var Td=[/\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],Ad=[/\b(?:migration|upgrade|dependency|dependencies|generated files?|write all|rewrite)\b/iu,/(?:迁移|升级|依赖|生成文件|批量写入)/u];function tn(e){let t=`${e.instruction}
30
- ${JSON.stringify(e.trigger)}`,n=[];Td.some(r=>r.test(t))&&n.push("high_risk_operation"),Ad.some(r=>r.test(t))&&n.push("broad_or_migrating_change"),e.kind==="correction"&&n.push("user_correction_requires_observation");let o=n.includes("high_risk_operation")?"high":n.includes("broad_or_migrating_change")||e.scope==="global"?"medium":"low";return {risk:o,manualOnly:o==="high"||n.includes("broad_or_migrating_change"),reasons:n}}var Cd=new Set(["project_convention","user_preference","decision_made","config_discovery"]);function on(e){let t=e.payload.executionId?e.database.getSkillExecution(e.payload.executionId):e.database.getLatestSkillExecutionForSession(e.payload.sessionId),n=e.database.listHostActionsForSession(e.payload.projectRoot,e.payload.sessionId,e.payload.executionId),o=n.find(l=>l.state==="verified"),r=n.find(l=>["failed","cancelled","degraded"].includes(l.state)),i=r?"negative":o?"positive":"unknown",s=new Set,a=[],c=0,d=0;for(let l of e.evidence){if(!Dd(l)){d+=1;continue}let u=Lr(l),p=Md(l,t?.skillName),g=Wr(l),m=jd(e.payload.projectRoot,u,l.facetKey??l.semanticKey??l.id,p),f=e.database.getLearningCandidate(m),k=tn({scope:"project",kind:u,instruction:g,trigger:p});e.database.upsertLearningCandidate({id:m,projectRoot:e.payload.projectRoot,scope:"project",kind:u,trigger:p,instruction:g,confidence:Od(l),manualOnly:k.manualOnly,risk:k.risk});f&&f.instruction!==g&&e.database.addLearningCandidateEvidence({id:$r(m,e.payload.sessionId,l.id,"contradicting"),candidateId:m,projectRoot:e.payload.projectRoot,sessionId:e.payload.sessionId,executionId:e.payload.executionId,memoryObservationId:l.id,sourceType:"correction",polarity:"contradicting",outcome:i,evidenceHash:Hr(m,e.payload,l,"contradicting"),receipt:e.payload.closureReceipt,payload:{previousInstruction:f.instruction,replacementInstruction:g,projectRevision:e.payload.projectRevision},createdAt:l.createdAt});let S=e.database.addLearningCandidateEvidence({id:$r(m,e.payload.sessionId,l.id,"supporting"),candidateId:m,projectRoot:e.payload.projectRoot,sessionId:e.payload.sessionId,executionId:e.payload.executionId,memoryObservationId:l.id,outcomeId:o?.id??r?.id,sourceType:Pd(l),polarity:"supporting",outcome:i,evidenceHash:Hr(m,e.payload,l,"supporting"),receipt:e.payload.closureReceipt,payload:{semanticKey:l.semanticKey,facetKey:l.facetKey,evidenceStatus:l.evidenceStatus,source:l.source,projectRevision:e.payload.projectRevision,executionStatus:t?.status,policyReasons:k.reasons},createdAt:l.createdAt});c+=1,s.add(m),e.rolloutMode!=="off"&&S.state==="candidate"&&S.supportingSessions>=3&&S.successfulOutcomes>=2&&e.database.transitionLearningCandidate(m,{target:"shadow",reason:"evidence_threshold_satisfied"}).state==="shadow"&&a.push(m);}return {considered:e.evidence.length,accepted:c,excluded:d,candidateIds:[...s],promotedToShadow:a}}function Dd(e){return !(!Cd.has(e.type)||e.source!=="explicit_intent"&&e.source!=="manual"&&e.evidenceStatus!=="verified"||!e.narrative.trim()&&!e.title.trim())}function Lr(e){return e.type==="decision_made"?"workflow":e.type==="user_preference"&&(e.semanticValue.startsWith("--")||e.tools.length>0)?"tool_preference":"convention"}function Md(e,t){return {...t?{skills:[t]}:{},...e.entities.length>0?{entities:[...new Set(e.entities)].slice(0,8)}:{},...e.files.length>0?{files:[...new Set(e.files)].slice(0,8)}:{},...e.tools.length>0?{commands:[...new Set(e.tools)].slice(0,8)}:{},semantic:{subject:e.semanticSubject,predicate:e.semanticPredicate,value:e.semanticValue,polarity:e.semanticPolarity}}}function Wr(e){return (e.narrative.trim()||e.title.trim()).replace(/\s+/gu," ").slice(0,1200)}function Od(e){let t=e.source==="explicit_intent"?.08:0;return Math.max(0,Math.min(1,e.confidence+t))}function Pd(e){return e.semanticPolarity==="negative"?"correction":Lr(e)==="tool_preference"?"tool_preference":e.source==="explicit_intent"?"memory":"convention"}function jd(e,t,n,o){let r={...o,semantic:void 0};return `learning:${createHash("sha256").update(`${e}\0project\0${t}\0${n}\0${stableLearningJson(r)}`).digest("hex").slice(0,24)}`}function $r(e,t,n,o){return `learning-evidence:${createHash("sha256").update(`${e}\0${t}\0${n}\0${o}`).digest("hex").slice(0,24)}`}function Hr(e,t,n,o){return createHash("sha256").update(stableLearningJson({candidateId:e,sessionId:t.sessionId,executionId:t.executionId,closureReceipt:t.closureReceipt,projectRevision:t.projectRevision,observationId:n.id,instruction:Wr(n),polarity:o})).digest("hex")}var se=3e4,an=1e3,Qd=new Set(["git","npm","pnpm","yarn"]);function qr(e){return {"workflow.worker_start":async({item:t})=>Xd(e,t),"workflow.worker_monitor":async({item:t})=>Zd(e,t),"workflow.worker_verify":async({item:t})=>el(e,t),"workflow.worker_merge":async({item:t})=>tl(e,t),"workflow.worker_cleanup":async({item:t})=>nl(e,t)}}async function Xd(e,t){await Te(e,t,async(n,o)=>{if(o.state==="running"||o.state==="starting"){rn(n,o);return}if(o.state!=="planned")return;let r=`worker-plane:${process.pid}`;n.leaseWorkflowWorker(e,o.workerId,r,se);let i=await createManagedWorktree({projectRoot:e,runId:o.runId,stepId:o.stepId,baseRevision:o.baseRevision,registered:!0});if(i.worktreePath!==o.worktreePath||i.branch!==o.branch){n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"hold",leaseOwner:r,reason:"managed_worktree_identity_mismatch"});return}n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"starting",leaseOwner:r});let s=Br(o.workerId),a=ol(o);createWorkerArtifacts(s,a);let d=createDefaultHostAdapterRegistry().list().find(g=>g.id===o.host);if(!d)throw new x("unsupported_worker_host",`Unsupported worker host ${o.host}`);let l=ae(o.handoff.actionId,"actionId"),u=n.getHostAction(e,l);if(!u)throw new x("worker_host_action_missing",`Host action ${l} was not found`);u.state==="waiting"&&n.startHostAction({actionId:l,projectRoot:e});let p=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 g=openGlobalDevFlowDatabase();try{g.heartbeatWorkflowWorker(e,o.workerId,r,se);}catch{}finally{g.close();}}});rl(s,{state:"running",pid:p.child.pid,owner:r,startedAt:Date.now()}),n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"running",leaseOwner:r,heartbeatAt:Date.now(),leaseExpiresAt:Date.now()+se}),rn(n,o),p.completion.finally(()=>{let g=openGlobalDevFlowDatabase();try{rn(g,o,Date.now());}finally{g.close();}});});}async function Zd(e,t){await Te(e,t,async(n,o)=>{if(o.state!=="running"&&o.state!=="starting")return;let r=Br(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=ae(o.handoff.actionId,"actionId");n.reportHostAction({actionId:d,projectRoot:e,report:{workerId:o.workerId,handoff:c},evidenceHash:Gr(c)}),n.transitionWorkflowWorker({projectRoot:e,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:e,payload:{workerId:o.workerId}});return}let i=il(r),s=typeof i?.pid=="number"?i.pid:void 0;if(s&&al(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:e,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_process_timeout"});let l=ae(o.handoff.actionId,"actionId");n.failHostAction({actionId:l,projectRoot:e,report:{reason:"worker_process_timeout"}});return}let d=o.leaseOwner??(typeof i?.owner=="string"?i.owner:void 0);throw d?(n.heartbeatWorkflowWorker(e,o.workerId,d,se),Jr("worker_running",an)):new x("worker_lease_owner_missing","Worker lease owner is missing")}n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_exited_without_handoff"});let a=ae(o.handoff.actionId,"actionId");n.failHostAction({actionId:a,projectRoot:e,report:{reason:"worker_exited_without_handoff"}});});}async function el(e,t){await Te(e,t,async(n,o)=>{if(o.state!=="reported")return;n.transitionWorkflowWorker({projectRoot:e,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=ae(o.handoff.actionId,"actionId"),s=n.getHostAction(e,i);if(!s)throw new x("worker_host_action_missing",`Host action ${i} was not found`);let a=zr(o),c=new GraderRegistry,d=await Ur(n,o,async()=>verifyWorkerOutput({workerId:o.workerId,projectRoot:e,worktreePath:o.worktreePath,baseRevision:o.baseRevision,parentRevision:await sl(e),contextReceipt:o.contextReceipt,allowedFiles:o.allowedFiles,handoff:r,hostAction:s,verificationCommands:a,graderIds:["receipt_validity","lifecycle_terminal_state","workflow_evidence"],graderRunner:{run:async l=>{let u=await c.run({taskId:o.stepId,taskKind:l.taskKind,projectRoot:l.projectRoot,acceptanceCriteria:[],evidence:l.evidence});return {...u,unavailableBlocking:u.unavailableRequired}}}}));if(!d.passed){n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:d.state,leaseOwner:o.leaseOwner,reason:d.reason}),d.state==="failed"&&n.failHostAction({actionId:i,projectRoot:e,outcome:"failed",report:{...s.report,verification:d},evidenceHash:d.simulationHash});return}n.transitionWorkflowWorker({projectRoot:e,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:e,payload:{workerId:o.workerId}});});}async function tl(e,t){await Te(e,t,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=ae(o.handoff.actionId,"actionId"),s=new SerializedWorkerMergeQueue(n,{onMerged:async({mergeCommit:c})=>{n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"merged",leaseOwner:o.leaseOwner,finalRevision:o.finalRevision,reason:`merged:${c}`});let d=n.getHostAction(e,i);n.verifyHostAction({actionId:i,projectRoot:e,report:{...d?.report??{},mergeCommit:c,verification:r},evidenceHash:Gr({mergeCommit:c,verification:r})});},scheduleCleanup:()=>{n.enqueueWork({idempotencyKey:`workflow-worker-cleanup:${o.workerId}:merged`,kind:"workflow.worker_cleanup",projectRoot:e,payload:{workerId:o.workerId}});}}),a=await Ur(n,o,()=>s.enqueueAndMerge({workerId:o.workerId,projectRoot:e,baseRevision:o.baseRevision,verification:r,message:`merge(devflow-worker): ${o.runId}/${o.stepId}`}));a.state==="conflict"&&n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"hold",leaseOwner:o.leaseOwner,reason:a.reason??"merge_conflict"});});}async function nl(e,t){await Te(e,t,async(n,o)=>{let r=t.payload,i=await cleanupManagedWorktree({repositoryRoot:e,worktreePath:o.worktreePath,branch:o.branch,registered:!0,handoffDurable:!!o.handoff.terminalHandoff||r.operatorApproved===!0});if(!i.cleaned)throw Jr(`cleanup_${i.reason??"refused"}`,3e4)});}async function Ur(e,t,n){let o=t.leaseOwner;if(!o)return n();let r=setInterval(()=>{try{e.heartbeatWorkflowWorker(t.projectRoot,t.workerId,o,se);}catch{}},Math.floor(se/3));r.unref();try{return await n()}finally{clearInterval(r);}}async function Te(e,t,n){let o=cl(t.payload),r=openGlobalDevFlowDatabase();try{let i=r.getWorkflowWorker(e,o);if(!i)throw new x("worker_not_found",`Worker ${o} was not found`);await n(r,i);}finally{r.close();}}function ol(e){let t=e.handoff.task;if(!t||typeof t!="object"||Array.isArray(t))throw new x("worker_task_missing","Worker task envelope is missing");let n=zr(e);return {workerId:e.workerId,runId:e.runId,stepId:e.stepId,projectRoot:e.projectRoot,worktreePath:e.worktreePath,baseRevision:e.baseRevision,contextReceipt:e.contextReceipt,retrievalSessionId:e.retrievalSessionId,allowedFiles:e.allowedFiles,requiredTools:[],task:t,verification:{commands:n,graders:["receipt_validity","lifecycle_terminal_state","workflow_evidence"]},constraints:{recursiveWorkers:false,maxContextCycles:3}}}function zr(e){let t=e.handoff.verificationCommands;if(!Array.isArray(t)||t.length===0)throw new x("verification_contract_missing","Worker verification commands are missing");return t.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"||!Qd.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 Br(e){let t=workerCoordinationRoot(e,homedir());return {root:t,taskFile:join(t,"task.json"),handoffFile:join(t,"handoff.json"),statusFile:join(t,"status.json"),stdoutFile:join(t,"stdout.log"),stderrFile:join(t,"stderr.log")}}function rl(e,t){writeJsonAtomic(e.statusFile,t);}function il(e){try{return JSON.parse(readFileSync$1(e.statusFile,"utf8"))}catch{return null}}function rn(e,t,n=Date.now()+an){e.enqueueWork({idempotencyKey:`workflow-worker-monitor:${t.workerId}:${Math.floor(n/an)}`,kind:"workflow.worker_monitor",projectRoot:t.projectRoot,payload:{workerId:t.workerId},nextAttemptAt:n,maxAttempts:1e3});}async function sl(e){let{gitRevision:t}=await import('@devflow-tools/workflow-engine');return t(e,"HEAD")}function al(e){try{return process.kill(e,0),!0}catch{return false}}function Jr(e,t){return Object.assign(new Error(e),{category:e,retryAfterMs:t,retryWithoutAttempt:true})}function cl(e){if(!e||typeof e!="object"||typeof e.workerId!="string")throw new x("invalid_worker_payload","Worker work item requires workerId");return e.workerId}function ae(e,t){if(typeof e!="string"||!e.trim())throw new x("worker_identity_missing",`Worker ${t} is missing`);return e}function Gr(e){return createHash("sha256").update(JSON.stringify(e)).digest("hex")}var ul=new Set(["Write","Edit","NotebookEdit"]);function Qr(e){if(!ul.has(e.toolName)||hl(e.toolResponse))return null;let t=gl(e.projectRoot,e.toolInput);if(!t)return null;let n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let o=n.getActiveContextReceipt(e.projectRoot,e.sessionId,e.executionId),r=o?.canonicalAction?.verificationPlan??[];if(!o||r.length===0)return null;let i=[],s=[];for(let c of r){let d=ml({projectRoot:e.projectRoot,targetFile:t,kind:c.kind,mode:c.mode==="write"?"write":"check",required:c.required===!0,contextReceipt:o.contextHash}),l=`${o.contextHash}\0${e.toolUseId??t}\0${c.kind}\0${t}`,u=`policy-verification:${createHash("sha256").update(l).digest("hex")}`,p=Date.now();if(!d){let f=`verification_unavailable:${c.kind}`;n.upsertSessionObligation({obligationId:u,projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,kind:"evidence_contract",state:"degraded",payload:{subtype:"policy_verification",status:"unknown",verificationKind:c.kind,targetFile:t,contextReceipt:o.contextHash},reason:f,createdAt:p,updatedAt:p,resolvedAt:p}),s.push(c.kind),c.required===!0&&C({projectRoot:e.projectRoot,sessionId:e.sessionId,requestId:o.requestId,executionId:e.executionId,kind:"verification.failed",payload:{receiptId:u,reasonCode:f},dedupeKey:`${u}:unavailable`,producer:"devflow-verification-scheduler"});continue}let g={...d,obligationId:u,sessionId:e.sessionId,executionId:e.executionId,requestId:o.requestId};n.upsertSessionObligation({obligationId:u,projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,kind:"evidence_contract",state:"open",payload:{subtype:"policy_verification",status:"scheduled",verificationKind:c.kind,command:d.display,targetFile:t,contextReceipt:o.contextHash,required:c.required===!0},createdAt:p,updatedAt:p});let m=n.enqueueWork({idempotencyKey:u,kind:"verification.policy",projectRoot:e.projectRoot,sessionId:e.sessionId,payload:g,maxAttempts:2,nextAttemptAt:p});C({projectRoot:e.projectRoot,sessionId:e.sessionId,requestId:o.requestId,executionId:e.executionId,kind:"durable_work.owned",payload:{workId:m.id,obligation:"verification"},dedupeKey:`${m.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(`
31
- `)||null}finally{n.close();}}async function Xr(e,t){let n=pl(e,t.payload),o=await fl(n,e),r=n.kind==="typecheck"?wl(o.output,n.targetFile,e):[],i=Vr({command:n.command,args:n.args}),s=openGlobalDevFlowDatabase();try{let a=bl(e),c=n.kind==="typecheck"?s.getPolicyVerificationBaseline(e,n.kind,i):null,d=c&&c.sourceRevision===a?c:null,l=d?r.filter(I=>!d.diagnosticHashes.includes(I)):[],u;o.spawnError||/could not determine executable|command not found|not recognized as an internal|ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL/iu.test(o.output)?u="unavailable":o.timedOut?u="unknown":o.exitCode===0?u="passed":n.kind==="typecheck"&&!d?u="unknown":n.kind==="typecheck"&&l.length===0?u="passed":u="failed";let p=createHash("sha256").update(o.output).digest("hex"),g=`verification-receipt:${Vr({obligationId:n.obligationId,commandHash:i,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:p,diagnosticHashes:r,introduced:l,status:u})}`,m={status:u,kind:n.kind,command:n.display,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:p,diagnosticHashes:r,introducedDiagnosticHashes:l,baselineAvailable:d!==null,receiptId:g},f=s.getWorkByIdempotencyKey(n.obligationId)?.id,k=s.getSessionObligation(e,n.sessionId,n.obligationId);if(k?.state==="open"&&(s.upsertSessionObligation({...k,payload:{...k.payload,status:u,outcome:m},updatedAt:Date.now()}),u!=="failed"&&s.resolveSessionObligation({projectRoot:e,sessionId:n.sessionId,obligationId:n.obligationId,state:u==="passed"?"satisfied":"degraded",receiptId:g,reason:u==="unknown"?"verification_result_unknown":u==="unavailable"?"verification_command_unavailable":void 0})),n.kind==="typecheck"&&o.exitCode===0&&s.upsertPolicyVerificationBaseline({projectRoot:e,kind:n.kind,commandHash:i,diagnosticHashes:[],sourceRevision:a,updatedAt:Date.now()}),kl(s,n,m),C({projectRoot:e,sessionId:n.sessionId,requestId:n.requestId,executionId:n.executionId,kind:u==="passed"?"verification.succeeded":"verification.failed",payload:{receiptId:g,reasonCode:`verification_${u}`,verificationKind:n.kind},dedupeKey:g,producer:"devflow-verification-worker"}),f&&u!=="failed"&&C({projectRoot:e,sessionId:n.sessionId,requestId:n.requestId,executionId:n.executionId,kind:"durable_work.completed",payload:{workId:f,obligation:"verification"},dedupeKey:`${f}:completed`,producer:"devflow-verification-worker"}),u==="failed"){let I=new Error(`Policy verification failed: ${n.display}`);throw I.category="policy_verification_failed",I}return m}finally{s.close();}}function ml(e){let t=yl(e.projectRoot),n=_l(e.projectRoot),o=t?.scripts??{},r={...t?.dependencies,...t?.devDependencies},i=null;if(e.kind==="formatter"&&(r.prettier||vl(e.projectRoot)))i=st(n,"prettier",[e.mode==="write"?"--write":"--check",e.targetFile],6e4);else if(e.kind==="typecheck"){let s=ln(o,["typecheck","type-check","check:types"]);s?i=cn(n,s,12e4):r.typescript&&existsSync(join(e.projectRoot,"tsconfig.json"))&&(i=st(n,"tsc",["--noEmit","--pretty","false"],12e4));}else if(e.kind==="lint"){let s=ln(o,["lint"]);s&&(i=cn(n,s,12e4));}else if(e.kind==="test"){let s=Il(e.projectRoot,e.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(e.kind==="build"){let s=ln(o,["build"]);s&&(i=cn(n,s,18e4));}else e.kind==="generated_files"&&(i={command:"git",args:["diff","--check","--",e.targetFile],timeoutMs:3e4});return i?{kind:e.kind,...i,display:[i.command,...i.args].map(Rl).join(" "),required:e.required,targetFile:e.targetFile,contextReceipt:e.contextReceipt}:null}function cn(e,t,n){return e==="yarn"?{command:"yarn",args:["run",t],timeoutMs:n}:e==="pnpm"?{command:"pnpm",args:["run",t],timeoutMs:n}:e==="bun"?{command:"bun",args:["run",t],timeoutMs:n}:{command:"npm",args:["run",t],timeoutMs:n}}function st(e,t,n,o){return e==="pnpm"?{command:"pnpm",args:["exec",t,...n],timeoutMs:o}:e==="yarn"?{command:"yarn",args:[t,...n],timeoutMs:o}:e==="bun"?{command:"bunx",args:[t,...n],timeoutMs:o}:{command:"npx",args:["--no-install",t,...n],timeoutMs:o}}function pl(e,t){if(!t||typeof t!="object"||Array.isArray(t))throw dn();let n=t,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)||!Zr(e,n.targetFile))throw dn();return n}function dn(){let e=new Error("Policy verification work payload is invalid");return e.category="invalid_payload",e}function fl(e,t){return new Promise(n=>{let o=spawn$1(e.command,e.args,{cwd:t,shell:false,stdio:["ignore","pipe","pipe"],env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),r="",i=false,s=l=>{i||(i=true,n(l));},a=l=>{r=(r+String(l)).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();},e.timeoutMs);o.on("error",l=>{clearTimeout(d),s({exitCode:null,timedOut:false,spawnError:true,output:`${r}
32
- ${l.message}`.slice(-32768)});}),o.on("close",l=>{clearTimeout(d),s({exitCode:l,timedOut:c,spawnError:false,output:r});});})}function gl(e,t){let n=t.file_path??t.notebook_path;if(typeof n!="string"||!n.trim())return null;let o=isAbsolute(n)?resolve(n):resolve(e,n);return Zr(e,o)?relative(e,o).split(sep).join("/"):null}function Zr(e,t){let n=isAbsolute(t)?resolve(t):resolve(e,t),o=relative(resolve(e),n);return o!==""&&o!==".."&&!o.startsWith(`..${sep}`)&&!isAbsolute(o)}function hl(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return t.ok===false||t.success===false||t.isError===true||!!t.error}function yl(e){try{return JSON.parse(readFileSync$1(join(e,"package.json"),"utf8"))}catch{return null}}function _l(e){return existsSync(join(e,"pnpm-lock.yaml"))?"pnpm":existsSync(join(e,"yarn.lock"))?"yarn":existsSync(join(e,"bun.lockb"))||existsSync(join(e,"bun.lock"))?"bun":"npm"}function vl(e){return [".prettierrc",".prettierrc.json",".prettierrc.js",".prettierrc.cjs","prettier.config.js","prettier.config.cjs"].some(t=>existsSync(join(e,t)))}function ln(e,t){return t.find(n=>typeof e[n]=="string"&&e[n].trim())??null}function Il(e,t){let n=t.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(e,a)))return a}let r=join(e,t.split("/").slice(0,-1).join("/")),i=t.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(e,join(r,s)).split(sep).join("/"))[0]??null}catch{return null}}function wl(e,t,n){let o=t.split(sep).join("/"),r=resolve(n,t).split(sep).join("/"),i=e.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 kl(e,t,n){if(!t.executionId)return;let o=e.getSkillExecution(t.executionId);if(!o)return;let r=o.metadata&&typeof o.metadata=="object"?o.metadata:{},i=Array.isArray(r.policyVerificationOutcomes)?r.policyVerificationOutcomes:[];e.updateSkillExecution(t.executionId,{metadata:{...r,policyVerificationOutcomes:[...i,n]}});}function bl(e){try{let t=readFileSync$1(join(e,".git","HEAD"),"utf8").trim();return t.startsWith("ref:")?readFileSync$1(join(e,".git",t.slice(5).trim()),"utf8").trim():t}catch{return}}function Vr(e){return createHash("sha256").update(JSON.stringify(e)).digest("hex")}function Rl(e){return /^[A-Za-z0-9_./:@=-]+$/u.test(e)?e:JSON.stringify(e)}function ti(e){let t=Date.now(),n=zl(e.projectRoot),o=claudeCodeRuntimeAdapter.normalizePrompt(e.hostEvent??{session_id:e.sessionId,prompt:e.prompt},{projectRoot:n}),r=o.sourceHash,i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100});try{let s=i.getTaskIntentArtifactBySource({projectRoot:n,sessionId:e.sessionId,sourceHash:r});if(s){let I=Pl(i,s);return {artifact:Hl(s),queryPlan:Nl(I),memoryIdentity:ei(s),reused:!0}}let a=ql(o.rawPrompt,o.command),c=buildRetrievalTaskPlan({query:a,parsedIntent:parseIntent(a,{segmentation:"regex"}),targetAnchors:Ll(o.rawPrompt),activeSkill:o.activeSkill,command:o.command}),d=`turn:${Ae(`${e.sessionId}\0${r}`)}`,l=`request:${Ae(`${n}\0${e.sessionId}\0${d}`)}`,u={projectRoot:n,projectId:`project:${Ae(n)}`,hostId:o.hostId,sessionId:e.sessionId,turnId:d,requestId:l},p=[{source:"deterministic_parser",field:"intent",value:c.intent,reason:c.classification.intentReason,confidence:c.classification.intentSource==="semantic_override"?.95:.75},{source:o.command?"slash_command":"deterministic_parser",field:"action",value:c.action,reason:c.classification.actionReason,confidence:o.command||c.action!=="analyze"?.95:.65},...c.targetAnchors.map(I=>({source:"target_anchor",field:"target",value:I,reason:"explicit_prompt_target",confidence:1}))],g={identity:u,version:1,rawPrompt:o.rawPrompt,normalizedPrompt:Ul(o.rawPrompt),...o.command?{command:o.command}:{},slashArgs:o.slashArgs,...o.activeSkill?{activeSkill:o.activeSkill}:{},intent:c.intent,action:c.action,entities:c.entities,targetAnchors:c.targetAnchors,policyConstraints:Wl(o.rawPrompt),classificationEvidence:p,sourceEventIds:[o.sourceEventId??`host-event:${r.slice(0,24)}`],sourceHash:r,createdAt:o.timestamp},m={...g,artifactHash:Bl(g)},f=buildChannelQueryPlan({artifact:m,taskPlan:c,expandedTerms:e.expandedTerms});i.appendTaskIntentArtifact(Fl(m)),i.appendChannelQueryPlan($l(f));let k=jl(i,m);try{appendTaskRuntimeBoundary({projectRoot:n,taskSpec:taskSpecFromImmutableIntent(m),kind:"task.spec.bound",payload:{intentArtifactHash:m.artifactHash},dedupeKey:m.artifactHash,producer:"devflow-task-intent",createdAt:m.createdAt,database:i});}catch(I){emitSemanticControlLog({event:"task.runtime.shadow_mismatch",identity:u,level:"warn",timestamp:Date.now(),data:{stage:"task.spec.bound",reason:I instanceof Error?I.message:String(I),authority:"legacy"}});}return emitSemanticControlLog({event:"host.prompt.normalized",identity:u,level:"info",timestamp:Date.now(),data:{sourceHash:r,command:m.command,activeSkill:m.activeSkill,rawPromptBytes:Buffer.byteLength(m.rawPrompt)}}),emitSemanticControlLog({event:"intent.artifact.created",identity:u,level:"info",timestamp:Date.now(),data:{artifactHash:m.artifactHash,intent:m.intent,action:m.action,evidence:m.classificationEvidence,entityCount:m.entities.length,targetCount:m.targetAnchors.length}}),emitSemanticControlLog({event:"intent.artifact.persisted",identity:u,level:"info",timestamp:Date.now(),data:{artifactHash:m.artifactHash,version:m.version,sourceHash:m.sourceHash,parserMode:"regex",captureLatencyMs:Date.now()-t}}),emitSemanticControlLog({event:"query.plan.created",identity:u,level:"info",timestamp:Date.now(),data:{planHash:f.planHash,sourceIntentHash:f.sourceIntentHash,generatedBy:f.generatedBy,codeQueries:f.code.length,memoryQueries:f.memory.length,knowledgeQueries:f.knowledge.length,knowledgeDisposition:f.knowledge.map(I=>I.requirement)}}),emitSemanticControlLog({event:"terminal.transition.persisted",identity:u,level:"info",timestamp:Date.now(),data:{state:"intent_bound",receiptId:k,sourceIntentHash:m.artifactHash}}),{artifact:m,queryPlan:f,memoryIdentity:ei(m),reused:!1}}finally{i.close();}}function Pl(e,t){let n=e.getChannelQueryPlanForIntent({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:t.turnId,sourceIntentHash:t.artifactHash});if(!n)throw new Error(`QUERY_PLAN_NOT_FOUND:${t.artifactHash}`);return n}function jl(e,t){let n=e.getLatestTerminalTransition(t.identity.projectRoot,t.identity.sessionId,t.identity.turnId);if(n)return n.receiptId;let o=`terminal:${Ae(`${t.artifactHash}\0open`)}`;return e.appendTerminalTransition({...t.identity,sequence:1,toState:"open",receiptId:o,reason:"host_prompt_accepted",payload:{sourceHash:t.sourceHash},createdAt:t.createdAt}),e.appendTerminalTransition({...t.identity,sequence:2,fromState:"open",toState:"intent_bound",receiptId:`terminal:${Ae(`${t.artifactHash}\0intent_bound`)}`,sourceReceiptId:o,reason:"immutable_intent_persisted",payload:{intentArtifactHash:t.artifactHash},createdAt:Math.max(t.createdAt,Date.now())}).receiptId}function Fl(e){return {...e.identity,version:e.version,supersedesHash:e.supersedesHash,rawPrompt:e.rawPrompt,normalizedPrompt:e.normalizedPrompt,command:e.command,slashArgs:e.slashArgs,activeSkill:e.activeSkill,intent:e.intent,action:e.action,entities:e.entities,targetAnchors:e.targetAnchors,policyConstraints:e.policyConstraints,classificationEvidence:e.classificationEvidence.map(t=>({...t})),sourceEventIds:e.sourceEventIds,sourceHash:e.sourceHash,artifactHash:e.artifactHash,createdAt:e.createdAt}}function $l(e){return {...e.identity,sourceIntentHash:e.sourceIntentHash,planHash:e.planHash,code:e.code.map(t=>({...t})),memory:e.memory.map(t=>({...t})),knowledge:e.knowledge.map(t=>({...t})),generatedBy:e.generatedBy,degradation:e.degradation?{...e.degradation}:void 0,createdAt:e.createdAt}}function Hl(e){return {identity:ni(e),version:e.version,...e.supersedesHash?{supersedesHash:e.supersedesHash}:{},rawPrompt:e.rawPrompt,normalizedPrompt:e.normalizedPrompt,...e.command?{command:e.command}:{},slashArgs:e.slashArgs,...e.activeSkill?{activeSkill:e.activeSkill}:{},intent:e.intent,action:e.action,entities:e.entities,targetAnchors:e.targetAnchors,policyConstraints:e.policyConstraints,classificationEvidence:e.classificationEvidence,sourceEventIds:e.sourceEventIds,sourceHash:e.sourceHash,artifactHash:e.artifactHash,createdAt:e.createdAt}}function Nl(e){return {identity:ni(e),sourceIntentHash:e.sourceIntentHash,planHash:e.planHash,code:e.code,memory:e.memory,knowledge:e.knowledge,generatedBy:e.generatedBy,...e.degradation?{degradation:e.degradation}:{},createdAt:e.createdAt}}function ni(e){return {projectRoot:e.projectRoot,projectId:e.projectId,hostId:e.hostId,sessionId:e.sessionId,turnId:e.turnId,requestId:e.requestId,...e.executionId?{executionId:e.executionId}:{}}}function ei(e){let t=e.rawPrompt.trim().slice(0,4e3);return {turnId:e.identity?e.identity.turnId:e.turnId,eventId:`memory-turn:${(e.identity?e.identity.turnId:e.turnId).replace(/^turn:/u,"")}`,promptHash:createHash("sha256").update(t).digest("hex"),createdAt:e.createdAt}}function Ll(e){let t=e.match(/(?:^|[\s`'"(])((?:\.{0,2}\/)?(?:[A-Za-z0-9_@.-]+\/)+[A-Za-z0-9_@.-]+(?:\.[A-Za-z0-9]+)?)/gu)??[];return oi(t.map(n=>n.trim().replace(/^[`'"(]+|[`'"),.;:,。;:]+$/gu,"")).filter(n=>!n.startsWith("/")||/\.[A-Za-z0-9]+$/u.test(n))).slice(0,16)}function Wl(e){let t=e.match(/--[a-z0-9][a-z0-9-]*(?:=[^\s,。;;]+)?/giu)??[];return oi(t.map(n=>n.normalize("NFKC"))).slice(0,16)}function ql(e,t){return t&&e.trimStart().replace(new RegExp(`^\\/${Jl(t)}\\b`,"iu"),"").trim()||e.trim()}function Ul(e){return e.normalize("NFKC").replace(/\s+/gu," ").trim().slice(0,4e3)}function oi(e){return [...new Set(e.filter(Boolean))]}function zl(e){let t=resolve(e);try{return realpathSync(t)}catch{return t}}function Bl(e){return createHash("sha256").update(fn(e)).digest("hex")}function Ae(e){return createHash("sha256").update(e).digest("hex").slice(0,24)}function fn(e){if(e===null||typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number")return Number.isFinite(e)?JSON.stringify(e):"null";if(Array.isArray(e))return `[${e.map(fn).join(",")}]`;if(!e||typeof e!="object")return JSON.stringify(String(e));let t=e;return `{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${fn(t[n])}`).join(",")}}`}function Jl(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}var du=600*1e3,lu=2e3,uu=250,mu=2e3,pu=1e3,ii=1024*1024,fu=2*1024*1024,gu=6e4,hu=100,yu={Agent:"get_project_context",Bash:"get_project_context",Glob:"get_project_context",Grep:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function _u(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.status=="string"?t.status:void 0;if(!(t.ok===false||t.success===false||t.isError===true||n==="failed"||n==="rejected"||n==="unavailable"||n==="warming"||!!t.error))return;let r=t.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 si(e){return /timeout|timed out|deadline|warming/i.test(e)?"timeout":/unavailable|not active|unknown tool|not found|not registered|route not found/i.test(e)?"unavailable":"failed"}function ai(e,t,n,o,r){let i=e.recordDomainActionOutcome;typeof i=="function"&&i.call(e,t,n,o,r);}function vu(e){switch(e){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 yn(e){return typeof e=="string"&&e.trim().length>0}function Iu(e,t,n=process.env,o){if(!e.startsWith("mcp__devflow__"))return t;let r=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{};if(yn(r.projectRoot))return r;let i=yn(n.CLAUDE_PROJECT_DIR)?n.CLAUDE_PROJECT_DIR:o;return yn(i)&&(r.projectRoot=i),r}var _n=class{constructor(t,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=t,this.socketPath=getDaemonSocketPath(t),this.pidPath=getDaemonPidPath(t),this.telemetry=new ee,this.runtimeStore=new L(this.projectRoot),this.serverManager=new Fe(t),this.hookRuntime=Ar(t),this.hookHealth=new it(t),this.hookHandlers=Mr({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=>en(o,this.hookRuntime,this.hostRuntime??{hostId:"unresolved",capabilities:new Map,profiles:new Set(["minimal","standard","strict"])}).policy}),this.initialSessionInput=n,this.workRuntime=new ot({projectRoot:t,handlers:{...qr(t),"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 he({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,writeContextPrefetchCache:s}=await import('@devflow-tools/context-engine'),a=await i(this.projectRoot);try{let c=await a.context.buildTaskContext(r.prompt,{mode:"fast",sessionId:r.sessionId,executionId:r.executionId,activeSkill:r.skillName});if(!s({projectRoot:this.projectRoot,query:r.prompt,sessionId:r.sessionId,executionId:r.executionId,profileFingerprint:r.profileFingerprint,rolloutMode:r.rolloutMode,retrievalVersion:r.retrievalVersion},c))throw new Error("Context prefetch envelope was not receipt-valid")}finally{for(let c of Object.values(a))try{c.close?.();}catch{}}},"verification.policy":async({item:o})=>{await Xr(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=on({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(t,n,o={},r){let i=r?this.runtimeStore.get(r):void 0;emitSemanticControlLog({event:t==="warn"||t==="error"?"hook.runtime.degraded":"hook.runtime.completed",identity:{projectRoot:this.projectRoot,sessionId:r,executionId:i?.executionId},level:t,timestamp:Date.now(),data:{stage:n,...o}});}async start(){this.hostRuntime=await Dr(this.projectRoot),mkdirSync(dirname(this.socketPath),{recursive:true,mode:448}),await this.cleanStaleStartupResources(),this.server=createServer(t=>this.handleConnection(t));try{await this.listen(),this.writePidFile(),Xn(this.projectRoot,process.pid);}catch(t){throw await this.closeServer(),this.cleanupOwnedResources(),t}if(this.server.on("error",t=>{this.logRuntime("error","server_error",{reason:t.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();},gu),this.telemetryFlushTimer.unref(),prepareEmbeddingModel().then(t=>{this.logRuntime("info","embedding_ready",{source:t.source,cacheRootHash:createHash("sha256").update(t.cacheRoot).digest("hex").slice(0,16)});}).catch(t=>{this.logRuntime("warn","embedding_unavailable",{reason:t.message,fallback:"lexical_retrieval"});}),this.workRuntime.start(),this.initialSessionInput){let t=this.initialSessionInput;this.initialSessionInput=void 0,this.handleRequest({type:"session-start",input:t});}this.drainSessionStartSpool(),this.scheduleMemoryTurnSpoolDrain(0),this.scheduleSessionFinalizeSpoolDrain(0),this.resetIdleTimer();}handleConnection(t){let n="",o=false,r=false,i=0,s=Promise.resolve();t.setEncoding("utf8");let a=()=>{r||(r=true,clearTimeout(c),t.destroy());},c=setTimeout(()=>{a();},lu).unref(),d=async l=>{if(!r){r=true,clearTimeout(c);try{await this.writeFrame(t,l);}catch{}finally{t.destroy();}}};t.on("data",l=>{if(r)return;n+=l;let u=n.split(`
33
- `);if(n=u.pop()??"",Buffer.byteLength(n,"utf8")>ii){a();return}if(u.length===0)return;let p=0;for(let g of u){let m=Buffer.byteLength(g,"utf8");if(m>ii){a();return}p+=m+1;}if(i+p>fu){a();return}i+=p,s=s.then(async()=>{for(let g of u){if(r)return;if(!o){let m;try{m=JSON.parse(g);}catch{await d({error:"handshake_invalid"});return}if(m?.type!=="hello"||typeof m.rootPath!="string"){await d({error:"handshake_invalid"});return}if(m.rootPath!==this.projectRoot){await d({error:"handshake_root_mismatch",expected:this.projectRoot});return}o=true,clearTimeout(c),this.resetIdleTimer();continue}if(g.trim())try{let m=JSON.parse(g),f=await this.handleRequest(m);f!==null&&!r&&await this.writeFrame(t,f);}catch(m){r||await this.writeFrame(t,{error:m.message});}}}).catch(()=>{a();}).finally(()=>{i-=p;});}),t.on("close",()=>clearTimeout(c)),t.on("error",()=>{});}writeFrame(t,n){return new Promise((o,r)=>{if(t.destroyed||!t.writable){r(new Error("Socket is not writable"));return}let i=false,s=true,a=false,c=setTimeout(()=>{t.destroy(),l(new Error("Timed out writing daemon response"));},pu),d=()=>{clearTimeout(c),t.off("close",u),t.off("error",p),t.off("drain",g);},l=f=>{a||!f&&(!i||!s)||(a=true,d(),f?r(f):o());},u=()=>l(new Error("Socket closed during write")),p=f=>l(f),g=()=>{s=true,l();};t.once("close",u),t.once("error",p),t.write(`${JSON.stringify(n)}
34
- `,f=>{if(f){l(f);return}i=true,l();})||(s=false,t.once("drain",g));})}async cleanStaleStartupResources(){let t=this.getPathIdentity(this.socketPath);if(t){if(await this.isSocketAcceptingConnections())throw new Error(`Daemon socket already active for ${this.projectRoot}`);this.removePathIfOwned(this.socketPath,t,"stale socket");}let n=this.getPathIdentity(this.pidPath);n&&this.removePathIfOwned(this.pidPath,n,"stale PID file");}getPathIdentity(t){try{let n=lstatSync(t);return {dev:n.dev,ino:n.ino}}catch(n){if(n.code==="ENOENT")return null;throw n}}pathMatchesIdentity(t,n){if(!n)return false;try{let o=this.getPathIdentity(t);return o?.dev===n.dev&&o.ino===n.ino}catch(o){return this.logRuntime("warn","path_ownership_check",{reason:o.message}),false}}writePidFile(){let t=openSync(this.pidPath,"wx",384);try{writeFileSync(t,`${process.pid}
35
- `);let n=fstatSync(t);this.pidIdentity={dev:n.dev,ino:n.ino};}finally{closeSync(t);}}removePathIfOwned(t,n,o,r){try{return !this.pathMatchesIdentity(t,n)||r!==void 0&&readFileSync(t,"utf8")!==r||!this.pathMatchesIdentity(t,n)?!1:(unlinkSync(t),!0)}catch(i){return i.code!=="ENOENT"&&this.logRuntime("warn","owned_path_cleanup",{label:o,reason:i.message}),false}}isSocketAcceptingConnections(){return new Promise((t,n)=>{let o=createConnection(this.socketPath),r=setTimeout(()=>{o.destroy(),n(new Error(`Timed out probing daemon socket ${this.socketPath}`));},uu),i=s=>{clearTimeout(r),o.destroy(),t(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((t,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,t();}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 t=openGlobalDevFlowDatabase();try{if(t.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{t.close();}this.logRuntime("info","idle_timeout_exit"),this.shutdown();},du).unref());}async handleRequest(t){let n=this.hostRuntime,o=wu(t.input);if(!n)return this.hookFailureResponse(t.type,{enabled:false,policy:"fail_open",reason:"host_adapter_not_ready",fallback:"host_event_continues_without_devflow_handler"});let r=en(t.type,this.hookRuntime,n);if(!r.enabled)return this.hookFailureResponse(t.type,r);let i=Date.now();try{let s=Pr(t.type,await Or({registry:this.hookHandlers,requestType:t.type,rawInput:t.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(t.type,n.hostId,"degraded",c);}else this.hookHealth.recordSuccess(t.type,n.hostId);return X("hook_handler_outcome",{success:!a,projectRoot:this.projectRoot,host:n.hostId,handler:t.type,degraded:a},Date.now()-i),this.logRuntime(a?"warn":"info","handler_outcome",{handler:t.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=jr(s);return this.hookHealth.recordFailure(t.type,n.hostId,a.category,a.reason),X("hook_handler_outcome",{success:false,projectRoot:this.projectRoot,host:n.hostId,handler:t.type,category:a.category,reason:a.reason},Date.now()-i),this.logRuntime("error","handler_outcome",{handler:t.type,host:n.hostId,category:a.category,reason:a.reason,durationMs:Date.now()-i},o),this.hookFailureResponse(t.type,r,s)}}async drainSessionStartSpool(){for(;;){let t=yr(this.projectRoot);if(!t)return;try{let n=await this.handleRequest({type:"session-start",input:t.input});if(n&&"status"in n&&n.status==="degraded")throw new Error(`session_start_degraded:${String(n.reason??"unknown")}`);_r(t),this.logRuntime("info","session_start_spool_accepted",{receiptId:t.receiptId});}catch(n){vr(t),this.logRuntime("warn","session_start_spool_deferred",{reason:n.message,fallback:"durable_spool"});return}}}hookFailureResponse(t,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 t==="pre-tool-use"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:n.policy==="fail_closed"?"deny":"allow",permissionDecisionReason:r,additionalContext:`DevFlow hook degraded: ${r}; fallback=${i}.`}}:t==="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(t){try{if(!t||t.trim()==="")return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};let n=JSON.parse(t);n.tool_input=Iu(n.tool_name,n.tool_input,process.env,this.projectRoot);let o=this.trackSession(n.session_id),r="";if(n.tool_name==="Skill"){let S=n.tool_input?.skill,b=S?Ke(S):null;b&&(r=this.startSkillExecution(o,b));}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 te(this.projectRoot,o,i?.executionId),d=c.getPhase(),l=fr({toolName:n.tool_name,toolInput:n.tool_input,projectRoot:this.projectRoot}),u=l?{permissionDecision:"deny",reason:l}:c.evaluate(n.tool_name,s),p;if(u.permissionDecision==="deny"?p={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:u.reason??"MCP context required"}}:u.additionalContext?p={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:u.additionalContext}}:p={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}},r){let S=p.hookSpecificOutput,b=typeof S.additionalContext=="string"?S.additionalContext:"";S.additionalContext=b?`${b}
36
- ${r}`:r;}n.tool_name.startsWith("mcp__devflow__")&&(p.hookSpecificOutput.updatedInput=n.tool_input);let g={...n.tool_input};delete g._devflow_session_id,delete g._devflow_execution_id,delete g._devflow_tool_use_id;let m=i?.executionId??o,k={eventId:we(o,n.tool_use_id),executionId:m,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:vu(n.tool_name),input:g,duration:0,blocked:p&&p.hookSpecificOutput?.permissionDecision==="deny"},I=await this.telemetry.sendEvent({...k,blockReason:k.blocked?l?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0,error:k.blocked?l?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0});return I&&!k.blocked&&(this.eventMap.push({toolName:n.tool_name,toolUseId:n.tool_use_id,eventId:I,sessionId:o,timestamp:k.timestamp}),this.noteTelemetryOperation()),I&&k.blocked&&await this.telemetry.completeEvent({eventId:I,sessionId:o,error:l?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED",duration:Date.now()-k.timestamp,completedAt:Date.now()}),p}catch{return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}}trackSession(t){let n=t?.trim()||(this.activeSessionIds.size===1?[...this.activeSessionIds][0]:"");if(!n)throw new Error("session_id_required");return this.registerSession(n),n}registerSession(t){this.activeSessionIds.has(t)||(this.activeSessionIds.size===0&&He(this.projectRoot,{bypassCount:0}),this.activeSessionIds.add(t),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.serverManager.addRef(t),this.telemetry.sendSessionStart(t,this.projectRoot,Date.now()).catch(()=>{})),this.runtimeStore.registerSession(t);}startSkillExecution(t,n,o){let r=this.runtimeStore.get(t)?.executionId,i=this.runtimeStore.startExecution(t,n,jn(n));return i.executionId&&i.executionId!==r&&this.telemetry.sendExecutionStart(i.executionId,t,n,i.lastActivityAt,this.projectRoot,i.requiredMcpTools).catch(()=>{}),Fn(n,this.projectRoot,o)}async handleSessionStart(t){try{let n=JSON.parse(t);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(t,n,o){let r=this.eventMap.filter(s=>s.toolName===t&&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(t){if(!yu[t])return null;let n=Math.floor(Date.now()/1e3),o=_t(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(t){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(t){if(!t)return null;let n;try{n=JSON.parse(t);}catch{return null}let o=n.tool_name||"",r=n.tool_input||{},i=n.tool_response,s=this.trackSession(n.session_id);if(Oo({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 R=r?.skill,A=R?Ke(R):null;A&&(this.startSkillExecution(s,A),He(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0}));}if(o.startsWith("mcp__")){let R=this.runtimeStore.get(s),A=new te(this.projectRoot,s,R?.executionId??s);A.recordMcpCall();let E=_u(i);ai(A,o.replace(/^mcp__[^_]+__/,""),E?si(E):"succeeded",E,n.tool_use_id);}let a=this.popEventFromMap(o,s,n.tool_use_id);if(a){let R=typeof i=="string"?i:JSON.stringify(i),A=R.length>5e3?{_truncated:true,_originalSize:R.length,text:R.slice(0,5e3)}:i,E=Date.now()-a.timestamp;await this.telemetry.completeEvent({eventId:a.eventId,sessionId:s,output:A,duration:E,completedAt:Date.now()})&&this.noteTelemetryOperation();}let c=typeof i=="object"&&i!==null?i:null,d=c?.exitCode,l=c?.stderr,u=/^\s*(ls|cat|pwd|cd|echo|head|tail|wc|which|whoami|date|env|printenv|id|hostname|uname)\b/,p=r.command||"",g=JSON.stringify(i),m=Buffer.byteLength(g,"utf8"),f=this.countResults(i),k,I,S=true;if(o.startsWith("mcp__"))k="mcp_call",I={mcpTool:o.replace(/^mcp__[^_]+__/,""),query:r.query??null,resultCount:f,resultSizeBytes:m};else if(o==="Read"||o==="Write"||o==="Edit")k=o==="Read"?"file_read":"file_write",I={filePath:r.file_path??null,fileContentSize:m};else if(o==="Bash"){let R=u.test(p),A=d!==void 0&&d!==0;S=!R||A,k=A?"bash_error":"bash_command",I={command:p||o,exitCode:d??null,stderr:l??null};}else o==="Agent"?(k="subagent",I={subagentType:r.subagent_type??null,description:typeof r.description=="string"?r.description.slice(0,200):null}):o==="WebSearch"||o==="WebFetch"?(k=o==="WebSearch"?"web_search":"web_fetch",I={query:typeof r.query=="string"?r.query.slice(0,200):null}):(S=false,k="tool_use",I={});if(S){let R={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:k,payload:I,command:p||void 0,exitCode:d,stderr:l??void 0,durationMs:0,createdAt:Date.now()};this.postMemoryEvent(R);}let b=So({toolName:o,toolResponse:i,sessionId:s,toolUseId:n.tool_use_id,runtimeStore:this.runtimeStore}),$=this.runtimeStore.get(s),T=Qr({projectRoot:this.projectRoot,sessionId:s,executionId:$?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:n.tool_use_id}),D=this.enforcePostToolUse(o);D&&this.logRuntime("warn","post_tool_enforcement",{tool:o,reason:D},s);let H=[b,T,D].filter(R=>!!R).join(`
29
+ `)}: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 Td(e,t){return !!e.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${t}`)}function Ad(e){if(!e)return false;let t=e.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(t)?false:/(?:已|已经|成功).{0,20}(?:记住|记下|记录|保存|持久化)|跨会话生效|(?:memory|preference).{0,20}(?:saved|remembered|persisted)|status=(?:accepted|committed)/iu.test(t)}function Cd(e,t,n){let o=e.get(t);if(o){for(let r of o.evidenceObligations)n.upsertSessionObligation({obligationId:`evidence:${r.obligationId}`,projectRoot:o.projectRoot,sessionId:t,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,t,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:t,obligationId:i,state:r.status==="resolved"?"satisfied":"degraded",receiptId:a,reason:r.reason,resolvedAt:r.completedAt});}}}var Dd=[/\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],Md=[/\b(?:migration|upgrade|dependency|dependencies|generated files?|write all|rewrite)\b/iu,/(?:迁移|升级|依赖|生成文件|批量写入)/u];function tn(e){let t=`${e.instruction}
30
+ ${JSON.stringify(e.trigger)}`,n=[];Dd.some(r=>r.test(t))&&n.push("high_risk_operation"),Md.some(r=>r.test(t))&&n.push("broad_or_migrating_change"),e.kind==="correction"&&n.push("user_correction_requires_observation");let o=n.includes("high_risk_operation")?"high":n.includes("broad_or_migrating_change")||e.scope==="global"?"medium":"low";return {risk:o,manualOnly:o==="high"||n.includes("broad_or_migrating_change"),reasons:n}}var Od=new Set(["project_convention","user_preference","decision_made","config_discovery"]);function on(e){let t=e.payload.executionId?e.database.getSkillExecution(e.payload.executionId):e.database.getLatestSkillExecutionForSession(e.payload.sessionId),n=e.database.listHostActionsForSession(e.payload.projectRoot,e.payload.sessionId,e.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 e.evidence){if(!Pd(u)){d+=1;continue}let l=Lr(u),m=jd(u,t?.skillName),f=Wr(u),p=Hd(e.payload.projectRoot,l,u.facetKey??u.semanticKey??u.id,m),g=e.database.getLearningCandidate(p),b=tn({scope:"project",kind:l,instruction:f,trigger:m});e.database.upsertLearningCandidate({id:p,projectRoot:e.payload.projectRoot,scope:"project",kind:l,trigger:m,instruction:f,confidence:Fd(u),manualOnly:b.manualOnly,risk:b.risk});g&&g.instruction!==f&&e.database.addLearningCandidateEvidence({id:$r(p,e.payload.sessionId,u.id,"contradicting"),candidateId:p,projectRoot:e.payload.projectRoot,sessionId:e.payload.sessionId,executionId:e.payload.executionId,memoryObservationId:u.id,sourceType:"correction",polarity:"contradicting",outcome:i,evidenceHash:Hr(p,e.payload,u,"contradicting"),receipt:e.payload.closureReceipt,payload:{previousInstruction:g.instruction,replacementInstruction:f,projectRevision:e.payload.projectRevision},createdAt:u.createdAt});let R=e.database.addLearningCandidateEvidence({id:$r(p,e.payload.sessionId,u.id,"supporting"),candidateId:p,projectRoot:e.payload.projectRoot,sessionId:e.payload.sessionId,executionId:e.payload.executionId,memoryObservationId:u.id,outcomeId:o?.id??r?.id,sourceType:$d(u),polarity:"supporting",outcome:i,evidenceHash:Hr(p,e.payload,u,"supporting"),receipt:e.payload.closureReceipt,payload:{semanticKey:u.semanticKey,facetKey:u.facetKey,evidenceStatus:u.evidenceStatus,source:u.source,projectRevision:e.payload.projectRevision,executionStatus:t?.status,policyReasons:b.reasons},createdAt:u.createdAt});c+=1,s.add(p),e.rolloutMode!=="off"&&R.state==="candidate"&&R.supportingSessions>=3&&R.successfulOutcomes>=2&&e.database.transitionLearningCandidate(p,{target:"shadow",reason:"evidence_threshold_satisfied"}).state==="shadow"&&a.push(p);}return {considered:e.evidence.length,accepted:c,excluded:d,candidateIds:[...s],promotedToShadow:a}}function Pd(e){return !(!Od.has(e.type)||e.source!=="explicit_intent"&&e.source!=="manual"&&e.evidenceStatus!=="verified"||!e.narrative.trim()&&!e.title.trim())}function Lr(e){return e.type==="decision_made"?"workflow":e.type==="user_preference"&&(e.semanticValue.startsWith("--")||e.tools.length>0)?"tool_preference":"convention"}function jd(e,t){return {...t?{skills:[t]}:{},...e.entities.length>0?{entities:[...new Set(e.entities)].slice(0,8)}:{},...e.files.length>0?{files:[...new Set(e.files)].slice(0,8)}:{},...e.tools.length>0?{commands:[...new Set(e.tools)].slice(0,8)}:{},semantic:{subject:e.semanticSubject,predicate:e.semanticPredicate,value:e.semanticValue,polarity:e.semanticPolarity}}}function Wr(e){return (e.narrative.trim()||e.title.trim()).replace(/\s+/gu," ").slice(0,1200)}function Fd(e){let t=e.source==="explicit_intent"?.08:0;return Math.max(0,Math.min(1,e.confidence+t))}function $d(e){return e.semanticPolarity==="negative"?"correction":Lr(e)==="tool_preference"?"tool_preference":e.source==="explicit_intent"?"memory":"convention"}function Hd(e,t,n,o){let r={...o,semantic:void 0};return `learning:${createHash("sha256").update(`${e}\0project\0${t}\0${n}\0${stableLearningJson(r)}`).digest("hex").slice(0,24)}`}function $r(e,t,n,o){return `learning-evidence:${createHash("sha256").update(`${e}\0${t}\0${n}\0${o}`).digest("hex").slice(0,24)}`}function Hr(e,t,n,o){return createHash("sha256").update(stableLearningJson({candidateId:e,sessionId:t.sessionId,executionId:t.executionId,closureReceipt:t.closureReceipt,projectRevision:t.projectRevision,observationId:n.id,instruction:Wr(n),polarity:o})).digest("hex")}var se=3e4,an=1e3,el=new Set(["git","npm","pnpm","yarn"]);function qr(e){return {"workflow.worker_start":async({item:t})=>tl(e,t),"workflow.worker_monitor":async({item:t})=>nl(e,t),"workflow.worker_verify":async({item:t})=>ol(e,t),"workflow.worker_merge":async({item:t})=>rl(e,t),"workflow.worker_cleanup":async({item:t})=>il(e,t)}}async function tl(e,t){await Te(e,t,async(n,o)=>{if(o.state==="running"||o.state==="starting"){rn(n,o);return}if(o.state!=="planned")return;let r=`worker-plane:${process.pid}`;n.leaseWorkflowWorker(e,o.workerId,r,se);let i=await createManagedWorktree({projectRoot:e,runId:o.runId,stepId:o.stepId,baseRevision:o.baseRevision,registered:!0});if(i.worktreePath!==o.worktreePath||i.branch!==o.branch){n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"hold",leaseOwner:r,reason:"managed_worktree_identity_mismatch"});return}n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"starting",leaseOwner:r});let s=Br(o.workerId),a=sl(o);createWorkerArtifacts(s,a);let d=createDefaultHostAdapterRegistry().list().find(f=>f.id===o.host);if(!d)throw new E("unsupported_worker_host",`Unsupported worker host ${o.host}`);let u=ae(o.handoff.actionId,"actionId"),l=n.getHostAction(e,u);if(!l)throw new E("worker_host_action_missing",`Host action ${u} was not found`);l.state==="waiting"&&n.startHostAction({actionId:u,projectRoot:e});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(e,o.workerId,r,se);}catch{}finally{f.close();}}});al(s,{state:"running",pid:m.child.pid,owner:r,startedAt:Date.now()}),n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"running",leaseOwner:r,heartbeatAt:Date.now(),leaseExpiresAt:Date.now()+se}),rn(n,o),m.completion.finally(()=>{let f=openGlobalDevFlowDatabase();try{rn(f,o,Date.now());}finally{f.close();}});});}async function nl(e,t){await Te(e,t,async(n,o)=>{if(o.state!=="running"&&o.state!=="starting")return;let r=Br(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=ae(o.handoff.actionId,"actionId");n.reportHostAction({actionId:d,projectRoot:e,report:{workerId:o.workerId,handoff:c},evidenceHash:Gr(c)}),n.transitionWorkflowWorker({projectRoot:e,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:e,payload:{workerId:o.workerId}});return}let i=cl(r),s=typeof i?.pid=="number"?i.pid:void 0;if(s&&ll(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:e,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_process_timeout"});let u=ae(o.handoff.actionId,"actionId");n.failHostAction({actionId:u,projectRoot:e,report:{reason:"worker_process_timeout"}});return}let d=o.leaseOwner??(typeof i?.owner=="string"?i.owner:void 0);throw d?(n.heartbeatWorkflowWorker(e,o.workerId,d,se),Jr("worker_running",an)):new E("worker_lease_owner_missing","Worker lease owner is missing")}n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_exited_without_handoff"});let a=ae(o.handoff.actionId,"actionId");n.failHostAction({actionId:a,projectRoot:e,report:{reason:"worker_exited_without_handoff"}});});}async function ol(e,t){await Te(e,t,async(n,o)=>{if(o.state!=="reported")return;n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"verifying",leaseOwner:o.leaseOwner});let r=o.handoff.terminalHandoff;if(!r)throw new E("worker_handoff_missing","Persisted worker handoff is missing");let i=ae(o.handoff.actionId,"actionId"),s=n.getHostAction(e,i);if(!s)throw new E("worker_host_action_missing",`Host action ${i} was not found`);let a=zr(o),c=new GraderRegistry,d=await Ur(n,o,async()=>verifyWorkerOutput({workerId:o.workerId,projectRoot:e,worktreePath:o.worktreePath,baseRevision:o.baseRevision,parentRevision:await dl(e),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:e,workerId:o.workerId,target:d.state,leaseOwner:o.leaseOwner,reason:d.reason}),d.state==="failed"&&n.failHostAction({actionId:i,projectRoot:e,outcome:"failed",report:{...s.report,verification:d},evidenceHash:d.simulationHash});return}n.transitionWorkflowWorker({projectRoot:e,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:e,payload:{workerId:o.workerId}});});}async function rl(e,t){await Te(e,t,async(n,o)=>{if(o.state!=="merge_ready")return;let r=o.handoff.verification;if(!r?.passed)throw new E("worker_verification_missing","Verified merge evidence is missing");let i=ae(o.handoff.actionId,"actionId"),s=new SerializedWorkerMergeQueue(n,{onMerged:async({mergeCommit:c})=>{n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"merged",leaseOwner:o.leaseOwner,finalRevision:o.finalRevision,reason:`merged:${c}`});let d=n.getHostAction(e,i);n.verifyHostAction({actionId:i,projectRoot:e,report:{...d?.report??{},mergeCommit:c,verification:r},evidenceHash:Gr({mergeCommit:c,verification:r})});},scheduleCleanup:()=>{n.enqueueWork({idempotencyKey:`workflow-worker-cleanup:${o.workerId}:merged`,kind:"workflow.worker_cleanup",projectRoot:e,payload:{workerId:o.workerId}});}}),a=await Ur(n,o,()=>s.enqueueAndMerge({workerId:o.workerId,projectRoot:e,baseRevision:o.baseRevision,verification:r,message:`merge(devflow-worker): ${o.runId}/${o.stepId}`}));a.state==="conflict"&&n.transitionWorkflowWorker({projectRoot:e,workerId:o.workerId,target:"hold",leaseOwner:o.leaseOwner,reason:a.reason??"merge_conflict"});});}async function il(e,t){await Te(e,t,async(n,o)=>{let r=t.payload,i=await cleanupManagedWorktree({repositoryRoot:e,worktreePath:o.worktreePath,branch:o.branch,registered:!0,handoffDurable:!!o.handoff.terminalHandoff||r.operatorApproved===!0});if(!i.cleaned)throw Jr(`cleanup_${i.reason??"refused"}`,3e4)});}async function Ur(e,t,n){let o=t.leaseOwner;if(!o)return n();let r=setInterval(()=>{try{e.heartbeatWorkflowWorker(t.projectRoot,t.workerId,o,se);}catch{}},Math.floor(se/3));r.unref();try{return await n()}finally{clearInterval(r);}}async function Te(e,t,n){let o=ul(t.payload),r=openGlobalDevFlowDatabase();try{let i=r.getWorkflowWorker(e,o);if(!i)throw new E("worker_not_found",`Worker ${o} was not found`);await n(r,i);}finally{r.close();}}function sl(e){let t=e.handoff.task;if(!t||typeof t!="object"||Array.isArray(t))throw new E("worker_task_missing","Worker task envelope is missing");let n=zr(e);return {workerId:e.workerId,runId:e.runId,stepId:e.stepId,projectRoot:e.projectRoot,worktreePath:e.worktreePath,baseRevision:e.baseRevision,contextReceipt:e.contextReceipt,retrievalSessionId:e.retrievalSessionId,allowedFiles:e.allowedFiles,requiredTools:[],task:t,verification:{commands:n,graders:["receipt_validity","lifecycle_terminal_state","workflow_evidence"]},constraints:{recursiveWorkers:false,maxContextCycles:3}}}function zr(e){let t=e.handoff.verificationCommands;if(!Array.isArray(t)||t.length===0)throw new E("verification_contract_missing","Worker verification commands are missing");return t.map(n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new E("verification_contract_invalid","Worker verification command is malformed");let o=n;if(typeof o.command!="string"||!el.has(o.command)||!Array.isArray(o.args)||o.args.some(r=>typeof r!="string"))throw new E("verification_contract_invalid","Worker verification command is not allowlisted");return {command:o.command,args:o.args}})}function Br(e){let t=workerCoordinationRoot(e,homedir());return {root:t,taskFile:join(t,"task.json"),handoffFile:join(t,"handoff.json"),statusFile:join(t,"status.json"),stdoutFile:join(t,"stdout.log"),stderrFile:join(t,"stderr.log")}}function al(e,t){writeJsonAtomic(e.statusFile,t);}function cl(e){try{return JSON.parse(readFileSync$1(e.statusFile,"utf8"))}catch{return null}}function rn(e,t,n=Date.now()+an){e.enqueueWork({idempotencyKey:`workflow-worker-monitor:${t.workerId}:${Math.floor(n/an)}`,kind:"workflow.worker_monitor",projectRoot:t.projectRoot,payload:{workerId:t.workerId},nextAttemptAt:n,maxAttempts:1e3});}async function dl(e){let{gitRevision:t}=await import('@devflow-tools/workflow-engine');return t(e,"HEAD")}function ll(e){try{return process.kill(e,0),!0}catch{return false}}function Jr(e,t){return Object.assign(new Error(e),{category:e,retryAfterMs:t,retryWithoutAttempt:true})}function ul(e){if(!e||typeof e!="object"||typeof e.workerId!="string")throw new E("invalid_worker_payload","Worker work item requires workerId");return e.workerId}function ae(e,t){if(typeof e!="string"||!e.trim())throw new E("worker_identity_missing",`Worker ${t} is missing`);return e}function Gr(e){return createHash("sha256").update(JSON.stringify(e)).digest("hex")}var fl=new Set(["Write","Edit","NotebookEdit"]);function Qr(e){if(!fl.has(e.toolName)||_l(e.toolResponse))return null;let t=vl(e.projectRoot,e.toolInput);if(!t)return null;let n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let o=n.getActiveContextReceipt(e.projectRoot,e.sessionId,e.executionId),r=o?.canonicalAction?.verificationPlan??[];if(!o||r.length===0)return null;let i=[],s=[];for(let c of r){let d=gl({projectRoot:e.projectRoot,targetFile:t,kind:c.kind,mode:c.mode==="write"?"write":"check",required:c.required===!0,contextReceipt:o.contextHash}),u=`${o.contextHash}\0${e.toolUseId??t}\0${c.kind}\0${t}`,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:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,kind:"evidence_contract",state:"degraded",payload:{subtype:"policy_verification",status:"unknown",verificationKind:c.kind,targetFile:t,contextReceipt:o.contextHash},reason:g,createdAt:m,updatedAt:m,resolvedAt:m}),s.push(c.kind),c.required===!0&&D({projectRoot:e.projectRoot,sessionId:e.sessionId,requestId:o.requestId,executionId:e.executionId,kind:"verification.failed",payload:{receiptId:l,reasonCode:g},dedupeKey:`${l}:unavailable`,producer:"devflow-verification-scheduler"});continue}let f={...d,obligationId:l,sessionId:e.sessionId,executionId:e.executionId,requestId:o.requestId};n.upsertSessionObligation({obligationId:l,projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,kind:"evidence_contract",state:"open",payload:{subtype:"policy_verification",status:"scheduled",verificationKind:c.kind,command:d.display,targetFile:t,contextReceipt:o.contextHash,required:c.required===!0},createdAt:m,updatedAt:m});let p=n.enqueueWork({idempotencyKey:l,kind:"verification.policy",projectRoot:e.projectRoot,sessionId:e.sessionId,payload:f,maxAttempts:2,nextAttemptAt:m});D({projectRoot:e.projectRoot,sessionId:e.sessionId,requestId:o.requestId,executionId:e.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(`
31
+ `)||null}finally{n.close();}}async function Xr(e,t){let n=hl(e,t.payload),o=await yl(n,e),r=n.kind==="typecheck"?Rl(o.output,n.targetFile,e):[],i=Vr({command:n.command,args:n.args}),s=openGlobalDevFlowDatabase();try{let a=xl(e),c=n.kind==="typecheck"?s.getPolicyVerificationBaseline(e,n.kind,i):null,d=c&&c.sourceRevision===a?c:null,u=d?r.filter(h=>!d.diagnosticHashes.includes(h)):[],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:${Vr({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,b=s.getSessionObligation(e,n.sessionId,n.obligationId);if(b?.state==="open"&&(s.upsertSessionObligation({...b,payload:{...b.payload,status:l,outcome:p},updatedAt:Date.now()}),l!=="failed"&&s.resolveSessionObligation({projectRoot:e,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:e,kind:n.kind,commandHash:i,diagnosticHashes:[],sourceRevision:a,updatedAt:Date.now()}),Sl(s,n,p),D({projectRoot:e,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"&&D({projectRoot:e,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 h=new Error(`Policy verification failed: ${n.display}`);throw h.category="policy_verification_failed",h}return p}finally{s.close();}}function gl(e){let t=Il(e.projectRoot),n=wl(e.projectRoot),o=t?.scripts??{},r={...t?.dependencies,...t?.devDependencies},i=null;if(e.kind==="formatter"&&(r.prettier||kl(e.projectRoot)))i=st(n,"prettier",[e.mode==="write"?"--write":"--check",e.targetFile],6e4);else if(e.kind==="typecheck"){let s=ln(o,["typecheck","type-check","check:types"]);s?i=cn(n,s,12e4):r.typescript&&existsSync(join(e.projectRoot,"tsconfig.json"))&&(i=st(n,"tsc",["--noEmit","--pretty","false"],12e4));}else if(e.kind==="lint"){let s=ln(o,["lint"]);s&&(i=cn(n,s,12e4));}else if(e.kind==="test"){let s=bl(e.projectRoot,e.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(e.kind==="build"){let s=ln(o,["build"]);s&&(i=cn(n,s,18e4));}else e.kind==="generated_files"&&(i={command:"git",args:["diff","--check","--",e.targetFile],timeoutMs:3e4});return i?{kind:e.kind,...i,display:[i.command,...i.args].map(El).join(" "),required:e.required,targetFile:e.targetFile,contextReceipt:e.contextReceipt}:null}function cn(e,t,n){return e==="yarn"?{command:"yarn",args:["run",t],timeoutMs:n}:e==="pnpm"?{command:"pnpm",args:["run",t],timeoutMs:n}:e==="bun"?{command:"bun",args:["run",t],timeoutMs:n}:{command:"npm",args:["run",t],timeoutMs:n}}function st(e,t,n,o){return e==="pnpm"?{command:"pnpm",args:["exec",t,...n],timeoutMs:o}:e==="yarn"?{command:"yarn",args:[t,...n],timeoutMs:o}:e==="bun"?{command:"bunx",args:[t,...n],timeoutMs:o}:{command:"npx",args:["--no-install",t,...n],timeoutMs:o}}function hl(e,t){if(!t||typeof t!="object"||Array.isArray(t))throw dn();let n=t,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)||!Zr(e,n.targetFile))throw dn();return n}function dn(){let e=new Error("Policy verification work payload is invalid");return e.category="invalid_payload",e}function yl(e,t){return new Promise(n=>{let o=spawn$1(e.command,e.args,{cwd:t,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();},e.timeoutMs);o.on("error",u=>{clearTimeout(d),s({exitCode:null,timedOut:false,spawnError:true,output:`${r}
32
+ ${u.message}`.slice(-32768)});}),o.on("close",u=>{clearTimeout(d),s({exitCode:u,timedOut:c,spawnError:false,output:r});});})}function vl(e,t){let n=t.file_path??t.notebook_path;if(typeof n!="string"||!n.trim())return null;let o=isAbsolute(n)?resolve(n):resolve(e,n);return Zr(e,o)?relative(e,o).split(sep).join("/"):null}function Zr(e,t){let n=isAbsolute(t)?resolve(t):resolve(e,t),o=relative(resolve(e),n);return o!==""&&o!==".."&&!o.startsWith(`..${sep}`)&&!isAbsolute(o)}function _l(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return t.ok===false||t.success===false||t.isError===true||!!t.error}function Il(e){try{return JSON.parse(readFileSync$1(join(e,"package.json"),"utf8"))}catch{return null}}function wl(e){return existsSync(join(e,"pnpm-lock.yaml"))?"pnpm":existsSync(join(e,"yarn.lock"))?"yarn":existsSync(join(e,"bun.lockb"))||existsSync(join(e,"bun.lock"))?"bun":"npm"}function kl(e){return [".prettierrc",".prettierrc.json",".prettierrc.js",".prettierrc.cjs","prettier.config.js","prettier.config.cjs"].some(t=>existsSync(join(e,t)))}function ln(e,t){return t.find(n=>typeof e[n]=="string"&&e[n].trim())??null}function bl(e,t){let n=t.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(e,a)))return a}let r=join(e,t.split("/").slice(0,-1).join("/")),i=t.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(e,join(r,s)).split(sep).join("/"))[0]??null}catch{return null}}function Rl(e,t,n){let o=t.split(sep).join("/"),r=resolve(n,t).split(sep).join("/"),i=e.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 Sl(e,t,n){if(!t.executionId)return;let o=e.getSkillExecution(t.executionId);if(!o)return;let r=o.metadata&&typeof o.metadata=="object"?o.metadata:{},i=Array.isArray(r.policyVerificationOutcomes)?r.policyVerificationOutcomes:[];e.updateSkillExecution(t.executionId,{metadata:{...r,policyVerificationOutcomes:[...i,n]}});}function xl(e){try{let t=readFileSync$1(join(e,".git","HEAD"),"utf8").trim();return t.startsWith("ref:")?readFileSync$1(join(e,".git",t.slice(5).trim()),"utf8").trim():t}catch{return}}function Vr(e){return createHash("sha256").update(JSON.stringify(e)).digest("hex")}function El(e){return /^[A-Za-z0-9_./:@=-]+$/u.test(e)?e:JSON.stringify(e)}function oi(e){let t=Date.now(),n=Vl(e.projectRoot),o=claudeCodeRuntimeAdapter.normalizePrompt(e.hostEvent??{session_id:e.sessionId,prompt:e.prompt},{projectRoot:n}),r=o.sourceHash,i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100});try{let s=i.getTaskIntentArtifactBySource({projectRoot:n,sessionId:e.sessionId,sourceHash:r});if(s){let x=Wl(i,s);return {artifact:Bl(s),queryPlan:Jl(x),memoryIdentity:ei(s),reused:!0}}let a=Kl(o.rawPrompt,o.command),c=buildRetrievalTaskPlan({query:a,parsedIntent:parseIntent(a,{segmentation:"regex"}),targetAnchors:ti(o.rawPrompt),activeSkill:o.activeSkill,command:o.command}),d=resolveSemanticResolutionMode(n),u=d==="off"?null:extractStructuralSemanticEvidence({prompt:ni(o.rawPrompt),command:o.command,targetAnchors:ti(o.rawPrompt)}),l=u?createProvisionalSemanticFrame({normalizedPrompt:u.normalizedPrompt,sourceHash:r,structural:u,now:o.timestamp}):null,m=`turn:${Ae(`${e.sessionId}\0${r}`)}`,f=`request:${Ae(`${n}\0${e.sessionId}\0${m}`)}`,p={projectRoot:n,projectId:`project:${Ae(n)}`,hostId:o.hostId,sessionId:e.sessionId,turnId:m,requestId:f},g=[{source:"deterministic_parser",field:"intent",value:c.intent,reason:c.classification.intentReason,confidence:c.classification.intentSource==="semantic_override"?.95:.75},{source:o.command?"slash_command":"deterministic_parser",field:"action",value:c.action,reason:c.classification.actionReason,confidence:o.command||c.action!=="analyze"?.95:.65},...c.targetAnchors.map(x=>({source:"target_anchor",field:"target",value:x,reason:"explicit_prompt_target",confidence:1}))],b={identity:p,version:1,rawPrompt:o.rawPrompt,normalizedPrompt:ni(o.rawPrompt),...o.command?{command:o.command}:{},slashArgs:o.slashArgs,...o.activeSkill?{activeSkill:o.activeSkill}:{},intent:c.intent,action:c.action,entities:c.entities,targetAnchors:c.targetAnchors,policyConstraints:Gl(o.rawPrompt),classificationEvidence:g,sourceEventIds:[o.sourceEventId??`host-event:${r.slice(0,24)}`],sourceHash:r,createdAt:o.timestamp},h={...b,artifactHash:Yl(b)},R=buildChannelQueryPlan({artifact:h,taskPlan:c,expandedTerms:e.expandedTerms});if(i.appendTaskIntentArtifact(Ul(h)),i.appendChannelQueryPlan(zl(R)),l){i.appendSemanticResolution({frameHash:l.frameHash,...p,sourceHash:r,artifactHash:h.artifactHash,artifactRevision:h.version,state:l.state,generatedBy:l.resolver.generatedBy,modelId:l.resolver.modelId,modelRevision:l.resolver.modelRevision,routeCatalogVersion:l.resolver.routeCatalogVersion,thresholdVersion:l.resolver.thresholdVersion,route:{status:"unavailable",reason:"prompt_hook_bounded"},sampling:{attempted:!1,status:"not_needed"},conflicts:[],frame:l,durationMs:0,createdAt:l.createdAt});let x=projectSemanticFrameToLegacyIntent(l);(x.intent!==h.intent||x.action!==h.action)&&emitSemanticControlLog({event:"semantic.regex.shadow_mismatch",identity:p,level:"info",timestamp:Date.now(),data:{mode:d,frameHash:l.frameHash,legacyIntent:h.intent,legacyAction:h.action,semanticIntent:x.intent,semanticAction:x.action}});}let w=ql(i,h);try{appendTaskRuntimeBoundary({projectRoot:n,taskSpec:taskSpecFromImmutableIntent(h),kind:"task.spec.bound",payload:{intentArtifactHash:h.artifactHash},dedupeKey:h.artifactHash,producer:"devflow-task-intent",createdAt:h.createdAt,database:i});}catch(x){emitSemanticControlLog({event:"task.runtime.shadow_mismatch",identity:p,level:"warn",timestamp:Date.now(),data:{stage:"task.spec.bound",reason:x instanceof Error?x.message:String(x),authority:"legacy"}});}return emitSemanticControlLog({event:"host.prompt.normalized",identity:p,level:"info",timestamp:Date.now(),data:{sourceHash:r,command:h.command,activeSkill:h.activeSkill,rawPromptBytes:Buffer.byteLength(h.rawPrompt)}}),emitSemanticControlLog({event:"intent.artifact.created",identity:p,level:"info",timestamp:Date.now(),data:{artifactHash:h.artifactHash,intent:h.intent,action:h.action,evidence:h.classificationEvidence,entityCount:h.entities.length,targetCount:h.targetAnchors.length}}),emitSemanticControlLog({event:"intent.artifact.persisted",identity:p,level:"info",timestamp:Date.now(),data:{artifactHash:h.artifactHash,version:h.version,sourceHash:h.sourceHash,parserMode:"regex",captureLatencyMs:Date.now()-t}}),emitSemanticControlLog({event:"query.plan.created",identity:p,level:"info",timestamp:Date.now(),data:{planHash:R.planHash,sourceIntentHash:R.sourceIntentHash,generatedBy:R.generatedBy,codeQueries:R.code.length,memoryQueries:R.memory.length,knowledgeQueries:R.knowledge.length,knowledgeDisposition:R.knowledge.map(x=>x.requirement)}}),emitSemanticControlLog({event:"terminal.transition.persisted",identity:p,level:"info",timestamp:Date.now(),data:{state:"intent_bound",receiptId:w,sourceIntentHash:h.artifactHash}}),{artifact:h,queryPlan:R,memoryIdentity:ei(h),reused:!1}}finally{i.close();}}function Wl(e,t){let n=e.getChannelQueryPlanForIntent({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:t.turnId,sourceIntentHash:t.artifactHash});if(!n)throw new Error(`QUERY_PLAN_NOT_FOUND:${t.artifactHash}`);return n}function ql(e,t){let n=e.getLatestTerminalTransition(t.identity.projectRoot,t.identity.sessionId,t.identity.turnId);if(n)return n.receiptId;let o=`terminal:${Ae(`${t.artifactHash}\0open`)}`;return e.appendTerminalTransition({...t.identity,sequence:1,toState:"open",receiptId:o,reason:"host_prompt_accepted",payload:{sourceHash:t.sourceHash},createdAt:t.createdAt}),e.appendTerminalTransition({...t.identity,sequence:2,fromState:"open",toState:"intent_bound",receiptId:`terminal:${Ae(`${t.artifactHash}\0intent_bound`)}`,sourceReceiptId:o,reason:"immutable_intent_persisted",payload:{intentArtifactHash:t.artifactHash},createdAt:Math.max(t.createdAt,Date.now())}).receiptId}function Ul(e){return {...e.identity,version:e.version,supersedesHash:e.supersedesHash,rawPrompt:e.rawPrompt,normalizedPrompt:e.normalizedPrompt,command:e.command,slashArgs:e.slashArgs,activeSkill:e.activeSkill,intent:e.intent,action:e.action,entities:e.entities,targetAnchors:e.targetAnchors,policyConstraints:e.policyConstraints,classificationEvidence:e.classificationEvidence.map(t=>({...t})),sourceEventIds:e.sourceEventIds,sourceHash:e.sourceHash,artifactHash:e.artifactHash,createdAt:e.createdAt}}function zl(e){return {...e.identity,sourceIntentHash:e.sourceIntentHash,planHash:e.planHash,code:e.code.map(t=>({...t})),memory:e.memory.map(t=>({...t})),knowledge:e.knowledge.map(t=>({...t})),generatedBy:e.generatedBy,degradation:e.degradation?{...e.degradation}:void 0,createdAt:e.createdAt}}function Bl(e){return {identity:ri(e),version:e.version,...e.supersedesHash?{supersedesHash:e.supersedesHash}:{},rawPrompt:e.rawPrompt,normalizedPrompt:e.normalizedPrompt,...e.command?{command:e.command}:{},slashArgs:e.slashArgs,...e.activeSkill?{activeSkill:e.activeSkill}:{},intent:e.intent,action:e.action,entities:e.entities,targetAnchors:e.targetAnchors,policyConstraints:e.policyConstraints,classificationEvidence:e.classificationEvidence,sourceEventIds:e.sourceEventIds,sourceHash:e.sourceHash,artifactHash:e.artifactHash,createdAt:e.createdAt}}function Jl(e){return {identity:ri(e),sourceIntentHash:e.sourceIntentHash,planHash:e.planHash,code:e.code,memory:e.memory,knowledge:e.knowledge,generatedBy:e.generatedBy,...e.degradation?{degradation:e.degradation}:{},createdAt:e.createdAt}}function ri(e){return {projectRoot:e.projectRoot,projectId:e.projectId,hostId:e.hostId,sessionId:e.sessionId,turnId:e.turnId,requestId:e.requestId,...e.executionId?{executionId:e.executionId}:{}}}function ei(e){let t=e.rawPrompt.trim().slice(0,4e3);return {turnId:e.identity?e.identity.turnId:e.turnId,eventId:`memory-turn:${(e.identity?e.identity.turnId:e.turnId).replace(/^turn:/u,"")}`,promptHash:createHash("sha256").update(t).digest("hex"),createdAt:e.createdAt}}function ti(e){let t=e.match(/(?:^|[\s`'"(])((?:\.{0,2}\/)?(?:[A-Za-z0-9_@.-]+\/)+[A-Za-z0-9_@.-]+(?:\.[A-Za-z0-9]+)?)/gu)??[];return ii(t.map(n=>n.trim().replace(/^[`'"(]+|[`'"),.;:,。;:]+$/gu,"")).filter(n=>!n.startsWith("/")||/\.[A-Za-z0-9]+$/u.test(n))).slice(0,16)}function Gl(e){let t=e.match(/--[a-z0-9][a-z0-9-]*(?:=[^\s,。;;]+)?/giu)??[];return ii(t.map(n=>n.normalize("NFKC"))).slice(0,16)}function Kl(e,t){return t&&e.trimStart().replace(new RegExp(`^\\/${Ql(t)}\\b`,"iu"),"").trim()||e.trim()}function ni(e){return e.normalize("NFKC").replace(/\s+/gu," ").trim().slice(0,4e3)}function ii(e){return [...new Set(e.filter(Boolean))]}function Vl(e){let t=resolve(e);try{return realpathSync(t)}catch{return t}}function Yl(e){return createHash("sha256").update(fn(e)).digest("hex")}function Ae(e){return createHash("sha256").update(e).digest("hex").slice(0,24)}function fn(e){if(e===null||typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number")return Number.isFinite(e)?JSON.stringify(e):"null";if(Array.isArray(e))return `[${e.map(fn).join(",")}]`;if(!e||typeof e!="object")return JSON.stringify(String(e));let t=e;return `{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${fn(t[n])}`).join(",")}}`}function Ql(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}var fu=600*1e3,gu=2e3,hu=250,yu=2e3,vu=1e3,ai=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(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.status=="string"?t.status:void 0;if(!(t.ok===false||t.success===false||t.isError===true||n==="failed"||n==="rejected"||n==="unavailable"||n==="warming"||!!t.error))return;let r=t.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 ci(e){return /timeout|timed out|deadline|warming/i.test(e)?"timeout":/unavailable|not active|unknown tool|not found|not registered|route not found/i.test(e)?"unavailable":"failed"}function di(e,t,n,o,r){let i=e.recordDomainActionOutcome;typeof i=="function"&&i.call(e,t,n,o,r);}function Ru(e){switch(e){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 yn(e){return typeof e=="string"&&e.trim().length>0}function Su(e,t,n=process.env,o){if(!e.startsWith("mcp__devflow__"))return t;let r=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{};if(yn(r.projectRoot))return r;let i=yn(n.CLAUDE_PROJECT_DIR)?n.CLAUDE_PROJECT_DIR:o;return yn(i)&&(r.projectRoot=i),r}var vn=class{constructor(t,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=t,this.socketPath=getDaemonSocketPath(t),this.pidPath=getDaemonPidPath(t),this.telemetry=new ee,this.runtimeStore=new L(this.projectRoot),this.serverManager=new Fe(t),this.hookRuntime=Ar(t),this.hookHealth=new it(t),this.hookHandlers=Mr({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=>en(o,this.hookRuntime,this.hostRuntime??{hostId:"unresolved",capabilities:new Map,profiles:new Set(["minimal","standard","strict"])}).policy}),this.initialSessionInput=n,this.workRuntime=new ot({projectRoot:t,handlers:{...qr(t),"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 E("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 he({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 E("invalid_payload","Context prefetch identity is incomplete");let{createEngines:i,writeContextPrefetchCache:s}=await import('@devflow-tools/context-engine'),a=await i(this.projectRoot);try{let c=await a.context.buildTaskContext(r.prompt,{mode:"fast",sessionId:r.sessionId,executionId:r.executionId,activeSkill:r.skillName});if(!s({projectRoot:this.projectRoot,query:r.prompt,sessionId:r.sessionId,executionId:r.executionId,profileFingerprint:r.profileFingerprint,rolloutMode:r.rolloutMode,retrievalVersion:r.retrievalVersion},c))throw new Error("Context prefetch envelope was not receipt-valid")}finally{for(let c of Object.values(a))try{c.close?.();}catch{}}},"verification.policy":async({item:o})=>{await Xr(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 E("invalid_payload","Learning analysis identity is incomplete");let i=openGlobalDevFlowDatabase();try{let s=await(await this.getMemoryGate()).listLearningEvidence(r.sessionId),a=on({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&&D({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(t,n,o={},r){let i=r?this.runtimeStore.get(r):void 0;emitSemanticControlLog({event:t==="warn"||t==="error"?"hook.runtime.degraded":"hook.runtime.completed",identity:{projectRoot:this.projectRoot,sessionId:r,executionId:i?.executionId},level:t,timestamp:Date.now(),data:{stage:n,...o}});}async start(){this.hostRuntime=await Dr(this.projectRoot),mkdirSync(dirname(this.socketPath),{recursive:true,mode:448}),await this.cleanStaleStartupResources(),this.server=createServer(t=>this.handleConnection(t));try{await this.listen(),this.writePidFile(),Xn(this.projectRoot,process.pid);}catch(t){throw await this.closeServer(),this.cleanupOwnedResources(),t}if(this.server.on("error",t=>{this.logRuntime("error","server_error",{reason:t.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(t=>{this.logRuntime("info","embedding_ready",{source:t.source,cacheRootHash:createHash("sha256").update(t.cacheRoot).digest("hex").slice(0,16)});}).catch(t=>{this.logRuntime("warn","embedding_unavailable",{reason:t.message,fallback:"lexical_retrieval"});}),this.workRuntime.start(),this.initialSessionInput){let t=this.initialSessionInput;this.initialSessionInput=void 0,this.handleRequest({type:"session-start",input:t});}this.drainSessionStartSpool(),this.scheduleMemoryTurnSpoolDrain(0),this.scheduleSessionFinalizeSpoolDrain(0),this.resetIdleTimer();}handleConnection(t){let n="",o=false,r=false,i=0,s=Promise.resolve();t.setEncoding("utf8");let a=()=>{r||(r=true,clearTimeout(c),t.destroy());},c=setTimeout(()=>{a();},gu).unref(),d=async u=>{if(!r){r=true,clearTimeout(c);try{await this.writeFrame(t,u);}catch{}finally{t.destroy();}}};t.on("data",u=>{if(r)return;n+=u;let l=n.split(`
33
+ `);if(n=l.pop()??"",Buffer.byteLength(n,"utf8")>ai){a();return}if(l.length===0)return;let m=0;for(let f of l){let p=Buffer.byteLength(f,"utf8");if(p>ai){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(t,g);}catch(p){r||await this.writeFrame(t,{error:p.message});}}}).catch(()=>{a();}).finally(()=>{i-=m;});}),t.on("close",()=>clearTimeout(c)),t.on("error",()=>{});}writeFrame(t,n){return new Promise((o,r)=>{if(t.destroyed||!t.writable){r(new Error("Socket is not writable"));return}let i=false,s=true,a=false,c=setTimeout(()=>{t.destroy(),u(new Error("Timed out writing daemon response"));},vu),d=()=>{clearTimeout(c),t.off("close",l),t.off("error",m),t.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();};t.once("close",l),t.once("error",m),t.write(`${JSON.stringify(n)}
34
+ `,g=>{if(g){u(g);return}i=true,u();})||(s=false,t.once("drain",f));})}async cleanStaleStartupResources(){let t=this.getPathIdentity(this.socketPath);if(t){if(await this.isSocketAcceptingConnections())throw new Error(`Daemon socket already active for ${this.projectRoot}`);this.removePathIfOwned(this.socketPath,t,"stale socket");}let n=this.getPathIdentity(this.pidPath);n&&this.removePathIfOwned(this.pidPath,n,"stale PID file");}getPathIdentity(t){try{let n=lstatSync(t);return {dev:n.dev,ino:n.ino}}catch(n){if(n.code==="ENOENT")return null;throw n}}pathMatchesIdentity(t,n){if(!n)return false;try{let o=this.getPathIdentity(t);return o?.dev===n.dev&&o.ino===n.ino}catch(o){return this.logRuntime("warn","path_ownership_check",{reason:o.message}),false}}writePidFile(){let t=openSync(this.pidPath,"wx",384);try{writeFileSync(t,`${process.pid}
35
+ `);let n=fstatSync(t);this.pidIdentity={dev:n.dev,ino:n.ino};}finally{closeSync(t);}}removePathIfOwned(t,n,o,r){try{return !this.pathMatchesIdentity(t,n)||r!==void 0&&readFileSync(t,"utf8")!==r||!this.pathMatchesIdentity(t,n)?!1:(unlinkSync(t),!0)}catch(i){return i.code!=="ENOENT"&&this.logRuntime("warn","owned_path_cleanup",{label:o,reason:i.message}),false}}isSocketAcceptingConnections(){return new Promise((t,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(),t(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((t,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,t();}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 t=openGlobalDevFlowDatabase();try{if(t.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{t.close();}this.logRuntime("info","idle_timeout_exit"),this.shutdown();},fu).unref());}async handleRequest(t){let n=this.hostRuntime,o=xu(t.input);if(!n)return this.hookFailureResponse(t.type,{enabled:false,policy:"fail_open",reason:"host_adapter_not_ready",fallback:"host_event_continues_without_devflow_handler"});let r=en(t.type,this.hookRuntime,n);if(!r.enabled)return this.hookFailureResponse(t.type,r);let i=Date.now();try{let s=Pr(t.type,await Or({registry:this.hookHandlers,requestType:t.type,rawInput:t.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(t.type,n.hostId,"degraded",c);}else this.hookHealth.recordSuccess(t.type,n.hostId);return X("hook_handler_outcome",{success:!a,projectRoot:this.projectRoot,host:n.hostId,handler:t.type,degraded:a},Date.now()-i),this.logRuntime(a?"warn":"info","handler_outcome",{handler:t.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=jr(s);return this.hookHealth.recordFailure(t.type,n.hostId,a.category,a.reason),X("hook_handler_outcome",{success:false,projectRoot:this.projectRoot,host:n.hostId,handler:t.type,category:a.category,reason:a.reason},Date.now()-i),this.logRuntime("error","handler_outcome",{handler:t.type,host:n.hostId,category:a.category,reason:a.reason,durationMs:Date.now()-i},o),this.hookFailureResponse(t.type,r,s)}}async drainSessionStartSpool(){for(;;){let t=yr(this.projectRoot);if(!t)return;try{let n=await this.handleRequest({type:"session-start",input:t.input});if(n&&"status"in n&&n.status==="degraded")throw new Error(`session_start_degraded:${String(n.reason??"unknown")}`);vr(t),this.logRuntime("info","session_start_spool_accepted",{receiptId:t.receiptId});}catch(n){_r(t),this.logRuntime("warn","session_start_spool_deferred",{reason:n.message,fallback:"durable_spool"});return}}}hookFailureResponse(t,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 t==="pre-tool-use"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:n.policy==="fail_closed"?"deny":"allow",permissionDecisionReason:r,additionalContext:`DevFlow hook degraded: ${r}; fallback=${i}.`}}:t==="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(t){try{if(!t||t.trim()==="")return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};let n=JSON.parse(t);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,w=R?Ke(R):null;w&&(r=this.startSkillExecution(o,w));}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 te(this.projectRoot,o,i?.executionId),d=c.getPhase(),u=fr({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,w=typeof R.additionalContext=="string"?R.additionalContext:"";R.additionalContext=w?`${w}
36
+ ${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,b={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"},h=await this.telemetry.sendEvent({...b,blockReason:b.blocked?u?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0,error:b.blocked?u?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0});return h&&!b.blocked&&(this.eventMap.push({toolName:n.tool_name,toolUseId:n.tool_use_id,eventId:h,sessionId:o,timestamp:b.timestamp}),this.noteTelemetryOperation()),h&&b.blocked&&await this.telemetry.completeEvent({eventId:h,sessionId:o,error:u?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED",duration:Date.now()-b.timestamp,completedAt:Date.now()}),m}catch{return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}}trackSession(t){let n=t?.trim()||(this.activeSessionIds.size===1?[...this.activeSessionIds][0]:"");if(!n)throw new Error("session_id_required");return this.registerSession(n),n}registerSession(t){this.activeSessionIds.has(t)||(this.activeSessionIds.size===0&&He(this.projectRoot,{bypassCount:0}),this.activeSessionIds.add(t),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.serverManager.addRef(t),this.telemetry.sendSessionStart(t,this.projectRoot,Date.now()).catch(()=>{})),this.runtimeStore.registerSession(t);}startSkillExecution(t,n,o){let r=this.runtimeStore.get(t)?.executionId,i=this.runtimeStore.startExecution(t,n,jn(n));return i.executionId&&i.executionId!==r&&this.telemetry.sendExecutionStart(i.executionId,t,n,i.lastActivityAt,this.projectRoot,i.requiredMcpTools).catch(()=>{}),Fn(n,this.projectRoot,o)}async handleSessionStart(t){try{let n=JSON.parse(t);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(t,n,o){let r=this.eventMap.filter(s=>s.toolName===t&&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(t){if(!ku[t])return null;let n=Math.floor(Date.now()/1e3),o=vt(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(t){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(t){if(!t)return null;let n;try{n=JSON.parse(t);}catch{return null}let o=n.tool_name||"",r=n.tool_input||{},i=n.tool_response,s=this.trackSession(n.session_id);if(Oo({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,C=S?Ke(S):null;C&&(this.startSkillExecution(s,C),He(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0}));}if(o.startsWith("mcp__")){let S=this.runtimeStore.get(s),C=new te(this.projectRoot,s,S?.executionId??s);C.recordMcpCall();let T=bu(i);di(C,o.replace(/^mcp__[^_]+__/,""),T?ci(T):"succeeded",T,n.tool_use_id);}let a=this.popEventFromMap(o,s,n.tool_use_id);if(a){let S=typeof i=="string"?i:JSON.stringify(i),C=S.length>5e3?{_truncated:true,_originalSize:S.length,text:S.slice(0,5e3)}:i,T=Date.now()-a.timestamp;await this.telemetry.completeEvent({eventId:a.eventId,sessionId:s,output:C,duration:T,completedAt:Date.now()})&&this.noteTelemetryOperation();}let c=typeof i=="object"&&i!==null?i:null,d=c?.exitCode,u=c?.stderr,l=/^\s*(ls|cat|pwd|cd|echo|head|tail|wc|which|whoami|date|env|printenv|id|hostname|uname)\b/,m=r.command||"",f=JSON.stringify(i),p=Buffer.byteLength(f,"utf8"),g=this.countResults(i),b,h,R=true;if(o.startsWith("mcp__"))b="mcp_call",h={mcpTool:o.replace(/^mcp__[^_]+__/,""),query:r.query??null,resultCount:g,resultSizeBytes:p};else if(o==="Read"||o==="Write"||o==="Edit")b=o==="Read"?"file_read":"file_write",h={filePath:r.file_path??null,fileContentSize:p};else if(o==="Bash"){let S=l.test(m),C=d!==void 0&&d!==0;R=!S||C,b=C?"bash_error":"bash_command",h={command:m||o,exitCode:d??null,stderr:u??null};}else o==="Agent"?(b="subagent",h={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",h={query:typeof r.query=="string"?r.query.slice(0,200):null}):(R=false,b="tool_use",h={});if(R){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:h,command:m||void 0,exitCode:d,stderr:u??void 0,durationMs:0,createdAt:Date.now()};this.postMemoryEvent(S);}let w=So({toolName:o,toolResponse:i,sessionId:s,toolUseId:n.tool_use_id,runtimeStore:this.runtimeStore}),x=this.runtimeStore.get(s),A=Qr({projectRoot:this.projectRoot,sessionId:s,executionId:x?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:n.tool_use_id}),M=this.enforcePostToolUse(o);M&&this.logRuntime("warn","post_tool_enforcement",{tool:o,reason:M},s);let H=[w,A,M].filter(S=>!!S).join(`
37
37
 
38
- `);return H?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:H}}:null}async handlePostToolUseFailure(t){let n;try{n=JSON.parse(t);}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 te(this.projectRoot,o,a?.executionId??o);ai(c,r.replace(/^mcp__[^_]+__/,""),si(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(t){if(!t)return 0;let n=t;if(typeof t=="string")try{n=JSON.parse(t);}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(t){G(`/api/memory/session-events?rootPath=${encodeURIComponent(this.projectRoot)}`,t);try{await(await this.getMemoryGate()).recordEvent(t);}catch(n){this.logRuntime("warn","memory_event_write",{reason:n.message,fallback:"http_mirror"},t.sessionId);}}async getMemoryGate(){let t=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return this.memoryWarmup??=t.forceWarmUp().catch(n=>{throw this.memoryWarmup=null,n}),await this.memoryWarmup,t}async handleUserPromptSubmit(t){let n=[];try{let o=JSON.parse(t),r=typeof o.prompt=="string"?o.prompt:"",i=typeof o.session_id=="string"&&o.session_id.trim()?this.trackSession(o.session_id):null,s=Bo(r),a=!1,c;if(r.trim()&&i){try{c=ti({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}; intent=${c.artifact.intent}; action=${c.artifact.action}; 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."),emitSemanticControlLog({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=Bt({projectRoot:this.projectRoot,sessionId:i,prompt:r,...c?{identity:c.memoryIdentity}:{}});if(d){let l=d;if(d.explicitContent&&d.turn.status==="pending")try{l=await Jt({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(u){this.logRuntime("warn","explicit_memory_commit",{reason:u.message,fallback:"durable_work_queue",turnId:d.turn.turnId},i);}n.push(l.additionalContext),a=l.skipSkillRouting;}}catch(d){a=!!Ie(r);try{let u=wr(this.projectRoot,{sessionId:i,prompt:r,createdAt:Date.now()});n.push(`DevFlow memory turn status=accepted; durable=true; receiptId=${u}; 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:u},i);}catch(u){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:u.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(`
39
- `)}:{}}}}async handlePreCompact(t){let n;try{let s=JSON.parse(t);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 he({projectRoot:this.projectRoot,sessionId:n,trigger:"pre_compact",memory:o}),i=eo(r);return {hookSpecificOutput:{hookEventName:"PreCompact",...i?{additionalContext:i}:{}}}}async persistMemoryTurnItem(t){if(!t||typeof t!="object")throw new Error("memory_turn_payload_invalid");let n=t;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 Jt({projectRoot:this.projectRoot,payload:n,memory:await this.getMemoryGate()});}scheduleMemoryTurnSpoolDrain(t){this.memoryTurnSpoolTimer||(this.memoryTurnSpoolTimer=setTimeout(()=>{this.memoryTurnSpoolTimer=null,this.drainMemoryTurnSpool();},t),this.memoryTurnSpoolTimer.unref());}async drainMemoryTurnSpool(){for(;;){let t=kr(this.projectRoot);if(!t)return;try{Bt({projectRoot:this.projectRoot,sessionId:t.payload.sessionId,prompt:t.payload.prompt}),br(t),this.workRuntime.drainOnce();}catch(n){Rr(t),this.logRuntime("warn","memory_turn_spool_replay",{reason:n.message,fallback:"bounded_retry"},t.payload.sessionId),this.scheduleMemoryTurnSpoolDrain(1e3);return}}}async bootstrapSessionWork(t){if(!t||typeof t!="object"||typeof t.sessionId!="string")throw new Error("session_bootstrap_payload_invalid");let n=t.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>=hu&&this.flushTelemetry();}async flushTelemetry(){this.successfulTelemetryOperations=0,await this.telemetry.flushAndAggregate();}startExplicitIntentFlush(){this.explicitIntentFlush||(this.explicitIntentFlush=this.flushExplicitMemoryIntents().finally(()=>{this.explicitIntentFlush=null;}));}async handleStop(t){let n=null,o=false,r;try{let i=JSON.parse(t);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=Fr({projectRoot:this.projectRoot,sessionId:n,transcriptPath:r,stopHookActive:o,runtimeStore:this.runtimeStore});if(i.decision==="block_once")return emitSemanticControlLog({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={...Ct(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);}emitSemanticControlLog({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 t=zo(this.projectRoot);if(t)try{let n=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);await n.forceWarmUp();let o=!1;for(;t.intents.length>0;){let r=t.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),Mt(t);continue}}finally{s.close();}}let i=await n.saveExplicitMemoryIntent(r.content,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();}}Mt(t);}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(t,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),o.deleteContextReceipt(this.projectRoot,t,n);}catch{}finally{o?.close();}}async refreshMemorySnapshot(t){try{let n=loadConfig(this.projectRoot).sessionStart?.injectMemories??!0,o=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return await et({projectRoot:this.projectRoot,memory:o,injectConfig:n,reason:t})}catch(n){return this.logRuntime("warn","memory_snapshot_refresh",{reason:n.message,fallback:"cached_snapshot",trigger:t}),zt({projectRoot:this.projectRoot,reason:t,load:async()=>{throw n}})}}async handleMemorySnapshot(){let t=await this.refreshMemorySnapshot("memory_snapshot_request"),{snapshot:n}=t;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:t.persisted}}async handleSessionEnd(t){let n=null;try{let s=JSON.parse(t);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=Ge(t,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(t,n){if(!t||typeof t!="object")throw new Error("session_finalize_payload_invalid");let o=t;if(typeof o.inputJson!="string"||typeof o.sessionId!="string")throw new Error("session_finalize_payload_invalid");let r=await this.getMemoryGate();await Lo(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(t,n){if(resolveCapabilityRollout(this.projectRoot).config.learningOverlays==="off")return;let r=t.getSessionClosure(this.projectRoot,n);if(!r||r.state!=="closed"||r.pendingWorkCount!==0||t.listSessionObligations(this.projectRoot,n).some(c=>c.state==="open"||c.state==="degraded"))return;let s=t.getLatestSkillExecutionForSession(n);if(s&&s.status==="running")return;let a=ku(this.projectRoot);t.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(t){this.sessionFinalizeSpoolTimer||(this.sessionFinalizeSpoolTimer=setTimeout(()=>{this.sessionFinalizeSpoolTimer=null,this.drainSessionFinalizeSpool();},t),this.sessionFinalizeSpoolTimer.unref());}async drainSessionFinalizeSpool(){for(;;){let t=ho(this.projectRoot);if(!t)return;try{if(!Ge(t.payload.inputJson,this.projectRoot,t.payload.cleanupSharedState,t.payload.executionId,!1))throw new Error("session_finalize_spool_rejected");yo(t),this.workRuntime.drainOnce();}catch(n){_o(t),this.logRuntime("warn","session_finalize_spool_replay",{reason:n.message,fallback:"bounded_retry"},t.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 t=this.server;return !t||!t.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,mu);t.close(r);}))}cleanupOwnedResources(){try{Zn(this.projectRoot,process.pid);}catch(t){this.logRuntime("warn","daemon_unregister",{reason:t.message});}this.removePathIfOwned(this.socketPath,this.socketIdentity,"socket"),this.removePathIfOwned(this.pidPath,this.pidIdentity,"PID file",`${process.pid}
40
- `);}};function wu(e){if(e)try{let t=JSON.parse(e);return typeof t.session_id=="string"&&t.session_id.trim()?t.session_id.trim():void 0}catch{return}}function ku(e){try{return execFileSync("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return `unversioned:${createHash("sha256").update(e).digest("hex").slice(0,16)}`}}if(process.env.DEVFLOW_HOOK_DAEMON_DISABLE_AUTOSTART!=="1"){let e=process.argv[2]||process.env.CLAUDE_PROJECT_DIR||process.cwd(),t=new _n(e,process.argv[3]);process.once("SIGTERM",()=>{t.shutdown();}),process.once("SIGINT",()=>{t.shutdown();}),t.start().catch(n=>{console.error("[devflow-daemon] Failed to start:",n),process.exit(1);});}export{_n as HookDaemon,Iu as injectProjectRootIfMissing};
38
+ `);return H?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:H}}:null}async handlePostToolUseFailure(t){let n;try{n=JSON.parse(t);}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 te(this.projectRoot,o,a?.executionId??o);di(c,r.replace(/^mcp__[^_]+__/,""),ci(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(t){if(!t)return 0;let n=t;if(typeof t=="string")try{n=JSON.parse(t);}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(t){G(`/api/memory/session-events?rootPath=${encodeURIComponent(this.projectRoot)}`,t);try{await(await this.getMemoryGate()).recordEvent(t);}catch(n){this.logRuntime("warn","memory_event_write",{reason:n.message,fallback:"http_mirror"},t.sessionId);}}async getMemoryGate(){let t=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return this.memoryWarmup??=t.forceWarmUp().catch(n=>{throw this.memoryWarmup=null,n}),await this.memoryWarmup,t}async handleUserPromptSubmit(t){let n=[];try{let o=JSON.parse(t),r=typeof o.prompt=="string"?o.prompt:"",i=typeof o.session_id=="string"&&o.session_id.trim()?this.trackSession(o.session_id):null,s=Bo(r),a=!1,c;if(r.trim()&&i){try{c=oi({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}; intent=${c.artifact.intent}; action=${c.artifact.action}; 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."),emitSemanticControlLog({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=Bt({projectRoot:this.projectRoot,sessionId:i,prompt:r,...c?{identity:c.memoryIdentity}:{}});if(d){let u=d;if(d.explicitContent&&d.turn.status==="pending")try{u=await Jt({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=wr(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(`
39
+ `)}:{}}}}async handlePreCompact(t){let n;try{let s=JSON.parse(t);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 he({projectRoot:this.projectRoot,sessionId:n,trigger:"pre_compact",memory:o}),i=eo(r);return {hookSpecificOutput:{hookEventName:"PreCompact",...i?{additionalContext:i}:{}}}}async persistMemoryTurnItem(t){if(!t||typeof t!="object")throw new Error("memory_turn_payload_invalid");let n=t;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 Jt({projectRoot:this.projectRoot,payload:n,memory:await this.getMemoryGate()});}scheduleMemoryTurnSpoolDrain(t){this.memoryTurnSpoolTimer||(this.memoryTurnSpoolTimer=setTimeout(()=>{this.memoryTurnSpoolTimer=null,this.drainMemoryTurnSpool();},t),this.memoryTurnSpoolTimer.unref());}async drainMemoryTurnSpool(){for(;;){let t=kr(this.projectRoot);if(!t)return;try{Bt({projectRoot:this.projectRoot,sessionId:t.payload.sessionId,prompt:t.payload.prompt}),br(t),this.workRuntime.drainOnce();}catch(n){Rr(t),this.logRuntime("warn","memory_turn_spool_replay",{reason:n.message,fallback:"bounded_retry"},t.payload.sessionId),this.scheduleMemoryTurnSpoolDrain(1e3);return}}}async bootstrapSessionWork(t){if(!t||typeof t!="object"||typeof t.sessionId!="string")throw new Error("session_bootstrap_payload_invalid");let n=t.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(t){let n=null,o=false,r;try{let i=JSON.parse(t);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=Fr({projectRoot:this.projectRoot,sessionId:n,transcriptPath:r,stopHookActive:o,runtimeStore:this.runtimeStore});if(i.decision==="block_once")return emitSemanticControlLog({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={...Ct(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);}emitSemanticControlLog({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 t=zo(this.projectRoot);if(t)try{let n=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);await n.forceWarmUp();let o=!1;for(;t.intents.length>0;){let r=t.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),Mt(t);continue}}finally{s.close();}}let i=await n.saveExplicitMemoryIntent(r.content,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();}}Mt(t);}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(t,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),o.deleteContextReceipt(this.projectRoot,t,n);}catch{}finally{o?.close();}}async refreshMemorySnapshot(t){try{let n=loadConfig(this.projectRoot).sessionStart?.injectMemories??!0,o=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return await et({projectRoot:this.projectRoot,memory:o,injectConfig:n,reason:t})}catch(n){return this.logRuntime("warn","memory_snapshot_refresh",{reason:n.message,fallback:"cached_snapshot",trigger:t}),zt({projectRoot:this.projectRoot,reason:t,load:async()=>{throw n}})}}async handleMemorySnapshot(){let t=await this.refreshMemorySnapshot("memory_snapshot_request"),{snapshot:n}=t;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:t.persisted}}async handleSessionEnd(t){let n=null;try{let s=JSON.parse(t);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=Ge(t,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(t,n){if(!t||typeof t!="object")throw new Error("session_finalize_payload_invalid");let o=t;if(typeof o.inputJson!="string"||typeof o.sessionId!="string")throw new Error("session_finalize_payload_invalid");let r=await this.getMemoryGate();await Lo(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(t,n){if(resolveCapabilityRollout(this.projectRoot).config.learningOverlays==="off")return;let r=t.getSessionClosure(this.projectRoot,n);if(!r||r.state!=="closed"||r.pendingWorkCount!==0||t.listSessionObligations(this.projectRoot,n).some(c=>c.state==="open"||c.state==="degraded"))return;let s=t.getLatestSkillExecutionForSession(n);if(s&&s.status==="running")return;let a=Eu(this.projectRoot);t.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(t){this.sessionFinalizeSpoolTimer||(this.sessionFinalizeSpoolTimer=setTimeout(()=>{this.sessionFinalizeSpoolTimer=null,this.drainSessionFinalizeSpool();},t),this.sessionFinalizeSpoolTimer.unref());}async drainSessionFinalizeSpool(){for(;;){let t=ho(this.projectRoot);if(!t)return;try{if(!Ge(t.payload.inputJson,this.projectRoot,t.payload.cleanupSharedState,t.payload.executionId,!1))throw new Error("session_finalize_spool_rejected");yo(t),this.workRuntime.drainOnce();}catch(n){vo(t),this.logRuntime("warn","session_finalize_spool_replay",{reason:n.message,fallback:"bounded_retry"},t.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 t=this.server;return !t||!t.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);t.close(r);}))}cleanupOwnedResources(){try{Zn(this.projectRoot,process.pid);}catch(t){this.logRuntime("warn","daemon_unregister",{reason:t.message});}this.removePathIfOwned(this.socketPath,this.socketIdentity,"socket"),this.removePathIfOwned(this.pidPath,this.pidIdentity,"PID file",`${process.pid}
40
+ `);}};function xu(e){if(e)try{let t=JSON.parse(e);return typeof t.session_id=="string"&&t.session_id.trim()?t.session_id.trim():void 0}catch{return}}function Eu(e){try{return execFileSync("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return `unversioned:${createHash("sha256").update(e).digest("hex").slice(0,16)}`}}if(process.env.DEVFLOW_HOOK_DAEMON_DISABLE_AUTOSTART!=="1"){let e=process.argv[2]||process.env.CLAUDE_PROJECT_DIR||process.cwd(),t=new vn(e,process.argv[3]);process.once("SIGTERM",()=>{t.shutdown();}),process.once("SIGINT",()=>{t.shutdown();}),t.start().catch(n=>{console.error("[devflow-daemon] Failed to start:",n),process.exit(1);});}export{vn as HookDaemon,Su as injectProjectRootIfMissing};