@devflow-tools/cli 0.17.0 → 0.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,38 +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,selectHostAdapter,getProjectStateDir,formatSkillRuntimeOverlay,createSkillRuntimeOverlay,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,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,appendFileSync,lstatSync as lstatSync$1,readSync,statSync,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 {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';function W(n,e,t){try{let o=openGlobalDevFlowDatabase();try{o.insertEvent({kind:n,timestamp:Date.now(),duration:t,success:e.success!==!1,metadata:e});}finally{o.close();}}catch{}}var Jr=getLocalApiKey(),Ze=join(homedir(),".devflow","errors");async function F(n,e,t={}){let o=t.endpoint??resolveRuntimeEndpoint().url,r=t.timeout??1500,i=t.durableMirror??true,s=t.maxRetries??(i?0:2),a=t.circuitBreaker??true,c=acquireRuntimeHttpCircuit(o,n);if(a&&!c.allowed)return {delivered:false,suppressed:true,fallbackReason:c.state.fallbackReason};let l;for(let u=0;u<=s;u+=1)try{return await Br(o,n,e,r),a&&registerRuntimeHttpSuccess(o,n).transitioned&&W("http_circuit_transition",{endpoint:o,path:new URL(n,o).pathname,previous:c.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(p){l=p instanceof Error?p:new Error(String(p)),u<s&&await Gr(Math.min(100*2**u,1e3));}if(!l)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return ln(n,l),{delivered:false,suppressed:false,fallbackReason:l.message};let d=registerRuntimeHttpFailure(o,n,t.fallbackReason??(i?"local_durable_mirror":"http_delivery_failed"));return d.transitioned&&(ln(n,l),W("http_circuit_transition",{endpoint:o,path:new URL(n,o).pathname,previous:c.state.status,status:"open",failures:d.state.failures,openUntil:d.state.openUntil,fallbackReason:d.state.fallbackReason})),{delivered:false,suppressed:false,fallbackReason:d.state.fallbackReason}}function Br(n,e,t,o){return new Promise((r,i)=>{let s=JSON.stringify(t),a=new URL(e,n),c=false,l=u=>{c||(c=true,u?i(u):r());},d=request$1({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":Jr,"Content-Length":Buffer.byteLength(s)},timeout:o},u=>{u.on("error",l),u.on("end",()=>{let p=u.statusCode??0;l(p>=200&&p<300?void 0:new Error(`HTTP ${p}`));}),u.resume();});d.on("error",l),d.on("timeout",()=>d.destroy(new Error(`HTTP mirror timed out after ${o}ms`))),d.write(s),d.end();})}function ln(n,e){try{existsSync(Ze)||mkdirSync$1(Ze,{recursive:!0}),appendFileSync(join(Ze,"http-errors.log"),`${new Date().toISOString()} | ${n} | ${e.message}
2
- `);}catch{}}function Gr(n){return new Promise(e=>setTimeout(e,n))}var gn=1e4,Qr=3e4,we=500,U=class{constructor(e){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=e?.apiUrl,this.cacheDir=e?.cacheDir??join$1(process.env.DEVFLOW_STATE_DIR??join$1(homedir$1(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=e?.legacyCacheDir??(e?.cacheDir?null:join$1(homedir$1(),".devflow","telemetry-cache")),this.database=e?.database??null,this.ownsDatabase=!e?.database;let t=e?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(t)&&t>=0?t:100;}async sendEvent(e){let t={...e,input:this.truncateInput(e.input)};return this.commitOrCache("tool_call",t)?(this.postHttp("/api/telemetry/tool-call",t),e.eventId):null}async sendExecutionStart(e,t,o,r,i=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:e,sessionId:t,skillName:o,startedAt:r,projectRoot:i,requiredMcpTools:s};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(e,t="completed",o=Date.now(),r){let i={executionId:e,status:t,finishedAt:o,metadata:r},s=this.commitOrCache("execution_complete",i);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",i),s}async sendSessionStart(e,t,o){let r={id:e,projectRoot:t,startedAt:o,label:t.split("/").pop()??"unknown"},i=this.commitOrCache("session_start",r);return i&&this.postHttp("/api/telemetry/sessions",r),i}async completeEvent(e){let t=this.commitOrCache("complete_event",e);return t&&(this.postHttp("/api/telemetry/tool-call/output",e),this.scheduleMetricAggregation()),t}async endSession(e,t=Date.now()){let o={sessionId:e,finishedAt:t},r=this.commitOrCache("session_end",o);return r&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(e)}/close`,{finishedAt:t})),r}async flushCache(){try{let o=this.getDatabase(),r=o.listTelemetryFailures({unresolvedOnly:!0,limit:we}).reverse();for(let i of r)try{this.applyOperation(i.operation,i.payload),o.resolveTelemetryFailure(i.id);}catch{}o.trimTelemetryFailures(we);}catch{}let t=[...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:Zr(JSON.parse(readFileSync(i,"utf8")),r)}}catch{return null}})).filter(o=>o!==null).sort((o,r)=>o.envelope.timestamp-r.envelope.timestamp||hn(o.envelope.operation)-hn(r.envelope.operation));for(let{cacheFile:o,envelope:r}of t)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(e,t){try{return this.applyOperation(e,t),!0}catch(o){return this.cacheOperation(e,t,o),false}}applyOperation(e,t){let o=this.getDatabase();switch(e){case "tool_call":this.ensureParentSession(o,t),o.insertToolCallEvent(t);return;case "execution_start":this.ensureParentSession(o,t),o.insertSkillExecution({executionId:t.executionId,sessionId:t.sessionId,skillName:t.skillName,startedAt:t.startedAt,status:"running",requiredMcpTools:t.requiredMcpTools});return;case "execution_complete":o.reconcileSkillExecution(t.executionId,t.status,t.finishedAt,t.metadata);return;case "session_start":o.ensureSession(t),o.insertRun({id:yn(t.id),source:"hook",tool:"session",input:{projectRoot:t.projectRoot},status:"active",startedAt:t.startedAt,tokenUsed:0,metadata:{sessionId:t.id,projectRoot:t.projectRoot}});return;case "complete_event":if(!o.updateToolCallEvent(t.eventId,{output:t.output===void 0?void 0:JSON.stringify(t.output),error:t.error,failureCategory:t.failureCategory,duration:t.duration}))throw new Error(`Tool call event ${t.eventId} is not available for completion`);return;case "session_end":o.closeSession(t.sessionId,t.finishedAt),o.updateRun(yn(t.sessionId),{status:"completed",finishedAt:t.finishedAt});return}}ensureParentSession(e,t){let o=typeof t.sessionId=="string"?t.sessionId.trim():"";if(!o)throw new Error("Canonical session ID is required for telemetry");let r=typeof t.projectRoot=="string"&&t.projectRoot.trim()?t.projectRoot:typeof t.input?.projectRoot=="string"&&t.input.projectRoot.trim()?t.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";e.ensureSession({id:o,projectRoot:r,label:r==="unknown"?void 0:r.split("/").pop(),startedAt:Number(t.startedAt??t.timestamp??Date.now())});}cacheOperation(e,t,o){let r=Date.now(),i={id:`failure:${r}:${Math.random().toString(36).slice(2,11)}`,operation:e,payload:t,failure:o instanceof Error?o.message:String(o),timestamp:r};try{let s=this.getDatabase();s.insertTelemetryFailure({id:i.id,operation:e,payload:t,error:i.failure,createdAt:r}),s.trimTelemetryFailures(we),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 e=readdirSync(this.cacheDir).filter(t=>t.endsWith(".json")).sort();for(let t of e.slice(0,Math.max(0,e.length-we)))unlinkSync(join$1(this.cacheDir,t));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},Qr).unref());}scheduleMetricAggregation(){if(this.metricAggregationScheduled||process.env.DEVFLOW_HOOK_DEGRADED==="1")return;this.metricAggregationScheduled=true,setTimeout(()=>{this.metricAggregationScheduled=false;try{this.getDatabase().aggregatePendingToolMetrics(50)===50&&this.scheduleMetricAggregation();}catch{}},25).unref();}postHttp(e,t){F(e,t,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(e){let t=JSON.stringify(e);return t===void 0||t.length<=gn?e:{_truncated:true,_original_size:t.length,_preview:`${t.substring(0,gn)}...`}}};function hn(n){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(n)}function yn(n){return `hook-run:${n}`}function Zr(n,e){if(!n||typeof n!="object")throw new Error("Invalid telemetry cache envelope");let t=n;if(typeof t.operation=="string"&&t.payload!==void 0)return t;let o=t.type==="tool_call"?"tool_call":t.type==="execution_start"?"execution_start":null;if(!o)throw new Error("Unknown legacy telemetry cache operation");let r=t.payload??{},i=Number(r.timestamp??r.startedAt??Date.now());return {id:`legacy-cache:${e}`,operation:o,payload:r,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:i}}function be(n){return n??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function R(n){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(be(n))}var ii=2,si=1;function ai(){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 vn(n=ai()){let e=[join$1(n,"dist","command-registry.json"),join$1(n,"command-registry.json")];for(let t of e)try{if(!existsSync$1(t))continue;let o=JSON.parse(readFileSync(t,"utf8"));if(o.version!==ii&&o.version!==si||!ci(o.commands)){console.error(`[devflow] command registry contract mismatch: ${t}`);continue}return o.commands}catch(o){console.error(`[devflow] command registry load failed: ${o.message}`);}return null}function ci(n){return !n||typeof n!="object"||Array.isArray(n)?false:Object.values(n).every(e=>{if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return et(t.mcpTools)&&et(t.blockedNative)&&(t.source===void 0||t.source==="core"||t.source==="plugin")&&(t.requiresContext===void 0||typeof t.requiresContext=="boolean")&&(t.runtimePackages===void 0||et(t.runtimePackages))&&(t.evidenceMode===void 0||["static","runtime","mixed"].includes(t.evidenceMode))})}function et(n){return Array.isArray(n)&&n.every(e=>typeof e=="string"&&e.length>0)}function wn(n){let e=vn();return e?e[n]?.mcpTools??[]:[]}function bn(n,e,t){return formatSkillRuntimeOverlay(createSkillRuntimeOverlay(n,e,{prompt:t}))}var nt=join$1(homedir$1(),".devflow"),ot=join$1(nt,"server-refs.json"),wi=600*1e3,bi=500;function _i(){existsSync$1(nt)||mkdirSync(nt,{recursive:true});}function _e(){try{if(existsSync$1(ot))return JSON.parse(readFileSync(ot,"utf-8"))}catch{}return {sessions:[],lastActivity:0}}function _n(n){_i(),writeFileSync(ot,JSON.stringify(n));}var Se=class{constructor(e){this.process=null;this.idleTimer=null;this.onShutdown=null;this.ownerToken=null;this.projectRoot=e;}setOnShutdown(e){this.onShutdown=e;}addRef(e){let t=_e();t.sessions.includes(e)||t.sessions.push(e),t.lastActivity=Date.now(),_n(t),this.resetIdleTimer();}removeRef(e){let t=_e();t.sessions=t.sessions.filter(o=>o!==e),t.lastActivity=Date.now(),_n(t),t.sessions.length===0&&this.resetIdleTimer();}get activeSessions(){return _e().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(t=>{let o=setTimeout(()=>{this.process&&!this.process.killed&&this.process.kill("SIGKILL"),t();},5e3);this.process?this.process.on("exit",()=>{clearTimeout(o),t();}):(clearTimeout(o),t());}),this.process=null;let e=readRuntimeEndpointState();e&&e.ownerToken===this.ownerToken&&updateRuntimeEndpointStatus("stopped");}}async startServer(){let e=ki(this.projectRoot);this.ownerToken=randomUUID$1();let t=resolveRuntimeEndpoint();this.process=spawn(process.execPath,[e,"--devflow-instance-token",this.ownerToken],{cwd:this.projectRoot,env:{...process.env,NODE_ENV:process.env.NODE_ENV||"development"},stdio:["ignore","pipe","pipe"]}),writeRuntimeEndpointState({url:t.url,port:t.port,pid:this.process.pid??0,ownerToken:this.ownerToken,status:"launching"}),this.process.stdout?.on("data",o=>{}),this.process.stderr?.on("data",o=>{}),this.process.on("exit",o=>{let r=readRuntimeEndpointState();r&&r.ownerToken===this.ownerToken&&updateRuntimeEndpointStatus("stopped"),this.process=null,this.onShutdown&&this.onShutdown();}),this.process.on("error",()=>{let o=readRuntimeEndpointState();o&&o.ownerToken===this.ownerToken&&updateRuntimeEndpointStatus("degraded"),this.process=null;});}async waitForReady(){let e=Date.now()+3e4;for(;Date.now()<e;){if(await this.healthCheck())return true;await new Promise(t=>setTimeout(t,bi));}return false}healthCheck(){return new Promise(e=>{let t=resolveRuntimeEndpoint(),o=new URL("/api/health",t.url),r=request({hostname:o.hostname,port:o.port,path:o.pathname,method:"GET",timeout:2e3},i=>{let s=i.statusCode===200;s&&readRuntimeEndpointState()&&updateRuntimeEndpointStatus("healthy"),i.resume(),e(s);});r.on("error",()=>e(false)),r.on("timeout",()=>{r.destroy(),e(false);}),r.end();})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),!(_e().sessions.length>0)&&(this.idleTimer=setTimeout(()=>{this.stop();},wi).unref());}};function ki(n){let e=createRequire(import.meta.url),t=[()=>e.resolve("@devflow-tools/server/dist/main.js"),()=>join$1(n,"node_modules","@devflow-tools","server","dist","main.js"),()=>join$1(n,"apps","server","dist","main.js")];for(let o of t)try{let r=o();if(existsSync$1(r))return r}catch{}throw new Error("DevFlow server entry point is not installed or built")}function Ie(n){if(!n||typeof n!="object"||Array.isArray(n))return {};let e=n,t={};for(let o of ["lastMcpCall","bypassCount"])if(o in e){let r=e[o];if(r==null)continue;t[o]=typeof r=="number"&&Number.isFinite(r)&&r>=0?r:0;}return t}function Ri(n,e){return n.lastMcpCall===e.lastMcpCall&&n.bypassCount===e.bypassCount}function Ei(n){try{return existsSync$1(n)?Ie(JSON.parse(readFileSync(n,"utf-8"))):{}}catch{return {}}}function xi(n,e){let t=e instanceof Error?e.message:String(e);console.error(`[devflow] Receipt ${n} skipped: ${t}`);}function kn(n){let e=R(n);for(let t of ["receipt.json","receipt-lock.sqlite","receipt-lock.sqlite-shm","receipt-lock.sqlite-wal"])try{existsSync$1(join$1(e,t))&&unlinkSync(join$1(e,t));}catch{}}function Ti(n,e){if(n.getHookReceipt(e)){kn(e);return}let t=join$1(R(e),"receipt.json");if(!existsSync$1(t))return;let o=Ei(t);n.updateHookReceipt(e,()=>o),kn(e);}function In(n,e,t){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),Ti(o,n);let r={},i=o.updateHookReceipt(n,a=>(r=Ie(a),Ie(e(r)))),s=Ie(i);return {receipt:s,applied:!0,changed:!Ri(r,s)}}catch(r){return xi(t,r),{receipt:{},applied:false,changed:false}}finally{try{o?.close();}catch{}}}function Re(n,e){return In(n,()=>e,"write").applied}function at(n,e){return In(n,e,"update")}var Sn={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},Ci=new Set(["Write","Edit","NotebookEdit"]),Di=new Set(["failed","timeout","unavailable"]);function Mi(n){switch(n){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var z=class{constructor(e,t,o){this.projectRoot=e;this.sessionId=t;this.executionId=o;}getPhase(){if(!this.sessionId||!this.executionId)return "idle";let e;try{e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let t=e.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(t&&t.expiresAt>Date.now())return "context_ready";t&&e.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId);}catch{}finally{try{e?.close();}catch{}}return "context_gathering"}getContextReceipt(){if(!this.sessionId||!this.executionId)return null;let e;try{e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let t=e.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);return t&&t.expiresAt>Date.now()?t:(t&&e.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId),null)}catch{return null}finally{try{e?.close();}catch{}}}evaluate(e,t){let o=this.getPhase();if(t||e==="Skill")return {permissionDecision:"allow"};if(o==="context_gathering"&&Sn[e])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_REQUIRED",reason:`DevFlow context required. Call mcp__devflow__get_project_context, then retry ${e}.`};if(o==="context_ready"){if(Ci.has(e)){let c=this.evaluateRequiredAction();if(c)return c}return {permissionDecision:"allow"}}let r=Sn[e];if(!r)return {permissionDecision:"allow"};let i=at(this.projectRoot,c=>({...c,bypassCount:(c.bypassCount??0)+1}));if(!i.applied)return {permissionDecision:"allow"};let s=i.receipt.bypassCount??0,a=Mi(e);return s>=a?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \u6B21\u76F4\u63A5\u4F7F\u7528 ${e}\uFF0C\u5EFA\u8BAE\u7528 mcp__devflow__${r} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){Re(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}recordDomainActionOutcome(e,t,o,r){if(!this.sessionId||!this.executionId)return false;let i;try{i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let s=i.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(!s||s.expiresAt<=Date.now()||s.canonicalAction?.tool!==e)return !1;let a=Date.now(),c=r?.trim()?`${r.trim()}:${t}`:`${e}:${t}:${a}`,l=s.actionAttempts??[];return i.upsertContextReceipt({...s,actionAttempts:l.some(d=>d.id===c||r&&d.toolUseId===r&&d.status===t)?l:[...l,{id:c,tool:e,status:t,attemptedAt:a,toolUseId:r,reason:o?.slice(0,500)}].slice(-20),actionSatisfiedAt:t==="succeeded"?a:s.actionSatisfiedAt,actionDegradation:t==="succeeded"?void 0:s.actionDegradation}),!0}catch{return false}finally{try{i?.close();}catch{}}}evaluateRequiredAction(){let e=this.getContextReceipt(),t=e?.canonicalAction;if(!e||!t||!t.required||t.status!=="required")return null;let o=t.binding;if(o.requiredContextReceipt!==e.contextHash||o.projectRoot!==this.projectRoot||o.sessionId!==this.sessionId||o.requestId!==e.requestId||o.executionId&&o.executionId!==this.executionId)return {permissionDecision:"deny",reasonCode:"DEVFLOW_ACTION_BINDING_STALE",reason:"DevFlow canonical action binding is stale or mismatched. Call mcp__devflow__get_project_context again before writing."};if(e.actionSatisfiedAt)return null;if(e.actionDegradation?.authorizedByContextReceipt===e.contextHash)return {permissionDecision:"allow",additionalContext:`DevFlow degraded fallback authorized by context receipt ${e.contextHash}: ${e.actionDegradation.reason}`};let r=(e.actionAttempts??[]).filter(i=>i.tool===t.tool&&Di.has(i.status));if(r.length>0){let i=r.at(-1),s={missedTool:t.tool,failedAttemptCount:r.length,reason:`${i.status}:${i.reason??"canonical domain action did not complete"}`,authorizedByContextReceipt:e.contextHash,authorizedAt:Date.now()};return this.persistDegradation(e,s),{permissionDecision:"allow",additionalContext:`DevFlow canonical tool mcp__devflow__${t.tool} ${i.status}; degraded direct write authorized by context receipt ${e.contextHash}. Preserve the action contract and verification plan.`}}return {permissionDecision:"deny",reasonCode:"DEVFLOW_REQUIRED_ACTION",reason:`DevFlow required action not completed. Call mcp__devflow__${t.tool} using context receipt ${e.contextHash}, then retry the write. Direct fallback is allowed only after unavailable, failed, or timeout evidence.`}}persistDegradation(e,t){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let r=o.getContextReceipt(e.projectRoot,e.sessionId,e.executionId);if(!r||r.contextHash!==e.contextHash||r.actionDegradation)return;o.upsertContextReceipt({...r,actionDegradation:t});let i=o.getSkillExecution(e.executionId);if(!i)return;let s=i.metadata&&typeof i.metadata=="object"?i.metadata:{},a=Array.isArray(s.requiredActionDegradations)?s.requiredActionDegradations:[];o.updateSkillExecution(e.executionId,{missedMcpTools:[...new Set([...i.missedMcpTools??[],t.missedTool])],failedToolCalls:Math.max(i.failedToolCalls??0,t.failedAttemptCount),fallbackCount:(i.fallbackCount??0)+1,fallbackReasons:[...new Set([...i.fallbackReasons??[],`required_action_${t.reason}`])],metadata:{...s,requiredActionDegradations:[...a,t]}});}catch{}finally{try{o?.close();}catch{}}}};var $i=10,Hi=5e3,Ni=3e4,Li=new Int32Array(new SharedArrayBuffer(4)),Dn=0;function Wi(n){if(typeof n!="object"||n===null)return false;let e=n;return typeof e.rootPath=="string"&&e.rootPath.length>0&&typeof e.projectHash=="string"&&e.projectHash.length>0&&typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.startedAt=="number"&&Number.isFinite(e.startedAt)&&e.startedAt>=0}function Mn(n){if(!existsSync(n))return {entries:[],needsRepair:false};try{let e=JSON.parse(readFileSync$1(n,"utf8"));if(!Array.isArray(e))return {entries:[],needsRepair:!0};let t=e.filter(Wi);return {entries:t,needsRepair:t.length!==e.length}}catch{return {entries:[],needsRepair:true}}}function An(n,e){mkdirSync$1(dirname$1(n),{recursive:true});let t=`${n}.${process.pid}.${Date.now()}.${Dn++}.tmp`,o;try{o=openSync$1(t,"wx"),writeFileSync$1(o,JSON.stringify(e,null,2)),closeSync$1(o),o=void 0,renameSync(t,n);}finally{try{o!==void 0&&closeSync$1(o);}finally{rmSync$1(t,{force:true});}}}function On(n){try{return process.kill(n,0),!0}catch(e){return e.code!=="ESRCH"}}function Pn(n){if(typeof n!="object"||n===null)return false;let e=n;return typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)&&typeof e.token=="string"&&e.token.length>0}function Rn(n,e){try{return readFileSync$1(n,"utf8")!==e?!1:(rmSync$1(n),!0)}catch(t){return t.code==="ENOENT"}}function qi(n){try{let e=readFileSync$1(n,"utf8"),t;try{let r=JSON.parse(e);Pn(r)&&(t=r);}catch{}return t?On(t.pid)?!1:Rn(n,e):Date.now()-statSync(n).mtimeMs>Ni&&Rn(n,e)}catch(e){return e.code==="ENOENT"}}function Ui(n){mkdirSync$1(dirname$1(n),{recursive:true});let e=`${n}.lock`,t=Date.now()+Hi;for(;;){let o=`${process.pid}:${Date.now()}:${Dn++}`,r;try{return r=openSync$1(e,"wx"),writeFileSync$1(r,JSON.stringify({pid:process.pid,createdAt:Date.now(),token:o})),closeSync$1(r),r=void 0,{path:e,token:o}}catch(i){if(r!==void 0)try{closeSync$1(r);}finally{rmSync$1(e,{force:true});}if(i.code!=="EEXIST")throw i}if(!qi(e)){if(Date.now()>=t)throw new Error(`Timed out acquiring daemon registry lock: ${e}`);Atomics.wait(Li,0,0,$i);}}}function zi(n){try{let e=readFileSync$1(n.path,"utf8"),t=JSON.parse(e);Pn(t)&&t.token===n.token&&rmSync$1(n.path);}catch(e){if(e.code!=="ENOENT")throw e}}function jn(n){let e=getDaemonRegistryPath(),t=Ui(e);try{return n(e)}finally{zi(t);}}function Fn(n,e){jn(t=>{let o=Mn(t).entries.filter(r=>r.rootPath!==n&&On(r.pid));o.push({rootPath:n,projectHash:getProjectHash(n),pid:e,startedAt:Date.now()}),An(t,o);});}function $n(n,e){jn(t=>{let o=Mn(t).entries.filter(r=>r.rootPath!==n||e!==void 0&&r.pid!==e);An(t,o);});}async function ce(n){let e=!n.memory,t=n.memory??new MemoryGate(n.projectRoot),o=0,r=0;try{await t.forceWarmUp(),n.trigger==="session_end"&&(o=await t.releasePendingDistillLeases(n.sessionId)),r=t.getPendingEventCount(n.sessionId,n.trigger!=="session_end");}finally{e&&t.close();}let i=Date.now(),s=n.trigger==="session_end"&&n.sessionId?`distill:session_end:${createHash("sha256").update(`${n.projectRoot}\0${n.sessionId}`).digest("hex").slice(0,24)}`:`distill:${i}:${Math.random().toString(36).slice(2,10)}`,a={id:s,pendingEvents:r,releasedLeases:o,trigger:n.trigger,sessionId:n.sessionId,details:n.details};try{let c=openGlobalDevFlowDatabase();try{c.recordMemoryDistillCheckpoint({id:s,projectRoot:n.projectRoot,sessionId:n.sessionId,trigger:n.trigger,pendingEvents:r,releasedLeases:o,details:n.details,createdAt:i}),c.insertEvent({kind:"memory_distill_requested",timestamp:i,success:!0,metadata:{...a,projectRoot:n.projectRoot}});}finally{c.close();}}catch(c){if(n.strictPersistence)throw c}return a}function Hn(n){if(n.pendingEvents===0)return "";let e=n.sessionId?`\uFF0CsessionId=${n.sessionId}`:"";return `Memory distill checkpoint: ${n.pendingEvents} \u4E2A\u4E8B\u4EF6\u5F85\u63D0\u70BC${e}\u3002\u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210\u540E\uFF0C\u8C03\u7528 mcp__devflow__memory_request_distill\uFF1B\u6309\u8FD4\u56DE\u7684 nextPage \u5206\u9875\u8BFB\u53D6\u5168\u90E8\u4E8B\u4EF6\uFF0C\u63D0\u70BC observations\uFF0C\u518D\u8C03\u7528 mcp__devflow__memory_save_distilled \u5E76\u786E\u8BA4\u4FDD\u5B58\u7ED3\u679C\u3002`}function qn(n){return Buffer.from(n,"utf8").toString("base64url")}function Xi(n,e,t){let o=e?.trim();if(o){let r=/^[a-zA-Z0-9:._-]{1,192}$/.test(o)?o:`tool-${createHash$1("sha256").update(o.slice(0,1024)).digest("hex").slice(0,32)}`;return `${n}:${r}`}return `${n}:legacy-${t}-${randomUUID().slice(0,8)}`}function Vn(n){return `${n}:legacy-journal`}var M=class{constructor(e){this.projectRoot=e;this.sessions=new Map;this.sessionsDir=join$1(R(e),"hook-sessions");}registerSession(e){let t=e.trim();if(!t)throw new Error("session_id_required");let o=this.get(t);if(o)return o.lastActivityAt=Date.now(),this.persist(o),o;let r=Date.now(),i={sessionId:t,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:r,lastActivityAt:r};return this.sessions.set(t,i),this.persist(i),i}startExecution(e,t,o){let r=this.registerSession(e);return (!r.executionId||r.skillName!==t)&&(r.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),r.skillName=t,r.requiredMcpTools=[...new Set(o)],r.lastActivityAt=Date.now(),this.persist(r),r}get(e){let t=e.trim();if(!t)return null;let o=this.sessions.get(t);if(o)return this.replayEvidenceJournal(o),o;let r=this.snapshotPath(t);if(!existsSync$1(r))return null;try{let i=JSON.parse(readFileSync(r,"utf8"));return i.sessionId!==t||i.projectRoot!==this.projectRoot?null:(i.requiredMcpTools=Array.isArray(i.requiredMcpTools)?i.requiredMcpTools:[],i.evidenceObligations=Un(i.evidenceObligations),i.evidenceDegradations=zn(i.evidenceDegradations),i.evidenceOutcomes=Jn(i.evidenceOutcomes),this.replayEvidenceJournal(i),this.sessions.set(t,i),i)}catch{return null}}completeExecution(e){let t=this.get(e);if(!t)return null;let o=structuredClone(t);return delete t.executionId,delete t.skillName,t.requiredMcpTools=[],t.lastActivityAt=Date.now(),this.persist(t),o}addEvidenceObligation(e,t,o=Date.now(),r){let i=this.registerSession(e),a=(r?void 0:i.evidenceObligations.find(l=>l.contractId===t.id))?.obligationId??Xi(t.id,r,o);this.appendEvidenceEvent(e,{kind:"add",obligationId:a,contractId:t.id,at:o,contract:t},`add\0${a}`),this.replayEvidenceJournal(i);let c=i.evidenceObligations.find(l=>l.obligationId===a);return c?(i.lastActivityAt=Date.now(),this.persist(i),structuredClone(c)):null}listEvidenceObligations(e){return (this.get(e)?.evidenceObligations??[]).map(t=>structuredClone(t))}markEvidenceCorrection(e,t,o,r,i=Date.now()){let s=this.get(e),a=s?.evidenceObligations.find(d=>d.obligationId===t);if(!s||!a)return null;let c=/^[a-f0-9]{64}$/.test(r)?r:"";if(!c)return null;this.appendEvidenceEvent(e,{kind:"correction",obligationId:t,contractId:a.contractId,at:i,fingerprint:c,violations:o.slice(0,16).map(d=>d.slice(0,240))},`correction\0${t}\0${c}`),this.replayEvidenceJournal(s),s.lastActivityAt=i,this.persist(s);let l=s.evidenceObligations.find(d=>d.obligationId===t);return l?structuredClone(l):null}resolveEvidenceObligation(e,t){let o=this.get(e);if(!o)return false;let r=o.evidenceObligations.find(s=>s.obligationId===t);if(!r)return false;let i=Date.now();return this.appendEvidenceEvent(e,{kind:"resolve",obligationId:t,contractId:r.contractId,at:i},`resolve\0${t}`),this.replayEvidenceJournal(o),o.lastActivityAt=i,this.persist(o),true}degradeEvidenceObligation(e,t,o,r=Date.now()){let i=this.get(e),s=i?.evidenceObligations.find(c=>c.obligationId===t);if(!i||!s)return false;let a=o.slice(0,240);return this.appendEvidenceEvent(e,{kind:"degrade",obligationId:t,contractId:s.contractId,at:r,reason:a},`degrade\0${t}\0${a}`),this.replayEvidenceJournal(i),i.lastActivityAt=r,this.persist(i),true}removeSession(e){let t=e.trim();t&&(this.sessions.delete(t),rmSync(this.snapshotPath(t),{force:true}),rmSync(this.evidenceJournalDir(t),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(e){return join$1(this.sessionsDir,`${qn(e)}.json`)}evidenceJournalDir(e){return join$1(this.sessionsDir,"evidence-journal",qn(e))}appendEvidenceEvent(e,t,o){let r=this.evidenceJournalDir(e);mkdirSync(r,{recursive:true,mode:448});let i=createHash$1("sha256").update(o).digest("hex"),s=join$1(r,`${t.kind}-${i}.json`);if(existsSync$1(s))return;let a=join$1(r,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync(a,JSON.stringify(t),{mode:384});try{linkSync(a,s);}catch(c){if(c.code!=="EEXIST")throw c}finally{rmSync(a,{force:true});}}replayEvidenceJournal(e){e.evidenceObligations=Un(e.evidenceObligations),e.evidenceDegradations=zn(e.evidenceDegradations),e.evidenceOutcomes=Jn(e.evidenceOutcomes);let t=this.evidenceJournalDir(e.sessionId);if(!existsSync$1(t))return;let o;try{o=readdirSync(t).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(t,i),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=Qi(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||Bn(i.kind)-Bn(s.kind));for(let i of r)this.applyEvidenceEvent(e,i);e.evidenceObligations=e.evidenceObligations.slice(-8),e.evidenceDegradations=e.evidenceDegradations.slice(-20),e.evidenceOutcomes=e.evidenceOutcomes.slice(-20);}applyEvidenceEvent(e,t){let o=e.evidenceOutcomes.find(s=>s.obligationId===t.obligationId);if(t.kind==="add"){if(o)return;let s=e.evidenceObligations.find(a=>a.obligationId===t.obligationId);s?(s.contract=t.contract,s.promptedAt=Math.min(s.promptedAt,t.at)):e.evidenceObligations.push({obligationId:t.obligationId,contractId:t.contractId,contract:t.contract,promptedAt:t.at,attempt:0,correctionRequested:false,violations:[]});return}let r=e.evidenceObligations.find(s=>s.obligationId===t.obligationId);if(t.kind==="correction"){if(!r||o||r.correctionFingerprint===t.fingerprint)return;r.attempt+=1,r.correctionRequested=true,r.correctionRequestedAt=t.at,r.correctionFingerprint=t.fingerprint,r.violations=t.violations;return}let i=r?.attempt??0;e.evidenceObligations=e.evidenceObligations.filter(s=>s.obligationId!==t.obligationId),!o&&(t.kind==="degrade"&&e.evidenceDegradations.push({obligationId:t.obligationId,contractId:t.contractId,reason:t.reason,degradedAt:t.at,attempt:i}),e.evidenceOutcomes.push({obligationId:t.obligationId,contractId:t.contractId,status:t.kind==="resolve"?"resolved":"degraded",completedAt:t.at,attempt:i,...t.kind==="degrade"?{reason:t.reason}:{}}));}persist(e){mkdirSync(this.sessionsDir,{recursive:true,mode:448});let t=this.snapshotPath(e.sessionId),o=`${t}.${process.pid}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(e),{mode:384}),renameSync$1(o,t);}};function Un(n){return Array.isArray(n)?n.flatMap(e=>{if(!e||typeof e!="object")return [];let t=e;if(typeof t.contractId!="string"||t.contractId.length===0||t.contractId.length>128||typeof t.promptedAt!="number"||typeof t.attempt!="number"||typeof t.correctionRequested!="boolean"||!Array.isArray(t.violations)||!Kn(t.contract))return [];let o=typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:Vn(t.contractId),r=typeof t.correctionTranscriptHash=="string"?t.correctionTranscriptHash:void 0,i=t.correctionFingerprint??r;return i!==void 0&&!/^[a-f0-9]{64}$/.test(i)?[]:[{...t,obligationId:o,correctionFingerprint:i}]}).slice(-8):[]}function zn(n){return Array.isArray(n)?n.filter(e=>{if(!e||typeof e!="object")return false;let t=e;return typeof t.obligationId=="string"&&typeof t.contractId=="string"&&typeof t.reason=="string"&&typeof t.degradedAt=="number"&&typeof t.attempt=="number"}).slice(-20):[]}function Jn(n){return Array.isArray(n)?n.filter(e=>{if(!e||typeof e!="object")return false;let t=e;return typeof t.obligationId=="string"&&typeof t.contractId=="string"&&(t.status==="resolved"||t.status==="degraded")&&typeof t.completedAt=="number"&&typeof t.attempt=="number"&&(t.reason===void 0||typeof t.reason=="string")}).slice(-20):[]}function Qi(n){if(!n||typeof n!="object")return null;let e=n,t=e.kind;if(t!=="add"&&t!=="correction"&&t!=="resolve"&&t!=="degrade"||typeof e.contractId!="string"||e.contractId.length>128||typeof e.at!="number")return null;let r={obligationId:typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:Vn(e.contractId),contractId:e.contractId,at:e.at};if(t==="add")return Kn(e.contract)?{kind:t,...r,contract:e.contract}:null;if(t==="correction"){let i=typeof e.fingerprint=="string"?e.fingerprint:e.transcriptHash;return typeof i=="string"&&/^[a-f0-9]{64}$/.test(i)&&Array.isArray(e.violations)&&e.violations.every(s=>typeof s=="string"&&s.length<=240)?{kind:t,...r,fingerprint:i,violations:e.violations}:null}return t==="resolve"?{kind:t,...r}:typeof e.reason=="string"&&e.reason.length<=240?{kind:t,...r,reason:e.reason}:null}function Bn(n){return n==="add"?0:n==="correction"?1:2}function Kn(n){if(!n||typeof n!="object")return false;let e=n,t=e.requiredSections,o=e.prohibitedClaims;return e.version==="1.0"&&typeof e.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(e.id)&&typeof e.runtimeProfilingOccurred=="boolean"&&typeof e.samplingEvidenceOccurred=="boolean"&&Array.isArray(t)&&t.length===3&&t[0]==="\u5DE5\u5177\u53D1\u73B0"&&t[1]==="\u6A21\u578B\u5047\u8BBE"&&t[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(o)&&o.length<=16&&o.every(r=>typeof r=="string"&&r.length<=128)&&typeof e.canonicalReport=="string"&&Buffer.byteLength(e.canonicalReport,"utf8")<=48*1024&&!!e.correctionPolicy&&e.correctionPolicy.maxAttempts===1&&e.correctionPolicy.repeatedViolation==="fail_open"}function Qn(n,e){let t=no(n);mkdirSync$1(t,{recursive:true,mode:448});let o=join(t,`${e.receiptId}.json`);if(existsSync(o))return e.receiptId;let r=`${o}.${process.pid}.tmp`;writeFileSync$1(r,JSON.stringify(e),{mode:384});try{renameSync(r,o);}catch(i){try{unlinkSync$1(r);}catch{}if(!existsSync(o))throw i}return e.receiptId}function Zn(n){let e=no(n);mkdirSync$1(e,{recursive:true,mode:448});let t=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!t)return null;let o=join(e,t),r=/\.json\.claim-\d+$/u.test(t),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(t).replace(/\.json(?:\.claim-\d+)?$/u,""),payload:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function eo(n){unlinkSync$1(n.path);}function to(n){try{renameSync(n.path,n.path.replace(/\.claim-\d+$/u,""));}catch{}}function no(n){return join(R(n),"session-finalize-pending")}var ls=256*1024,ds=48*1024,us=512*1024,ps=500,ms=5,le=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function fs(n){return n==="react_audit_performance"||n.endsWith("__react_audit_performance")}function gs(n){let e=de(n,0,new Set);return e?Es(e.contract,e.canonicalReport):null}function io(n){if(!n.sessionId||!fs(n.toolName))return null;let e=gs(n.toolResponse);if(!e)return null;let t=Date.now(),o=n.runtimeStore.addEvidenceObligation(n.sessionId,e,t,n.toolUseId),r=n.runtimeStore.get(n.sessionId);if(o&&r){let i=openGlobalDevFlowDatabase();try{i.upsertSessionObligation({obligationId:`evidence:${o.obligationId}`,projectRoot:r.projectRoot,sessionId:n.sessionId,executionId:r.executionId,kind:"evidence_contract",state:"open",payload:{contract:e,runtimeObligationId:o.obligationId},createdAt:t,updatedAt:t});}finally{i.close();}}return hs(e)}function hs(n){return [`DevFlow performance evidence contract ${n.id} is active.`,`The final performance answer MUST contain these three sections exactly: ${n.requiredSections.join(" / ")}.`,n.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=${n.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.",n.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,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,appendFileSync,realpathSync,statSync,readSync,lstatSync as lstatSync$1,chmodSync,fsyncSync}from'node:fs';import {join,dirname as dirname$1,basename,resolve,relative,sep,isAbsolute}from'node:path';import {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 Q(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 ui=getLocalApiKey(),dt=join(homedir(),".devflow","errors");async function B(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 mi(o,e,t,r),a&&registerRuntimeHttpSuccess(o,e).transitioned&&Q("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)),u<s&&await pi(Math.min(100*2**u,1e3));}if(!d)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return bn(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&&(bn(e,d),Q("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 mi(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":ui,"Content-Length":Buffer.byteLength(s)},timeout:o},u=>{u.on("error",d),u.on("end",()=>{let m=u.statusCode??0;d(m>=200&&m<300?void 0:new Error(`HTTP ${m}`));}),u.resume();});l.on("error",d),l.on("timeout",()=>l.destroy(new Error(`HTTP mirror timed out after ${o}ms`))),l.write(s),l.end();})}function bn(e,t){try{existsSync(dt)||mkdirSync$1(dt,{recursive:!0}),appendFileSync(join(dt,"http-errors.log"),`${new Date().toISOString()} | ${e} | ${t.message}
2
+ `);}catch{}}function pi(e){return new Promise(t=>setTimeout(t,e))}var Tn=1e4,vi=3e4,xe=500,X=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:xe}).reverse();for(let i of r)try{this.applyOperation(i.operation,i.payload),o.resolveTelemetryFailure(i.id);}catch{}o.trimTelemetryFailures(xe);}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:_i(JSON.parse(readFileSync(i,"utf8")),r)}}catch{return null}})).filter(o=>o!==null).sort((o,r)=>o.envelope.timestamp-r.envelope.timestamp||An(o.envelope.operation)-An(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:Cn(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(Cn(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(xe),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-xe)))unlinkSync(join$1(this.cacheDir,n));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},vi).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){B(t,n,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let n=JSON.stringify(t);return n===void 0||n.length<=Tn?t:{_truncated:true,_original_size:n.length,_preview:`${n.substring(0,Tn)}...`}}};function An(e){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(e)}function Cn(e){return `hook-run:${e}`}function _i(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 Ee(e){return e??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function D(e){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(Ee(e))}var Ri=2,xi=1;function Ei(){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 Dn(e=Ei()){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!==Ri&&o.version!==xi||!Ti(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 Ti(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 Te(n.mcpTools)&&Te(n.blockedNative)&&(n.source===void 0||n.source==="core"||n.source==="plugin")&&(n.requiresContext===void 0||typeof n.requiresContext=="boolean")&&(n.runtimePackages===void 0||Te(n.runtimePackages))&&(n.hostTools===void 0||Ai(n.hostTools))&&(n.evidenceMode===void 0||["static","runtime","mixed"].includes(n.evidenceMode))})}function Ai(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&Object.entries(e).every(([t,n])=>t.length>0&&Te(n))}function Te(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0)}function Mn(e){let t=Dn();return t?t[e]?.mcpTools??[]:[]}function On(e,t,n){return formatSkillRuntimeOverlay(createSkillRuntimeOverlay(e,t,{prompt:n}))}var ut=join$1(homedir$1(),".devflow"),mt=join$1(ut,"server-refs.json"),Li=600*1e3,Wi=500;function qi(){existsSync$1(ut)||mkdirSync(ut,{recursive:true});}function Ae(){try{if(existsSync$1(mt))return JSON.parse(readFileSync(mt,"utf-8"))}catch{}return {sessions:[],lastActivity:0}}function Pn(e){qi(),writeFileSync(mt,JSON.stringify(e));}var De=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=Ae();n.sessions.includes(t)||n.sessions.push(t),n.lastActivity=Date.now(),Pn(n),this.resetIdleTimer();}removeRef(t){let n=Ae();n.sessions=n.sessions.filter(o=>o!==t),n.lastActivity=Date.now(),Pn(n),n.sessions.length===0&&this.resetIdleTimer();}get activeSessions(){return Ae().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=Ui(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,Wi));}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),!(Ae().sessions.length>0)&&(this.idleTimer=setTimeout(()=>{this.stop();},Li).unref());}};function Ui(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 Me(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 Ji(e,t){return e.lastMcpCall===t.lastMcpCall&&e.bypassCount===t.bypassCount}function Gi(e){try{return existsSync$1(e)?Me(JSON.parse(readFileSync(e,"utf-8"))):{}}catch{return {}}}function Vi(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 jn(e){let t=D(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 Ki(e,t){if(e.getHookReceipt(t)){jn(t);return}let n=join$1(D(t),"receipt.json");if(!existsSync$1(n))return;let o=Gi(n);e.updateHookReceipt(t,()=>o),jn(t);}function $n(e,t,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),Ki(o,e);let r={},i=o.updateHookReceipt(e,a=>(r=Me(a),Me(t(r)))),s=Me(i);return {receipt:s,applied:!0,changed:!Ji(r,s)}}catch(r){return Vi(e,n,r),{receipt:{},applied:false,changed:false}}finally{try{o?.close();}catch{}}}function Oe(e,t){return $n(e,()=>t,"write").applied}function ht(e,t){return $n(e,t,"update")}var Fn={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},Qi=new Set(["Write","Edit","NotebookEdit"]),Yi=new Set(["failed","timeout","unavailable"]);function Xi(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 Z=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"&&Fn[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(Qi.has(t)){let c=this.evaluateRequiredAction();if(c)return c}return {permissionDecision:"allow"}}let r=Fn[t];if(!r)return {permissionDecision:"allow"};let i=ht(this.projectRoot,c=>({...c,bypassCount:(c.bypassCount??0)+1}));if(!i.applied)return {permissionDecision:"allow"};let s=i.receipt.bypassCount??0,a=Xi(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(){Oe(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&&Yi.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 rs=10,is=5e3,ss=3e4,as=new Int32Array(new SharedArrayBuffer(4)),Un=0;function cs(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 zn(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(cs);return {entries:n,needsRepair:n.length!==t.length}}catch{return {entries:[],needsRepair:true}}}function Bn(e,t){mkdirSync$1(dirname$1(e),{recursive:true});let n=`${e}.${process.pid}.${Date.now()}.${Un++}.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 Jn(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function Gn(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 Hn(e,t){try{return readFileSync$1(e,"utf8")!==t?!1:(rmSync$1(e),!0)}catch(n){return n.code==="ENOENT"}}function ds(e){try{let t=readFileSync$1(e,"utf8"),n;try{let r=JSON.parse(t);Gn(r)&&(n=r);}catch{}return n?Jn(n.pid)?!1:Hn(e,t):Date.now()-statSync(e).mtimeMs>ss&&Hn(e,t)}catch(t){return t.code==="ENOENT"}}function ls(e){mkdirSync$1(dirname$1(e),{recursive:true});let t=`${e}.lock`,n=Date.now()+is;for(;;){let o=`${process.pid}:${Date.now()}:${Un++}`,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(!ds(t)){if(Date.now()>=n)throw new Error(`Timed out acquiring daemon registry lock: ${t}`);Atomics.wait(as,0,0,rs);}}}function us(e){try{let t=readFileSync$1(e.path,"utf8"),n=JSON.parse(t);Gn(n)&&n.token===e.token&&rmSync$1(e.path);}catch(t){if(t.code!=="ENOENT")throw t}}function Vn(e){let t=getDaemonRegistryPath(),n=ls(t);try{return e(t)}finally{us(n);}}function Kn(e,t){Vn(n=>{let o=zn(n).entries.filter(r=>r.rootPath!==e&&Jn(r.pid));o.push({rootPath:e,projectHash:getProjectHash(e),pid:t,startedAt:Date.now()}),Bn(n,o);});}function Qn(e,t){Vn(n=>{let o=zn(n).entries.filter(r=>r.rootPath!==e||t!==void 0&&r.pid!==t);Bn(n,o);});}async function fe(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 Yn(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 to(e){return Buffer.from(e,"utf8").toString("base64url")}function vs(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 ao(e){return `${e}:legacy-journal`}var H=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(D(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=no(i.evidenceObligations),i.evidenceDegradations=oo(i.evidenceDegradations),i.evidenceOutcomes=ro(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??vs(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,`${to(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",to(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=no(t.evidenceObligations),t.evidenceDegradations=oo(t.evidenceDegradations),t.evidenceOutcomes=ro(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=_s(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||io(i.kind)-io(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 no(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)||!co(n.contract))return [];let o=typeof n.obligationId=="string"&&n.obligationId.length>0&&n.obligationId.length<=384?n.obligationId:ao(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 oo(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 ro(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 _s(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:ao(t.contractId),contractId:t.contractId,at:t.at};if(n==="add")return co(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 io(e){return e==="add"?0:e==="correction"?1:2}function co(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 mo(e,t){let n=ho(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 po(e){let t=ho(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 fo(e){unlinkSync$1(e.path);}function go(e){try{renameSync(e.path,e.path.replace(/\.claim-\d+$/u,""));}catch{}}function ho(e){return join(D(e),"session-finalize-pending")}var Cs=256*1024,Ds=48*1024,Ms=512*1024,Os=500,Ps=5,ge=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function js(e){return e==="react_audit_performance"||e.endsWith("__react_audit_performance")}function Fs(e){let t=he(e,0,new Set);return t?Gs(t.contract,t.canonicalReport):null}function _o(e){if(!e.sessionId||!js(e.toolName))return null;let t=Fs(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:Le(e.toolResponse),runtimeProfilingOccurred:t.runtimeProfilingOccurred,samplingEvidenceOccurred:t.samplingEvidenceOccurred,toolUseId:e.toolUseId}});}return $s(t)}function $s(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 so(n){let e=n.runtimeStore??new M(n.projectRoot),t=e.listEvidenceObligations(n.sessionId);if(t.length===0)return null;let o=co(n.transcriptPath,t);if(!o.answer){let s=o.degradationReason??"transcript_answer_unavailable";for(let a of t)e.degradeEvidenceObligation(n.sessionId,a.obligationId,s);return null}let r=o.fingerprint;if(!r){for(let s of t)e.degradeEvidenceObligation(n.sessionId,s.obligationId,"transcript_identity_unavailable");return null}let i=[];for(let s of t){let a=vs(o.answer,[s]);if(a.length===0){e.resolveEvidenceObligation(n.sessionId,s.obligationId);continue}if(!s.correctionFingerprint){e.markEvidenceCorrection(n.sessionId,s.obligationId,a,r),i.push({obligation:s,violations:a});continue}if(s.correctionFingerprint===r){i.push({obligation:s,violations:a});continue}e.degradeEvidenceObligation(n.sessionId,s.obligationId,"evidence_contract_unresolved");}return i.length===0?null:ys(i)}function ys(n){let e=[...new Set(n.flatMap(o=>o.violations))],t=[...new Map(n.map(o=>[o.obligation.contractId,o.obligation.contract.canonicalReport])).values()];return {decision:"block",reason:["DevFlow evidence contract violation. Correct the final performance answer once before stopping.",`Violations: ${e.join("; ")}`,"Use this canonical report (you may add clearly labeled hypotheses or runtime verification steps, but no unsupported measured claims):",t.join(`
4
+ `)}function wo(e){let t=e.runtimeStore??new H(e.projectRoot),n=t.listEvidenceObligations(e.sessionId);if(n.length===0)return Hs(e,t),null;let o=bt(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=Io(o.answer,[s]);if(a.length===0){t.resolveEvidenceObligation(e.sessionId,s.obligationId),Ne(e,s,"satisfied",r);continue}if(!s.correctionFingerprint){t.markEvidenceCorrection(e.sessionId,s.obligationId,a,r),i.push({obligation:s,violations:a}),Ne(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"),Ne(e,s,"degraded",r,a);}return i.length===0?null:Ns(i)}function Hs(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=bt(e.transcriptPath,o);if(!(!r.answer||!r.fingerprint))for(let i of o)Io(r.answer,[i]).length>0||t.resolveDegradedEvidence(e.sessionId,i.obligationId)&&Ne(e,i,"satisfied",r.fingerprint);}function Ne(e,t,n,o,r=[]){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 Le(e,t=0){if(t>6||e==null)return [];if(typeof e=="string")try{return Le(JSON.parse(e),t+1)}catch{return []}if(Array.isArray(e)){for(let o of e){let r=Le(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=Le(o,t+1);if(r.length>0)return r}return []}function Ns(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 vs(n,e){let t=new Set,o=new Set(e.flatMap(c=>c.contract.requiredSections)),r=ao(n.split(/\r?\n/)),i=lo(r.headingLines);for(let c of o)i.found.has(c)||t.add(`missing_section:${c}`);if(e.every(c=>c.contract.runtimeProfilingOccurred))return [...t];let a=e.every(c=>c.contract.samplingEvidenceOccurred);for(let c=0;c<r.claimLines.length;c++){let l=r.claimLines[c].trim();if(!l||bs(l))continue;let d=i.byLine.get(c);for(let u of Rs(l))ks(u,d,a,t);}return [...t]}function ao(n){let e=false,t=[],o=[];for(let r of n){if(/^\s*```/.test(r)){e=!e,t.push(""),o.push(r.replace(/^\s*```+[^\s`]*/,"").replace(/```+\s*$/,"").trim());continue}t.push(e?"":r.replace(/`[^`]*`/g,"").trim()),o.push(r.replace(/`([^`]*)`/g,(i,s)=>ws(s)?"":s).trim());}return {headingLines:t,claimLines:o}}function ws(n){let e=n.trim().slice(0,256);return !e||/\s/.test(e)||n.trim().length>256?false:/^[A-Za-z_$][\w$.-]*$/.test(e)||/^(['"])[^'"`]*\1$/.test(e)}function bs(n){if(n.length>2048)return false;let e=n.replace(/^\s*(?:[-*+]|\d+[.)])\s+/,"").trim();return e?_s(e)||/^(?:\/\/|\/\*|\*\/|\*\s|#!)/.test(e)||/^(?:import|export|const|let|var|function|class|type|interface|enum|namespace|declare)\b/.test(e)||/^(?:async\s+)?(?:function\s+)?[A-Za-z_$][\w$]*\s*=\s*/.test(e)||/^[A-Za-z_$][\w$.[\]'"-]*\s*(?:=|\+=|-=|\*=|\/=|\?\?=|&&=|\|\|=)\s*/.test(e)||/^[A-Za-z_$'"-][\w$.'"-]*\s*:\s*[^:]+[,}]?$/.test(e)||/=>/.test(e)||/^(?:await\s+|return\s+|throw\s+|new\s+)?[A-Za-z_$][\w$.]*\s*\([^)]*\)\s*;?$/.test(e)||/^(['"])[\s\S]*\1[;,]?$/.test(e)?true:/[{}()[\]=<>]\s*;?$/.test(e)&&/(?:;|=>|\b(?:return|new|await)\b)/.test(e):false}function _s(n){if(n.length>1024)return false;let e="(?:--[A-Za-z0-9_-]+|(?:-webkit-|-moz-|-ms-)?(?:animation(?:-[a-z-]+)?|transition(?:-[a-z-]+)?|opacity|transform|will-change|contain|content-visibility|display|position|top|right|bottom|left|width|height|min-(?:width|height)|max-(?:width|height)|margin(?:-[a-z]+)?|padding(?:-[a-z]+)?|color|background(?:-[a-z-]+)?|border(?:-[a-z-]+)?|font(?:-[a-z-]+)?|line-height|z-index|overflow(?:-[xy])?))";return new RegExp(`^${e}\\s*:\\s*\\S[^;]{0,960};$`,"i").test(n)}function ks(n,e,t,o){let r=/\bP0\b/gi;for(let v of n.matchAll(r))ro(n,v.index??0,v[0],"p0")||o.add("unsupported_p0_severity");let i=/(?:中高|高)(?:风险|优先级)|严重(?:问题|风险)|\bhigh[- ](?:risk|severity|priority)\b/gi;for(let v of n.matchAll(i))ro(n,v.index??0,v[0],"high")||o.add("unsupported_high_severity");let s=/(?:性能)?瓶颈|卡顿|掉帧|CPU\s*(?:热点|尖峰)|\bbottleneck\b|\bjank\b|\bdropped frames?\b|\bCPU hotspot\b/gi;for(let v of n.matchAll(s))Is(n,v.index??0,v[0])||(/(?:瓶颈|bottleneck)/i.test(v[0])?o.add("unsupported_confirmed_bottleneck"):o.add("unsupported_runtime_effect"));let a=/\b\d{1,3}(?:\.\d+)?\s*%/.test(n),c=/(?:预计|预期|估计|提升|降低|减少|节省|改善|收益|加速|improve|reduce|faster|gain|benefit|speedup|expected|estimated)/i.test(n),l=/\b\d+(?:\.\d+)?\s*[x×]\b/i.test(n);(a||l)&&c&&o.add(a?"unsupported_benefit_percentage":"unsupported_performance_number");let d=/\b\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:ms|fps|hz)\b/i.test(n)||/\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:毫秒|次\s*\/\s*秒|帧)/.test(n),u=e==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&/(?:采集|记录|测量|收集|collect|measure|record)/i.test(n)&&!/(?:预计|预期|估计|约|大约|通常|平均|每(?:隔)?|达到|提升|降低|减少|节省|改善|improve|reduce|faster|expected|estimated|average|typically|every)/i.test(n);a&&!c&&!u&&o.add("unsupported_benefit_percentage"),d&&!u&&o.add("unsupported_performance_number");let p=/(?:requestAnimationFrame|\bRAF\b)/i.test(n),f=/(?:建议|应该|应当|使用|添加|采用|切换|包裹|优化|节流|\buse\b|\badopt\b|\brecommend\b|\bswitch\b|\bwrap\b|\bthrottl(?:e|ing)\b)/i.test(n),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(n);p&&f&&!m&&!t&&o.add("raf_without_sampling_evidence");}function ro(n,e,t,o){let r=n.slice(Math.max(0,e-64),e),i=n.slice(e+t.length,e+t.length+28),s=Ss(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 Ss(n){if(/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?|不是|并非|未被)\s*(?:任何|明确的)?\s*(?:(?:问题|发现|证据|项|内容)\s*)?(?:(?:属于|(?:被)?(?:评|判定|认定|标记|列|视|定|归(?:类)?)为)\s*)?$/i.test(n)||/\b(?:no evidence (?:of|for)|no|not|isn't|is\s+not)\s+(?:an?\s+)?(?:(?:issues?|findings?|evidence|items?)\s+)?(?:(?:classified|rated|marked|labelled|labeled)(?:\s+as)?\s+)?$/i.test(n))return true;let t=/(?:不得|不能|不应|不宜|不要)\s*(?:被\s*)?(?:(?:直接|轻易|简单|明确|正式|合理|据此|当前|目前)\s*){0,2}(?:(?:评|判定|认定|标记|列|视|定|归(?:类)?)为|属于)\s*$/i,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 t.test(n)||o.test(n)}function Is(n,e,t){let o=n.slice(Math.max(0,e-40),e),r=n.slice(e+t.length,e+t.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 Rs(n){return n.split(/(?:[。!?;;,,]|\b(?:but|however|yet|nevertheless|nonetheless)\b|但是|但|然而|却|不过|可是)/i).map(e=>e.trim()).filter(Boolean)}function de(n,e,t){if(e>ms||n===null||n===void 0)return null;if(typeof n=="string"){if(Buffer.byteLength(n,"utf8")>ls)return null;try{return de(JSON.parse(n),e+1,t)}catch{return null}}if(typeof n!="object"||t.has(n))return null;if(t.add(n),Array.isArray(n)){for(let r of n.slice(0,16)){let i=de(r,e+1,t);if(i)return i}return null}let o=n;if("evidenceContract"in o)return {contract:o.evidenceContract,canonicalReport:o.canonicalReport};for(let r of ["structuredContent","data","result"])if(r in o){let i=de(o[r],e+1,t);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=de(i,e+1,t);if(s)return s}return null}function Es(n,e){if(!n||typeof n!="object"||Array.isArray(n))return null;let t=n;if(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(t.requiredSections)||t.requiredSections.length!==le.length)return null;let o=t.requiredSections.filter(c=>typeof c=="string");if(o.length!==le.length||le.some((c,l)=>o[l]!==c)||!Array.isArray(t.prohibitedClaims)||t.prohibitedClaims.length>16)return null;let r=t.prohibitedClaims.filter(c=>typeof c=="string"&&c.length<=128);if(r.length!==t.prohibitedClaims.length)return null;let i=t.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 t.canonicalReport=="string"?t.canonicalReport:e;return typeof a!="string"||Buffer.byteLength(a,"utf8")>ds||le.some(c=>!a.includes(c))?null:{version:"1.0",id:t.id,runtimeProfilingOccurred:t.runtimeProfilingOccurred,samplingEvidenceOccurred:t.samplingEvidenceOccurred,requiredSections:o,prohibitedClaims:r,correctionPolicy:{maxAttempts:1,repeatedViolation:"fail_open"},canonicalReport:a}}function co(n,e){if(!n||n.length>4096)return {degradationReason:"transcript_path_missing"};let t;try{let o=lstatSync$1(n);if(!o.isFile()||o.isSymbolicLink())return {degradationReason:"transcript_path_unsafe"};t=openSync$1(n,constants.O_RDONLY|(constants.O_NOFOLLOW??0));let r=fstatSync$1(t);if(!r.isFile()||r.dev!==o.dev||r.ino!==o.ino)return {degradationReason:"transcript_path_changed"};let i=Math.min(r.size,us),s=Buffer.alloc(i),a=0;for(;a<i;){let m=readSync(t,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 l=c.split(/\r?\n/).slice(-ps),d=e.length>0?Math.min(...e.map(m=>m.promptedAt)):0,u=Ts(l,d),f=[...u].reverse().find(m=>xs(m.text,e))??u.at(-1);return f?.text?{answer:f.text,fingerprint:f.fingerprint}:{degradationReason:"transcript_answer_unavailable"}}catch{return {degradationReason:"transcript_unreadable"}}finally{t!==void 0&&closeSync$1(t);}}function xs(n,e){let t=new Set(e.flatMap(r=>r.contract.requiredSections)),o=lo(ao(n.split(/\r?\n/u)).headingLines);return [...t].every(r=>o.found.has(r))}function Me(n){return co(n,[]).answer}function Ts(n,e){let t=[];for(let o=0;o<n.length;o++){let r=n[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=Cs(i.timestamp);if(c>0&&c+5e3<e)continue;let l=s.content,d=typeof l=="string"?l:Array.isArray(l)?l.filter(u=>u&&typeof u=="object"&&u.type==="text").map(u=>u.text).filter(u=>typeof u=="string").join(`
12
- `):"";if(d.trim()){let u=d.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")}`,f=createHash("sha256").update(u).digest("hex"),m=createHash("sha256").update(`${p}\0${f}`).digest("hex");t.push({text:u,timestamp:c,fingerprint:m});}}catch{continue}}return t}function Cs(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?e:0}function lo(n){let e=new Set,t=new Map,o;for(let r=0;r<n.length;r++){let i=n[r].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=le.find(a=>i===a);s&&(o=s,e.add(s)),t.set(r,o);}return {found:e,byLine:t}}function fo(n){let e;try{if(Ps(n.toolResponse))return null;e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let t=e.getActiveContextReceipt(n.projectRoot,n.sessionId,n.executionId);if(!t)return null;let o=n.toolName==="Read"?Ms(n.toolInput):void 0,r=o?t.selectedFiles?.find(d=>As(n.projectRoot,d,o)):void 0,i=Os(n.toolName),s=r?"code":t.canonicalNextAction===i?"action":null,a=r??(s==="action"?i:void 0);if(!s||!a)return null;let c=[t.contextHash,t.requestId??"",s,a,n.toolUseId??`${n.sessionId}:${n.executionId??t.executionId}`].join("\0");e.recordContextSelectionEvent({id:`ctxsel:${createHash("sha256").update(c).digest("hex").slice(0,32)}`,projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:t.executionId,requestId:t.requestId,selectionType:s,candidateId:a,toolName:n.toolName,toolUseId:n.toolUseId,selectedAt:Date.now()});let l=e.listRetrievalLedgerEvents({projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:t.executionId,requestId:t.requestId}).find(d=>d.sourceType===s&&d.sourceId===a&&d.stage==="selected");return l&&e.appendRetrievalLedgerEvent({...l,id:ho(l.id,"adopted",n.toolUseId??n.toolName),stage:"adopted",toolEvidence:[n.toolUseId??n.toolName],payload:{...l.payload,adoptedByTool:n.toolName},createdAt:Date.now()}),s}catch{return null}finally{try{e?.close();}catch{}}}function go(n){let e=openGlobalDevFlowDatabase();try{let t=e.listRetrievalLedgerEvents(n),o=new Map(t.filter(c=>c.stage==="selected").map(c=>[uo(c),c])),r=new Map(t.filter(c=>c.stage==="adopted").map(c=>[uo(c),c])),i=0,s=0,a=0;for(let[c,l]of o){let d=r.get(c),u=d&&n.verificationReceipt&&n.outcome!=="unknown"?n.outcome:"unknown",p=u==="positive"?"positive_outcome":u==="negative"?"negative_outcome":"unknown";e.appendRetrievalLedgerEvent({...l,id:ho(l.id,p,n.verificationReceipt??n.sessionId),stage:p,reason:d?n.outcomeReason:"selected_not_adopted",toolEvidence:d?.toolEvidence??[],verificationReceipt:u==="unknown"?void 0:n.verificationReceipt,payload:{...l.payload,adopted:!!d},createdAt:n.finishedAt??Date.now()}),p==="positive_outcome"?i+=1:p==="negative_outcome"?s+=1:a+=1;}return {adopted:r.size,positive:i,negative:s,unknown:a}}finally{e.close();}}function Ms(n){for(let e of ["file_path","path"]){let t=n[e];if(typeof t=="string"&&t.trim())return t.trim()}}function As(n,e,t){let o=resolve(n,e),r=isAbsolute(t)?resolve(t):resolve(n,t);return o===r}function Os(n){return n.startsWith("mcp__")?n.split("__").at(-1)??n:n}function Ps(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let e=n;return e.ok===false||e.success===false||e.isError===true||!!e.error||["failed","rejected","unavailable"].includes(String(e.status??""))}function ho(n,e,t){return `retrieval:${createHash("sha256").update(`${n}\0${e}\0${t}`).digest("hex")}`}function uo(n){return [n.requestId,n.contextReceipt,n.sourceType,n.sourceId].join("\0")}function ft(n){let e={committed:0,skipped:0,pending:0},t=[];for(let o of n)e[o.status]+=1,o.receiptId&&t.push(o.receiptId);return {memoryReceiptIds:[...new Set(t)],missingMemoryDecisionCount:e.pending,memoryTurnOutcomes:e}}function B(n){return (n instanceof Error?n.message:String(n)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var $=class extends Error{constructor(e,t){super(`session_finalize_${e}:${t}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${e}`;}};function ue(n){let e;try{e=openGlobalDevFlowDatabase();let t=(n.executionId?e.getSkillExecution(n.executionId):null)??e.getLatestSkillExecutionForSession(n.sessionId),o={stage:n.stage,reason:n.reason,degradedAt:Date.now()};t&&e.mergeSkillExecutionMetadata(t.executionId,{...n.metadata,sessionFinalizationDegradations:[o]}),e.insertEvent({kind:"session_finalize_degraded",timestamp:o.degradedAt,success:!1,metadata:{projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:t?.executionId,...o}});}catch{}finally{e?.close();}}function Ae(n,e=be(),t=true,o,r=true){let i;try{i=JSON.parse(n);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${e}\0${s}`).digest("hex").slice(0,24)}`,c={inputJson:n,sessionId:s,cleanupSharedState:t,executionId:o},l;try{l=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let d=l.requestSessionClosure({receiptId:a,projectRoot:e,sessionId:s,payload:c}),u=l.getWorkByIdempotencyKey(a);return {status:d.state==="closed"||d.state==="closed_with_pending_work"?"completed":"accepted",receiptId:a,workState:u?.state??"pending",closureState:d.state,pendingWorkCount:d.pendingWorkCount}}catch(d){if(!r)throw d;return Qn(e,{receiptId:a,...c}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{l?.close();}}async function vo(n,e=be(),t=true,o){let r;try{r=JSON.parse(n);}catch{return}let i=r.session_id?.trim();if(!i)return;let s=new M(e),a=s.get(i),c={evidenceDegradations:a?.evidenceDegradations??[],evidenceContractOutcomes:a?.evidenceOutcomes??[],pendingEvidenceContractIds:a?.evidenceObligations.map(f=>f.contractId)??[]},l=o?.telemetry??new U,d=!o?.telemetry,u=false,p;try{try{await l.flushAndAggregate();}catch{}let f=Date.now(),m=o?.executionId??a?.executionId,v;try{let h=openGlobalDevFlowDatabase();try{v=h.listSessionMemoryTurnsForReconciliation(e,i);for(let g of v){let b=`memory:${g.turnId}`,y=h.getSessionObligation(e,i,b);y?y.state==="open"&&g.status!=="pending"&&h.resolveSessionObligation({projectRoot:e,sessionId:i,obligationId:b,state:"satisfied",receiptId:g.receiptId,reason:g.reason,resolvedAt:g.decidedAt}):h.upsertSessionObligation({obligationId:b,projectRoot:e,sessionId:i,turnId:g.turnId,kind:"memory_decision",state:g.status==="pending"?"open":"satisfied",payload:{eventId:g.eventId,promptHash:g.promptHash},receiptId:g.receiptId,reason:g.reason,createdAt:g.createdAt,updatedAt:g.decidedAt??g.createdAt,resolvedAt:g.decidedAt});}}finally{h.close();}}catch(h){let g=B(h),b={...c,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:g,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ue({projectRoot:e,sessionId:i,executionId:m,stage:"turn_load",reason:g,metadata:b}),new $("turn_load",g)}let w=ft(v),S=o?.memory??(p=new MemoryGate(e)),I={status:"completed"};try{I=typeof S.reconcileTurnObservationLineage=="function"?{status:"completed",...await S.reconcileTurnObservationLineage(v)}:{status:"unsupported_adapter",committed:0,skipped:0,quarantined:0,unlinked:0};}catch(h){let g=B(h);throw I={status:"degraded",reason:g},ue({projectRoot:e,sessionId:i,executionId:m,stage:"memory_lineage",reason:g,metadata:{...w,...c,memoryLineageReconciliation:I}}),new $("memory_lineage",g)}let E={status:"unknown",selected:0,adopted:0,unknown:0,positive:0,negative:0};try{let h=Me(r.transcript_path),g=openGlobalDevFlowDatabase(),b="unknown",y="no_terminal_host_action_evidence",ye,te,ne,Ke=[];try{let Ye=g.listHostActionsForSession(e,i,m),on=Ye.filter(T=>T.state==="verified"),Xe=Ye.filter(T=>["failed","cancelled","degraded"].includes(T.state));Xe.length>0?(b="negative",y=`terminal_host_action_${Xe[0].state}`):on.length>0&&(b="positive",y="host_action_verified");let ve=Xe[0]??on.at(-1);if(ye=ve?.runId,te=ve?.contextReceipt,ne=ve?.evidenceHash,Ke=Ye.flatMap(T=>{let L=T.report.toolUseIds;return Array.isArray(L)?L.filter(oe=>typeof oe=="string"):[]}),!ve&&m){let T=g.getSkillExecution(m),L=T?.metadata&&typeof T.metadata=="object"&&Array.isArray(T.metadata.policyVerificationOutcomes)?T.metadata.policyVerificationOutcomes:[],oe=L.find(j=>j.status==="failed"),Qe=L.filter(j=>j.status==="passed");oe?(b="negative",y="policy_verification_failed",ne=typeof oe.receiptId=="string"?oe.receiptId:void 0):Qe.length>0&&(b="positive",y="policy_verification_passed",ne=typeof Qe.at(-1)?.receiptId=="string"?String(Qe.at(-1).receiptId):void 0),te=g.getActiveContextReceipt(e,i,m)?.contextHash,Ke=L.map(j=>j.command).filter(j=>typeof j=="string");}}finally{g.close();}let Fr=go({projectRoot:e,sessionId:i,executionId:m,outcome:b,outcomeReason:y,verificationReceipt:ne,finishedAt:f}),$r=await S.attributeRetrievalBenefits({sessionId:i,executionId:m,finalAnswer:h,outcome:b,outcomeReason:y,workflowRunId:ye,contextReceipt:te,toolEvidence:Ke,verificationReceipt:ne});E={status:h?"evaluated":"unknown",...$r,retrievalLedger:Fr};}catch(h){E={...E,status:"degraded",reason:B(h)};}let C;try{C=await S.reconcileDecidedTurnEventWindows(i,v,f);}catch(h){let g=B(h),b={...w,...c,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:g,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ue({projectRoot:e,sessionId:i,executionId:m,stage:"event_reconciliation",reason:g,metadata:b}),new $("event_reconciliation",g)}let P;try{P=await ce({projectRoot:e,sessionId:i,trigger:"session_end",memory:S,details:{eventReconciliation:C},strictPersistence:!0});}catch(h){let g=B(h),b={...w,...c,memoryEventReconciliation:{status:"completed",...C,checkpointPending:null},memoryCheckpointDegradation:g};throw ue({projectRoot:e,sessionId:i,executionId:m,stage:"checkpoint",reason:g,metadata:b}),new $("checkpoint",g)}let N={memoryLineageReconciliation:I,memoryBenefitAttribution:E,memoryEventReconciliation:{status:"completed",...C,checkpointPending:P.pendingEvents},memoryDistillCheckpoint:P};try{let h=openGlobalDevFlowDatabase();try{let g=`session-finalize:${i}:events`,b=Math.max(Number(P.pendingEvents??0),Number(C.remainingUndecided??0)),y=h.getSessionObligation(e,i,g);b>0?h.upsertSessionObligation({obligationId:g,projectRoot:e,sessionId:i,executionId:m,kind:"session_finalize",state:"open",payload:{pendingEvents:b,reconciliation:C,checkpointId:P.id},reason:"active_unprocessed_session_events",createdAt:y?.createdAt??f,updatedAt:f}):y?.state==="open"&&h.resolveSessionObligation({projectRoot:e,sessionId:i,obligationId:g,state:"satisfied",reason:"session_events_reconciled",resolvedAt:f});}finally{h.close();}}catch(h){console.error("[devflow] Session finalization obligation persistence failed:",h.message);}try{await S.closeSession(i),p&&(p.close(),p=void 0);}catch(h){let g=B(h),b={...w,...c,...N,memorySessionCloseDegradation:g};throw ue({projectRoot:e,sessionId:i,executionId:m,stage:"memory_close",reason:g,metadata:b}),new $("memory_close",g)}let D={...w,...c,...N};u=!0;let _;try{_=openGlobalDevFlowDatabase();let h=m;if(h)try{_.reconcileSkillExecution(h,"completed",f,D);let y=_.getSkillExecution(h);await F("/api/telemetry/skill-execution/complete",{executionId:h,finishedAt:f,status:"completed",summary:{totalToolCalls:y?.totalToolCalls??0,mcpToolCalls:y?.mcpToolCalls??0,directToolCalls:y?.directToolCalls??0,subagentCount:y?.subagentCount??0,totalDuration:y?.totalDuration??0,mcpComplianceRate:y?.mcpComplianceRate??0,missedTools:y?.missedMcpTools??[],actualFailureCount:y?.failedToolCalls??0,fallbackCount:y?.fallbackCount??0,fallbackReasons:y?.fallbackReasons??[]},metadata:D},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let g=_.reconcileRunningSkillExecutionsForSession(i,f,{closureReason:"session_finalize",...D});for(let y of g)await F("/api/telemetry/skill-execution/complete",{executionId:y.executionId,finishedAt:y.finishedAt,status:y.status,summary:{totalToolCalls:y.totalToolCalls??0,mcpToolCalls:y.mcpToolCalls??0,directToolCalls:y.directToolCalls??0,subagentCount:y.subagentCount??0,totalDuration:y.totalDuration??0,mcpComplianceRate:y.mcpComplianceRate??0,missedTools:y.missedMcpTools??[],actualFailureCount:y.failedToolCalls??0,fallbackCount:y.fallbackCount??0,fallbackReasons:y.fallbackReasons??[]},metadata:D},{fallbackReason:"skill_execution_already_reconciled_locally"});let b=_.getLatestSkillExecutionForSession(i);if(b&&!g.some(y=>y.executionId===b.executionId)&&_.mergeSkillExecutionMetadata(b.executionId,D),t){_.deleteHookReceipt(e);let y=R(e),ye=createHash("sha256").update(e).digest("hex").slice(0,12);for(let te of [`session-id-${ye}`,"current-execution-id","current-skill.json","event-map.json"])rmSync$1(join(y,te),{force:!0});}_.deleteContextReceipt(e,i);}catch{}finally{_?.close();}try{await l.endSession(i),await l.flushAndAggregate();}catch{}}finally{if(p)try{p.close();}catch{}d&&l.close(),u&&s.removeSession(i);}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let n=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t;}),process.stdin.on("end",async()=>{let t=Ae(e.trim()||process.argv[2]||"");t&&n(JSON.stringify(t)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var zs=/^\/(?:devflow:)?[\w-]+\b\s*/iu,Js=/\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,Bs=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,Gs=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function Oe(n){let e=n.trim().replace(zs,"").trim();return !e||Js.test(e)?null:(Gs.exec(e)??Bs.exec(e))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}function Vs(n){let e=createHash("sha256").update(n).digest("hex").slice(0,16),t=process.env.DEVFLOW_STATE_DIR||join(homedir(),".devflow","state",e);return join(t,"memory-intents.jsonl")}function Ks(n){try{return readFileSync$1(n,"utf8").split(`
13
- `).filter(Boolean).flatMap(e=>{try{let t=JSON.parse(e);return typeof t.content=="string"&&typeof t.createdAt=="number"?[t]:[]}catch{return []}})}catch{return []}}function ko(n){let e=Vs(n),t=`${e}.claim-`,o=`${basename(e)}.claim-`,r=(()=>{try{return readdirSync$1(dirname$1(e)).filter(a=>a.startsWith(o)&&!a.includes(".tmp-")).sort()[0]}catch{return}})(),i=r?join(dirname$1(e),r):`${t}${Date.now()}-${process.pid}`;if(!r)try{renameSync(e,i);}catch{return null}let s=Ks(i);if(s.length===0){try{unlinkSync$1(i);}catch{}return null}return {path:i,intents:s}}function ht(n){if(n.intents.shift(),n.intents.length===0){try{unlinkSync$1(n.path);}catch{}return}let e=`${n.path}.tmp-${process.pid}`;writeFileSync$1(e,n.intents.map(t=>JSON.stringify(t)).join(`
10
+ `)}}function Io(e,t){let n=new Set,o=new Set(t.flatMap(c=>c.contract.requiredSections)),r=bo(e.split(/\r?\n/)),i=ko(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||Ws(d))continue;let l=i.byLine.get(c);for(let u of Js(d))Us(u,l,a,n);}return [...n]}function bo(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)=>Ls(s)?"":s).trim());}return {headingLines:n,claimLines:o}}function Ls(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 Ws(e){if(e.length>2048)return false;let t=e.replace(/^\s*(?:[-*+]|\d+[.)])\s+/,"").trim();return t?qs(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 qs(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 Us(e,t,n,o){let r=/\bP0\b/gi;for(let f of e.matchAll(r))vo(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))vo(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))Bs(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 m=/(?:requestAnimationFrame|\bRAF\b)/i.test(e),g=/(?:建议|应该|应当|使用|添加|采用|切换|包裹|优化|节流|\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&&g&&!p&&!n&&o.add("raf_without_sampling_evidence");}function vo(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=zs(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 zs(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 Bs(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 Js(e){return e.split(/(?:[。!?;;,,]|\b(?:but|however|yet|nevertheless|nonetheless)\b|但是|但|然而|却|不过|可是)/i).map(t=>t.trim()).filter(Boolean)}function he(e,t,n){if(t>Ps||e===null||e===void 0)return null;if(typeof e=="string"){if(Buffer.byteLength(e,"utf8")>Cs)return null;try{return he(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=he(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=he(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=he(i,t+1,n);if(s)return s}return null}function Gs(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!==ge.length)return null;let o=n.requiredSections.filter(c=>typeof c=="string");if(o.length!==ge.length||ge.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")>Ds||ge.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 bt(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,Ms),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(-Os),l=t.length>0?Math.min(...t.map(p=>p.promptedAt)):0,u=Ks(d,l),g=[...u].reverse().find(p=>Vs(p.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 Vs(e,t){let n=new Set(t.flatMap(r=>r.contract.requiredSections)),o=ko(bo(e.split(/\r?\n/u)).headingLines);return [...n].every(r=>o.found.has(r))}function We(e){return bt(e,[]).answer}function Ks(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=Qs(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(),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")}`,g=createHash("sha256").update(u).digest("hex"),p=createHash("sha256").update(`${m}\0${g}`).digest("hex");n.push({text:u,timestamp:c,fingerprint:p});}}catch{continue}}return n}function Qs(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 ko(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=ge.find(a=>i===a);s&&(o=s,t.add(s)),n.set(r,o);}return {found:t,byLine:n}}function Eo(e){let t;try{if(ta(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=e.toolName==="Read"?Xs(e.toolInput):void 0,r=o?n.selectedFiles?.find(l=>Zs(e.projectRoot,l,o)):void 0,i=ea(e.toolName),s=r?"code":n.canonicalNextAction===i?"action":null,a=r??(s==="action"?i:void 0);if(!s||!a)return null;let c=[n.contextHash,n.requestId??"",s,a,e.toolUseId??`${e.sessionId}:${e.executionId??n.executionId}`].join("\0");t.recordContextSelectionEvent({id:`ctxsel:${createHash("sha256").update(c).digest("hex").slice(0,32)}`,projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n.executionId,requestId:n.requestId,selectionType:s,candidateId:a,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}).find(l=>l.sourceType===s&&l.sourceId===a&&l.stage==="selected");if(d&&t.appendRetrievalLedgerEvent({...d,id:St(d.id,"adopted",e.toolUseId??e.toolName),stage:"adopted",toolEvidence:[e.toolUseId??e.toolName],payload:{...d.payload,adoptedByTool:e.toolName},createdAt:Date.now()}),s==="action"){let l=new Set(n.canonicalAction?.binding.requiredPolicyFacets??[]);if(l.size>0){let u=t.listRetrievalLedgerEvents({projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n.executionId,requestId:n.requestId}).filter(m=>m.sourceType==="memory"&&m.stage==="selected"&&m.applicability.some(g=>g.startsWith("policy:")&&l.has(g.slice(7))));for(let m of u)t.appendRetrievalLedgerEvent({...m,id:St(m.id,"adopted",e.toolUseId??e.toolName),stage:"adopted",toolEvidence:[e.toolUseId??e.toolName],payload:{...m.payload,adoptedByTool:e.toolName,adoptionReason:"required_policy_facet"},createdAt:Date.now()});}}return s}catch{return null}finally{try{t?.close();}catch{}}}function To(e){let t=openGlobalDevFlowDatabase();try{let n=t.listRetrievalLedgerEvents(e),o=new Map(n.filter(c=>c.stage==="selected").map(c=>[So(c),c])),r=new Map(n.filter(c=>c.stage==="adopted").map(c=>[So(c),c])),i=0,s=0,a=0;for(let[c,d]of o){let l=r.get(c),u=l&&e.verificationReceipt&&e.outcome!=="unknown"?e.outcome:"unknown",m=u==="positive"?"positive_outcome":u==="negative"?"negative_outcome":"unknown";t.appendRetrievalLedgerEvent({...d,id:St(d.id,m,e.verificationReceipt??e.sessionId),stage:m,reason:l?e.outcomeReason:"selected_not_adopted",toolEvidence:l?.toolEvidence??[],verificationReceipt:u==="unknown"?void 0:e.verificationReceipt,payload:{...d.payload,adopted:!!l},createdAt:e.finishedAt??Date.now()}),m==="positive_outcome"?i+=1:m==="negative_outcome"?s+=1:a+=1;}return {adopted:r.size,positive:i,negative:s,unknown:a,adoptedSources:[...r.values()].map(c=>({sourceType:c.sourceType,sourceId:c.sourceId}))}}finally{t.close();}}function Xs(e){for(let t of ["file_path","path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n.trim()}}function Zs(e,t,n){let o=resolve(e,t),r=isAbsolute(n)?resolve(n):resolve(e,n);return o===r}function ea(e){return e.startsWith("mcp__")?e.split("__").at(-1)??e:e}function ta(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 St(e,t,n){return `retrieval:${createHash("sha256").update(`${e}\0${t}\0${n}`).digest("hex")}`}function So(e){return [e.requestId,e.contextReceipt,e.sourceType,e.sourceId].join("\0")}var da=8*1024*1024;function Do(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(da,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,m=0,g=0;for(let I of c){let k;try{k=JSON.parse(I);}catch{continue}for(let R of Rt(k,l)){let b=claudeCodeRuntimeAdapter.normalizeToolResult(R,{projectRoot:e.projectRoot});if(b.success||!b.error)continue;let j=b.toolUseId??b.sourceHash;if(u.has(j))continue;u.add(j),m++;let T=b.toolUseId?t.getToolCallEventByToolUseId(e.sessionId,b.toolUseId):null,C=Co(T?.input,"_devflow_turn_id"),F=Co(T?.input,"_devflow_request_id"),S=C?d.find(E=>E.turnId===C):[...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:C??S?.turnId,requestId:F??S?.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:C??S?.turnId,requestId:F??S?.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 p=createHash("sha256").update(s).digest("hex"),f=`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:f,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:g,checkpointId:f}}),{status:"completed",eventsRead:c.length,failuresFound:m,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 Co(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function Rt(e,t,n=0){if(n>7||e===null||e===void 0)return [];if(Array.isArray(e))return e.flatMap(s=>Rt(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:xt(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(...Rt(a,t,n+1));return i}function xt(e){if(typeof e=="string")return e.slice(0,4e3);if(Array.isArray(e))return e.map(xt).filter(Boolean).join(`
13
+ `).slice(0,4e3);if(!e||typeof e!="object")return "";let t=e;return [t.text,t.content,t.message].map(xt).filter(Boolean).join(`
14
+ `).slice(0,4e3)}var Mo={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:["memory_decided","memory_quarantined"],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 Oo(e){let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=t.getLatestTerminalTransition(e.artifact.projectRoot,e.artifact.sessionId,e.artifact.turnId);if(!n)throw new Error(`TERMINAL_INTENT_STATE_MISSING:${e.artifact.turnId}`);let o=e.memoryStatus==="pending"?e.retryOwned?"closed_with_retry_work":"closed_with_degradation":"closed";for(let r of ma(n.toState,o,e.memoryStatus)){let i=n.sequence+1,s=`terminal:${createHash("sha256").update(`${e.artifact.artifactHash}\0${i}\0${r}`).digest("hex").slice(0,24)}`;n=t.appendTerminalTransition({projectRoot:e.artifact.projectRoot,projectId:e.artifact.projectId,hostId:e.artifact.hostId,sessionId:e.artifact.sessionId,turnId:e.artifact.turnId,requestId:e.artifact.requestId,executionId:e.artifact.executionId,sequence:i,fromState:n.toState,toState:r,receiptId:s,sourceReceiptId:e.memoryReceiptId??n.receiptId,reason:pa(r,e),payload:{memoryStatus:e.memoryStatus,retryOwned:e.retryOwned??!1,sourceIntentHash:e.artifact.artifactHash},createdAt:Date.now()}),emitSemanticControlLog({event:"terminal.state.transitioned",identity:{projectRoot:e.artifact.projectRoot,projectId:e.artifact.projectId,hostId:e.artifact.hostId,sessionId:e.artifact.sessionId,turnId:e.artifact.turnId,requestId:e.artifact.requestId,...e.artifact.executionId?{executionId:e.artifact.executionId}:{}},level:r==="closed"?"info":r.includes("degradation")||r.includes("retry")?"warn":"info",timestamp:Date.now(),data:{fromState:n.fromState,nextState:r,receiptId:s,reason:n.reason}});}return n}finally{t.close();}}function ma(e,t,n){if(e===t||Mo[e].length===0)return [];let o=n==="pending"?["context_degraded","action_not_required","action_degraded","memory_quarantined",t]:["context_degraded","action_not_required","action_degraded","memory_decided",t],r=[],i=e;for(let s of o)i!==s&&Mo[i].includes(s)&&(r.push(s),i=s);if(i!==t)throw new Error(`TERMINAL_PATH_UNAVAILABLE:${e}->${t}`);return r}function pa(e,t){return e==="context_degraded"?"terminal_reconciliation_without_context_transition":e==="action_not_required"?"no_outstanding_canonical_action_receipt":e==="memory_decided"?`canonical_memory_${t.memoryStatus}`:e==="memory_quarantined"?t.reason:e==="closed_with_retry_work"?"durable_retry_owner_confirmed":e==="closed_with_degradation"?"terminal_obligation_unowned":t.reason}function Et(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 O(e){return (e instanceof Error?e.message:String(e)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var G=class extends Error{constructor(t,n){super(`session_finalize_${t}:${n}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${t}`;}};function ye(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 qe(e,t=Ee(),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),m={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:m.status==="completed"?"info":"debug",timestamp:Date.now(),data:{stage:"enqueue",...m}}),m}catch(l){if(!r)throw l;return mo(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:O(l),fallback:"durable_spool"}}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{d?.close();}}async function jo(e,t=Ee(),n=true,o){let r;try{r=JSON.parse(e);}catch{return}let i=r.session_id?.trim();if(!i)return;let s=new H(t),a=s.get(i),c=Do({projectRoot:t,sessionId:i,transcriptPath:r.transcript_path}),d={evidenceDegradations:a?.evidenceDegradations??[],evidenceContractOutcomes:a?.evidenceOutcomes??[],pendingEvidenceContractIds:a?.evidenceObligations.map(p=>p.contractId)??[],transcriptReconciliation:c},l=o?.telemetry??new X,u=!o?.telemetry,m=false,g;try{try{await l.flushAndAggregate();}catch{}let p=Date.now(),f=o?.executionId??a?.executionId,I;try{let y=openGlobalDevFlowDatabase();try{I=y.listSessionMemoryTurnsForReconciliation(t,i);for(let h of I){let w=`memory:${h.turnId}`,v=y.getSessionObligation(t,i,w);v?v.state==="open"&&h.status!=="pending"&&y.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:w,state:"satisfied",receiptId:h.receiptId,reason:h.reason,resolvedAt:h.decidedAt}):y.upsertSessionObligation({obligationId:w,projectRoot:t,sessionId:i,turnId:h.turnId,kind:"memory_decision",state:h.status==="pending"?"open":"satisfied",payload:{eventId:h.eventId,promptHash:h.promptHash},receiptId:h.receiptId,reason:h.reason,createdAt:h.createdAt,updatedAt:h.decidedAt??h.createdAt,resolvedAt:h.decidedAt});}}finally{y.close();}}catch(y){let h=O(y),w={...d,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:h,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ye({projectRoot:t,sessionId:i,executionId:f,stage:"turn_load",reason:h,metadata:w}),new G("turn_load",h)}let k=Et(I),R=o?.memory??(g=new MemoryGate(t)),b={status:"completed"};try{b=typeof R.reconcileTurnObservationLineage=="function"?{status:"completed",...await R.reconcileTurnObservationLineage(I)}:{status:"unsupported_adapter",committed:0,skipped:0,quarantined:0,unlinked:0};}catch(y){let h=O(y);throw b={status:"degraded",reason:h},ye({projectRoot:t,sessionId:i,executionId:f,stage:"memory_lineage",reason:h,metadata:{...k,...d,memoryLineageReconciliation:b}}),new G("memory_lineage",h)}let j={status:"unknown",selected:0,adopted:0,unknown:0,positive:0,negative:0};try{let y=We(r.transcript_path),h=openGlobalDevFlowDatabase(),w="unknown",v="no_terminal_host_action_evidence",ce,W,$,q=[];try{let U=h.listHostActionsForSession(t,i,f),yn=U.filter(P=>P.state==="verified"),at=U.filter(P=>["failed","cancelled","degraded"].includes(P.state));at.length>0?(w="negative",v=`terminal_host_action_${at[0].state}`):yn.length>0&&(w="positive",v="host_action_verified");let Re=at[0]??yn.at(-1);if(ce=Re?.runId,W=Re?.contextReceipt,$=Re?.evidenceHash,q=U.flatMap(P=>{let K=P.report.toolUseIds;return Array.isArray(K)?K.filter(de=>typeof de=="string"):[]}),!Re&&f){let P=h.getSkillExecution(f),K=P?.metadata&&typeof P.metadata=="object"&&Array.isArray(P.metadata.policyVerificationOutcomes)?P.metadata.policyVerificationOutcomes:[],de=K.find(z=>z.status==="failed"),ct=K.filter(z=>z.status==="passed");de?(w="negative",v="policy_verification_failed",$=typeof de.receiptId=="string"?de.receiptId:void 0):ct.length>0&&(w="positive",v="policy_verification_passed",$=typeof ct.at(-1)?.receiptId=="string"?String(ct.at(-1).receiptId):void 0),W=h.getActiveContextReceipt(t,i,f)?.contextHash,q=K.map(z=>z.command).filter(z=>typeof z=="string");}}finally{h.close();}let hn=To({projectRoot:t,sessionId:i,executionId:f,outcome:w,outcomeReason:v,verificationReceipt:$,finishedAt:p}),oi=await R.attributeRetrievalBenefits({sessionId:i,executionId:f,finalAnswer:y,outcome:w,outcomeReason:v,workflowRunId:ce,contextReceipt:W,toolEvidence:q,verificationReceipt:$,adoptedSourceIds:hn.adoptedSources.filter(U=>U.sourceType==="memory").map(U=>U.sourceId)});j={status:y?"evaluated":"unknown",...oi,retrievalLedger:hn};}catch(y){j={...j,status:"degraded",reason:O(y)};}let T;try{T=await R.reconcileDecidedTurnEventWindows(i,I,p);}catch(y){let h=O(y),w={...k,...d,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:h,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ye({projectRoot:t,sessionId:i,executionId:f,stage:"event_reconciliation",reason:h,metadata:w}),new G("event_reconciliation",h)}let C;try{C=await fe({projectRoot:t,sessionId:i,trigger:"session_end",memory:R,details:{eventReconciliation:T},strictPersistence:!0});}catch(y){let h=O(y),w={...k,...d,memoryEventReconciliation:{status:"completed",...T,checkpointPending:null},memoryCheckpointDegradation:h};throw ye({projectRoot:t,sessionId:i,executionId:f,stage:"checkpoint",reason:h,metadata:w}),new G("checkpoint",h)}let F={memoryLineageReconciliation:b,memoryBenefitAttribution:j,memoryEventReconciliation:{status:"completed",...T,checkpointPending:C.pendingEvents},memoryDistillCheckpoint:C};try{let y=openGlobalDevFlowDatabase();try{let h=`session-finalize:${i}:events`,w=Math.max(Number(C.pendingEvents??0),Number(T.remainingUndecided??0)),v=y.getSessionObligation(t,i,h);w>0?y.upsertSessionObligation({obligationId:h,projectRoot:t,sessionId:i,executionId:f,kind:"session_finalize",state:"open",payload:{pendingEvents:w,reconciliation:T,checkpointId:C.id},reason:"active_unprocessed_session_events",createdAt:v?.createdAt??p,updatedAt:p}):v?.state==="open"&&y.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:h,state:"satisfied",reason:"session_events_reconciled",resolvedAt:p});}finally{y.close();}}catch(y){emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:f},level:"warn",timestamp:Date.now(),data:{stage:"obligation_persistence",reason:O(y)}});}try{await R.closeSession(i),g&&(g.close(),g=void 0);}catch(y){let h=O(y),w={...k,...d,...F,memorySessionCloseDegradation:h};throw ye({projectRoot:t,sessionId:i,executionId:f,stage:"memory_close",reason:h,metadata:w}),new G("memory_close",h)}let S={...k,...d,...F},A=[];try{let y=openGlobalDevFlowDatabase();try{let h=new Map(y.listLatestTaskIntentArtifacts(t,i).map(w=>[w.turnId,w]));for(let w of I){let v=h.get(w.turnId);if(!v)continue;let W=[y.getWorkByIdempotencyKey(`memory-turn:capture_prompt:${w.turnId}`),y.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${w.turnId}`)].filter(Boolean).some(q=>q.state==="pending"||q.state==="leased"||q.state==="failed"),$=Oo({artifact:v,memoryStatus:w.status,memoryReceiptId:w.receiptId,retryOwned:W,reason:w.status==="pending"?"session_end_memory_pending":"session_end_reconciled"});A.push({turnId:w.turnId,state:$.toState,receiptId:$.receiptId});}}finally{y.close();}}catch(y){A.push({state:"terminal_integrity_failure",reason:O(y)});}S.terminalOutcomes=A,m=!0;let E;try{E=openGlobalDevFlowDatabase();let y=f;if(y)try{E.reconcileSkillExecution(y,"completed",p,S);let v=E.getSkillExecution(y);await B("/api/telemetry/skill-execution/complete",{executionId:y,finishedAt:p,status:"completed",summary:{totalToolCalls:v?.totalToolCalls??0,mcpToolCalls:v?.mcpToolCalls??0,directToolCalls:v?.directToolCalls??0,subagentCount:v?.subagentCount??0,totalDuration:v?.totalDuration??0,mcpComplianceRate:v?.mcpComplianceRate??0,missedTools:v?.missedMcpTools??[],actualFailureCount:v?.failedToolCalls??0,fallbackCount:v?.fallbackCount??0,fallbackReasons:v?.fallbackReasons??[]},metadata:S},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let h=E.reconcileRunningSkillExecutionsForSession(i,p,{closureReason:"session_finalize",...S});for(let v of h)await B("/api/telemetry/skill-execution/complete",{executionId:v.executionId,finishedAt:v.finishedAt,status:v.status,summary:{totalToolCalls:v.totalToolCalls??0,mcpToolCalls:v.mcpToolCalls??0,directToolCalls:v.directToolCalls??0,subagentCount:v.subagentCount??0,totalDuration:v.totalDuration??0,mcpComplianceRate:v.mcpComplianceRate??0,missedTools:v.missedMcpTools??[],actualFailureCount:v.failedToolCalls??0,fallbackCount:v.fallbackCount??0,fallbackReasons:v.fallbackReasons??[]},metadata:S},{fallbackReason:"skill_execution_already_reconciled_locally"});let w=E.getLatestSkillExecutionForSession(i);if(w&&!h.some(v=>v.executionId===w.executionId)&&E.mergeSkillExecutionMetadata(w.executionId,S),n){E.deleteHookReceipt(t);let v=D(t),ce=createHash("sha256").update(t).digest("hex").slice(0,12);for(let W of [`session-id-${ce}`,"current-execution-id","current-skill.json","event-map.json"])rmSync$1(join(v,W),{force:!0});}E.deleteContextReceipt(t,i);}catch(y){emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:f},level:"warn",timestamp:Date.now(),data:{stage:"lifecycle_telemetry",reason:O(y),fallback:"fail_open"}});}finally{E?.close();}try{await l.endSession(i),await l.flushAndAggregate();}catch(y){emitSemanticControlLog({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:f},level:"warn",timestamp:Date.now(),data:{stage:"telemetry_flush",reason:O(y),fallback:"local_state_authoritative"}});}}finally{if(g)try{g.close();}catch{}u&&l.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=qe(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 ka=/^\/(?:devflow:)?[\w-]+\b\s*/iu,Sa=/\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,Ra=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,xa=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function Ue(e){let t=e.trim().replace(ka,"").trim();return !t||Sa.test(t)?null:(xa.exec(t)??Ra.exec(t))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}function Ea(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 Ta(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 No(e){let t=Ea(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=Ta(i);if(s.length===0){try{unlinkSync$1(i);}catch{}return null}return {path:i,intents:s}}function At(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
16
  `)+`
15
- `,{mode:384}),renameSync(e,n.path);}function Pe(n){let e=n.trim().replace(/^\//,"");if(!e.startsWith("devflow:"))return null;let t=e.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(t)?`devflow:${t.toLowerCase()}`:null}function So(n){let e=n.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!e)return null;let t=Pe(e[1]);return t?{rawName:e[1],skillName:t}:null}function pe(n,e){return e?`evt_tool_${createHash$1("sha256").update(`${n}\0${e}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var fe=1,St="memory-snapshot-v1.json",jo=512*1024,Fo=256*1024,$o=2e3,oa=500,ra=10,ia=240,sa=300*1e3,aa=720*60*60*1e3,Ho=2147483647,ca=100,xo=250,la=3e4,da=10,je=new Map;function No(n){return n.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:n.ownerUid===n.currentUid,modeSafe:(n.mode&18)===0}}function H(n){return resolve(n)}function Y(n){return createHash("sha256").update(H(n)).digest("hex").slice(0,16)}function It(n,e={}){let t=Y(n),o=e.stateRoot?join(e.stateRoot,t):getProjectStateDir(H(n));return join(o,St)}function $e(n,e){let o=(n instanceof Error?n.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return o?`${e}:${o}`:e}function Rt(n,e){return Array.isArray(n)&&n.length<=e&&n.every(t=>typeof t=="string"&&t.length>0&&t.length<=512)}function ua(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let e=n;return typeof e.id=="string"&&e.id.length>0&&e.id.length<=512&&typeof e.kind=="string"&&e.kind.length>0&&e.kind.length<=128&&(e.family===void 0||typeof e.family=="string"&&e.family.length>0&&e.family.length<=256)&&(e.entity===void 0||typeof e.entity=="string"&&e.entity.length>0&&e.entity.length<=256)&&Rt(e.memoryIds,100)&&(e.status==="withheld"||e.status==="resolved")&&(e.summary===void 0||typeof e.summary=="string"&&e.summary.length<=2e3)}function pa(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let e=n;return typeof e.reason=="string"&&e.reason.length>0&&e.reason.length<=512&&(e.stale===void 0||typeof e.stale=="boolean")}function Et(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))return null;let o=n,r=H(e),i=Y(r),s=o.generation===void 0?0:o.generation;return o.version!==fe||o.projectRoot!==r||o.projectHash!==i||typeof o.markdown!="string"||Buffer.byteLength(o.markdown,"utf8")>Fo||!Rt(o.memoryIds,$o)||!Array.isArray(o.conflicts)||o.conflicts.length>oa||!o.conflicts.every(ua)||typeof o.generatedAt!="number"||!Number.isFinite(o.generatedAt)||o.generatedAt<0||o.generatedAt>t+sa||!Number.isInteger(s)||s<0||s>Ho||!["ready","pending","degraded","disabled"].includes(String(o.status))||o.degradation!==void 0&&!pa(o.degradation)?null:{...o,generation:s}}function xt(n,e,t,o,r=0){let i=H(n);return {version:fe,projectRoot:i,projectHash:Y(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:o,generation:r,status:e,degradation:{reason:t}}}function V(n,e={}){let t=e.now??Date.now(),o=It(n,e),r;try{r=openSync$1(o,constants.O_RDONLY|constants.O_NOFOLLOW);let i=fstatSync$1(r);if(!i.isFile()||i.size<=0||i.size>jo)throw new Error("cache_size_invalid");let s=No({...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=Et(a,n,t);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&t-c.generatedAt>aa?{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:xt(n,a?"pending":"degraded",a?"cache_missing":$e(i,"cache_invalid"),t),source:"none",valid:false,stale:false}}finally{if(r!==void 0)try{closeSync$1(r);}catch{}}}function To(n){if(!Number.isInteger(n)||n<0||n>=Ho)throw new Error("memory_snapshot_generation_exhausted");return n+1}function ma(n){let e=dirname$1(n);mkdirSync$1(e,{recursive:true,mode:448}),chmodSync(e,448);}function fa(n){ma(n);let e=`${n}.lock`,t={pid:process.pid,createdAt:Date.now(),token:randomUUID$1()},o=JSON.stringify(t),r;try{return r=openSync$1(e,"wx",384),writeFileSync$1(r,o),fsyncSync(r),{fd:r,path:e,contents:o}}catch(i){if(r!==void 0){try{closeSync$1(r);}catch{}try{unlinkSync$1(e);}catch{}}if(i.code==="EEXIST")return null;throw i}}function ga(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let e=n;return Number.isInteger(e.pid)&&Number(e.pid)>0&&typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)&&typeof e.token=="string"&&e.token.length>0}function ha(n){try{return process.kill(n,0),!1}catch(e){return e.code==="ESRCH"}}function ya(n){return !n.canonicalCachePath||!n.directoryIsSafe||!n.lockIsRegularFile||!n.metadataValid||!n.contentsUnchanged||!n.ownerDead&&!n.stale?false:n.currentUid!==void 0?n.directoryUid===n.currentUid&&n.lockUid===n.currentUid:true}function va(n){return isAbsolute(n)&&resolve(n)===n&&basename(n)===St&&/^[a-f0-9]{16}$/u.test(basename(dirname$1(n)))}function wa(n,e){let t=`${n}.lock`;try{let o=lstatSync$1(dirname$1(n)),r=lstatSync$1(t),i=readFileSync$1(t,"utf8"),s=null;try{let f=JSON.parse(i);ga(f)&&(s=f);}catch{}let a=s?.createdAt??r.mtimeMs,c=Date.now()-a>e,l=s?ha(s.pid):!1,d=readFileSync$1(t,"utf8")===i,u=typeof process.getuid=="function"?process.getuid():void 0,p=No({...u!==void 0?{currentUid:u}:{},ownerUid:o.uid,mode:o.mode});return ya({canonicalCachePath:va(n),directoryIsSafe:o.isDirectory()&&!o.isSymbolicLink()&&p.modeSafe,lockIsRegularFile:r.isFile()&&!r.isSymbolicLink(),metadataValid:s!==null,ownerDead:l,stale:c,contentsUnchanged:d,...u!==void 0?{currentUid:u}:{},directoryUid:o.uid,lockUid:r.uid})?(unlinkSync$1(t),!0):!1}catch{return false}}function ba(n){try{closeSync$1(n.fd);}catch{}try{readFileSync$1(n.path,"utf8")===n.contents&&unlinkSync$1(n.path);}catch{}}function _a(n){return new Promise(e=>setTimeout(e,n))}function yt(n,e,t,o){let r=Number.isFinite(n)?Math.floor(n):e;return Math.min(o,Math.max(t,r))}async function ka(n,e){let t=yt(e.lockTimeoutMs,ca,0,xo),o=yt(e.lockRetryMs,da,1,xo),r=yt(e.lockStaleMs,la,0,Number.MAX_SAFE_INTEGER),i=Date.now()+t;for(;;){let s=fa(n);if(s)return s;if(wa(n,r))continue;let a=i-Date.now();if(a<=0)throw new Error("memory_snapshot_cache_lock_timeout");await _a(Math.min(o,a));}}async function Co(n,e,t){let o=await ka(n,e);try{return await t()}finally{ba(o);}}function Do(n,e,t,o){let r=o.now??Date.now(),i=H(n),s={version:fe,projectRoot:i,projectHash:Y(i),markdown:e.markdown,memoryIds:e.memoryIds??[],conflicts:e.conflicts??[],generatedAt:r,generation:t,status:e.status??"ready",...e.degradation?{degradation:e.degradation}:{}};if(!Et(s,n,r))throw new Error("memory_snapshot_payload_invalid");let a=JSON.stringify(s);if(Buffer.byteLength(a,"utf8")>jo)throw new Error("memory_snapshot_cache_too_large");let c=It(n,o),l=dirname$1(c);mkdirSync$1(l,{recursive:true,mode:448}),chmodSync(l,448);let d=join(l,`.${St}.${process.pid}.${randomUUID$1()}.tmp`),u;try{u=openSync$1(d,"wx",384),writeFileSync$1(u,a),fsyncSync(u),closeSync$1(u),u=void 0,chmodSync(d,384),renameSync(d,c),chmodSync(c,384);let p;try{p=openSync$1(l,"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(d,{force:true});}}function Sa(n,e){let o=(je.get(n)??Promise.resolve()).catch(()=>{}).then(e),r=o.then(()=>{},()=>{});return je.set(n,r),o.finally(()=>{je.get(n)===r&&je.delete(n);})}function vt(n,e,t,o,r){return n.valid?n.snapshot.generation>r?{...n,persisted:false}:{...n,snapshot:{...n.snapshot,status:"degraded",degradation:{reason:t,stale:n.stale||void 0}},persisted:false}:{snapshot:xt(e,"degraded",t,o,r),source:"none",valid:false,stale:false,persisted:false}}async function Tt(n){let e=It(n.projectRoot,n.cacheOptions);return Sa(e,async()=>{let t=V(n.projectRoot,n.cacheOptions),o=t.valid?t.snapshot.generation:0,r;try{r=await n.load();}catch(i){let s=$e(i,`refresh_failed:${n.reason}`);try{return await Co(e,n.cacheOptions??{},()=>{let a=V(n.projectRoot,n.cacheOptions);if(a.valid)return vt(a,n.projectRoot,s,n.cacheOptions?.now??Date.now(),o);let c=To(o),l=xt(n.projectRoot,"degraded",s,n.cacheOptions?.now??Date.now(),c);return {snapshot:Do(n.projectRoot,l,c,n.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(a){let c=V(n.projectRoot,n.cacheOptions);return vt(c,n.projectRoot,$e(a,s),n.cacheOptions?.now??Date.now(),o)}}try{return await Co(e,n.cacheOptions??{},()=>{let i=V(n.projectRoot,n.cacheOptions);if(i.valid&&i.snapshot.generation>o)return {...i,persisted:!1};let s=To(Math.max(o,i.valid?i.snapshot.generation:0));return {snapshot:Do(n.projectRoot,r,s,n.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(i){let s=V(n.projectRoot,n.cacheOptions);return vt(s,n.projectRoot,$e(i,`refresh_commit_failed:${n.reason}`),n.cacheOptions?.now??Date.now(),o)}})}async function Le(n){return Tt({projectRoot:n.projectRoot,reason:n.reason,cacheOptions:n.cacheOptions,load:async()=>{if(n.injectConfig===false)return {status:"disabled",markdown:"",memoryIds:[],conflicts:[]};let e=typeof n.injectConfig=="object"?n.injectConfig:{},t=Number.isFinite(e.topN)?Math.max(0,Math.floor(e.topN)):10,o=Number.isFinite(e.budgetTokens)?Math.max(1,Math.floor(e.budgetTokens)):800,r=await n.memory.getAll({purpose:"session_bootstrap",budgetTokens:o,limit:t}),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",l=(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}:{}})),d=a?`## Project memory
16
- 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&&l.length>0?`## Project memory
17
- ${l.length} explicit preference conflict(s) are withheld from automatic guidance; an explicit choice is required.`:r.memories.length===0?`## Project memory
17
+ `,{mode:384}),renameSync(t,e.path);}function ze(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 Lo(e){let t=e.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!t)return null;let n=ze(t[1]);return n?{rawName:t[1],skillName:n}:null}function ve(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 we=1,Ft="memory-snapshot-v1.json",Xo=512*1024,Zo=256*1024,er=2e3,Fa=500,$a=10,Ha=240,Na=300*1e3,La=720*60*60*1e3,tr=2147483647,Wa=100,zo=250,qa=3e4,Ua=10,Be=new Map;function nr(e){return e.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:e.ownerUid===e.currentUid,modeSafe:(e.mode&18)===0}}function V(e){return resolve(e)}function oe(e){return createHash("sha256").update(V(e)).digest("hex").slice(0,16)}function $t(e,t={}){let n=oe(e),o=t.stateRoot?join(t.stateRoot,n):getProjectStateDir(V(e));return join(o,Ft)}function Ge(e,t){let o=(e instanceof Error?e.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return o?`${t}:${o}`:t}function Ht(e,t){return Array.isArray(e)&&e.length<=t&&e.every(n=>typeof n=="string"&&n.length>0&&n.length<=512)}function za(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)&&Ht(t.memoryIds,100)&&(t.status==="withheld"||t.status==="resolved")&&(t.summary===void 0||typeof t.summary=="string"&&t.summary.length<=2e3)}function Ba(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 Nt(e,t,n){if(!e||typeof e!="object"||Array.isArray(e))return null;let o=e,r=V(t),i=oe(r),s=o.generation===void 0?0:o.generation;return o.version!==we||o.projectRoot!==r||o.projectHash!==i||typeof o.markdown!="string"||Buffer.byteLength(o.markdown,"utf8")>Zo||!Ht(o.memoryIds,er)||!Array.isArray(o.conflicts)||o.conflicts.length>Fa||!o.conflicts.every(za)||typeof o.generatedAt!="number"||!Number.isFinite(o.generatedAt)||o.generatedAt<0||o.generatedAt>n+Na||!Number.isInteger(s)||s<0||s>tr||!["ready","pending","degraded","disabled"].includes(String(o.status))||o.degradation!==void 0&&!Ba(o.degradation)?null:{...o,generation:s}}function Lt(e,t,n,o,r=0){let i=V(e);return {version:we,projectRoot:i,projectHash:oe(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:o,generation:r,status:t,degradation:{reason:n}}}function te(e,t={}){let n=t.now??Date.now(),o=$t(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>Xo)throw new Error("cache_size_invalid");let s=nr({...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=Nt(a,e,n);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&n-c.generatedAt>La?{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:Lt(e,a?"pending":"degraded",a?"cache_missing":Ge(i,"cache_invalid"),n),source:"none",valid:false,stale:false}}finally{if(r!==void 0)try{closeSync$1(r);}catch{}}}function Bo(e){if(!Number.isInteger(e)||e<0||e>=tr)throw new Error("memory_snapshot_generation_exhausted");return e+1}function Ja(e){let t=dirname$1(e);mkdirSync$1(t,{recursive:true,mode:448}),chmodSync(t,448);}function Ga(e){Ja(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 Va(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 Ka(e){try{return process.kill(e,0),!1}catch(t){return t.code==="ESRCH"}}function Qa(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 Ya(e){return isAbsolute(e)&&resolve(e)===e&&basename(e)===Ft&&/^[a-f0-9]{16}$/u.test(basename(dirname$1(e)))}function Xa(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);Va(g)&&(s=g);}catch{}let a=s?.createdAt??r.mtimeMs,c=Date.now()-a>t,d=s?Ka(s.pid):!1,l=readFileSync$1(n,"utf8")===i,u=typeof process.getuid=="function"?process.getuid():void 0,m=nr({...u!==void 0?{currentUid:u}:{},ownerUid:o.uid,mode:o.mode});return Qa({canonicalCachePath:Ya(e),directoryIsSafe:o.isDirectory()&&!o.isSymbolicLink()&&m.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 Za(e){try{closeSync$1(e.fd);}catch{}try{readFileSync$1(e.path,"utf8")===e.contents&&unlinkSync$1(e.path);}catch{}}function ec(e){return new Promise(t=>setTimeout(t,e))}function Ct(e,t,n,o){let r=Number.isFinite(e)?Math.floor(e):t;return Math.min(o,Math.max(n,r))}async function tc(e,t){let n=Ct(t.lockTimeoutMs,Wa,0,zo),o=Ct(t.lockRetryMs,Ua,1,zo),r=Ct(t.lockStaleMs,qa,0,Number.MAX_SAFE_INTEGER),i=Date.now()+n;for(;;){let s=Ga(e);if(s)return s;if(Xa(e,r))continue;let a=i-Date.now();if(a<=0)throw new Error("memory_snapshot_cache_lock_timeout");await ec(Math.min(o,a));}}async function Jo(e,t,n){let o=await tc(e,t);try{return await n()}finally{Za(o);}}function Go(e,t,n,o){let r=o.now??Date.now(),i=V(e),s={version:we,projectRoot:i,projectHash:oe(i),markdown:t.markdown,memoryIds:t.memoryIds??[],conflicts:t.conflicts??[],generatedAt:r,generation:n,status:t.status??"ready",...t.degradation?{degradation:t.degradation}:{}};if(!Nt(s,e,r))throw new Error("memory_snapshot_payload_invalid");let a=JSON.stringify(s);if(Buffer.byteLength(a,"utf8")>Xo)throw new Error("memory_snapshot_cache_too_large");let c=$t(e,o),d=dirname$1(c);mkdirSync$1(d,{recursive:true,mode:448}),chmodSync(d,448);let l=join(d,`.${Ft}.${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 m;try{m=openSync$1(d,"r");try{fsyncSync(m);}catch{}}finally{m!==void 0&&closeSync$1(m);}return s}finally{if(u!==void 0)try{closeSync$1(u);}catch{}rmSync$1(l,{force:true});}}function nc(e,t){let o=(Be.get(e)??Promise.resolve()).catch(()=>{}).then(t),r=o.then(()=>{},()=>{});return Be.set(e,r),o.finally(()=>{Be.get(e)===r&&Be.delete(e);})}function Dt(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:Lt(t,"degraded",n,o,r),source:"none",valid:false,stale:false,persisted:false}}async function Wt(e){let t=$t(e.projectRoot,e.cacheOptions);return nc(t,async()=>{let n=te(e.projectRoot,e.cacheOptions),o=n.valid?n.snapshot.generation:0,r;try{r=await e.load();}catch(i){let s=Ge(i,`refresh_failed:${e.reason}`);try{return await Jo(t,e.cacheOptions??{},()=>{let a=te(e.projectRoot,e.cacheOptions);if(a.valid)return Dt(a,e.projectRoot,s,e.cacheOptions?.now??Date.now(),o);let c=Bo(o),d=Lt(e.projectRoot,"degraded",s,e.cacheOptions?.now??Date.now(),c);return {snapshot:Go(e.projectRoot,d,c,e.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(a){let c=te(e.projectRoot,e.cacheOptions);return Dt(c,e.projectRoot,Ge(a,s),e.cacheOptions?.now??Date.now(),o)}}try{return await Jo(t,e.cacheOptions??{},()=>{let i=te(e.projectRoot,e.cacheOptions);if(i.valid&&i.snapshot.generation>o)return {...i,persisted:!1};let s=Bo(Math.max(o,i.valid?i.snapshot.generation:0));return {snapshot:Go(e.projectRoot,r,s,e.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(i){let s=te(e.projectRoot,e.cacheOptions);return Dt(s,e.projectRoot,Ge(i,`refresh_commit_failed:${e.reason}`),e.cacheOptions?.now??Date.now(),o)}})}async function Qe(e){return Wt({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
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
+ ${d.length} explicit preference conflict(s) are withheld from automatic guidance; an explicit choice is required.`:r.memories.length===0?`## Project memory
18
20
  \u672C\u9879\u76EE\u6682\u65E0\u8BB0\u5FC6`:`## Project memory (auto-injected, ${r.memories.length} items, ${r.tokenCount} tokens)
19
21
  ${r.memories.map(u=>`- **${u.title||u.type}**: ${u.content} (confidence ${u.confidence.toFixed(2)}, ${u.source})`).join(`
20
- `)}`;return {status:a?"degraded":"ready",markdown:d,memoryIds:r.memories.map(u=>u.id),conflicts:l,...a?{degradation:{reason:c}}:{}}}})}function Ia(n){if(!n)return true;try{return JSON.parse(readFileSync$1(n,"utf8")).sessionStart?.injectMemories??!0}catch{return true}}function Ra(n,e,t){if(!e.trim())return null;try{let o=JSON.parse(e);if(o.status!=="ok"&&o.status!=="degraded")return null;if(o.enabled===!1){let i=H(n);return {version:fe,projectRoot:i,projectHash:Y(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:t,generation:0,status:"disabled"}}let r=Et(o.snapshot,n,t);if(r)return r;if(o.status==="ok"&&typeof o.markdown=="string"&&o.markdown.length>0&&Buffer.byteLength(o.markdown,"utf8")<=Fo){let i=H(n);return {version:fe,projectRoot:i,projectHash:Y(i),markdown:o.markdown,memoryIds:Rt(o.memoryIds,$o)?o.memoryIds:[],conflicts:[],generatedAt:t,generation:0,status:"ready"}}}catch{}return null}function wt(n,e){return [...(n??e).replace(/[\r\n\t|]+/gu," ").trim()||e].slice(0,ia).join("")}function Ea(n){if(n.length===0)return "";let e=n.slice(0,ra),t=e.map(o=>{let r=wt(o.family,"unknown"),i=wt(o.entity,"unknown"),s=wt(o.summary,"Explicit choice required.");return `- family=${r}; entity=${i}; status=${o.status}; summary=${s}`});return n.length>e.length&&t.push(`- ${n.length-e.length} additional conflict(s) omitted from SessionStart output.`),`## Withheld preference conflicts (${n.length})
21
- ${t.join(`
22
- `)}`}function xa(n){let e=n.now??Date.now();if(Ia(n.configPath)===false)return "";let t=Ra(n.projectRoot,n.daemonResponse??"",e),o=t?{snapshot:t,source:"daemon"}:V(n.projectRoot,{...n.cacheOptions,now:e}),{snapshot:r}=o;if(r.status==="disabled")return `## Project memory
23
- 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=Ea(r.conflicts);return r.markdown?[r.markdown,c,a].filter(Boolean).join(`
22
+ `)}`;return {status:a?"degraded":"ready",markdown:l,memoryIds:r.memories.map(u=>u.id),conflicts:d,...a?{degradation:{reason:c}}:{}}}})}function oc(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=V(e);return {version:we,projectRoot:i,projectHash:oe(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"disabled"}}let r=Nt(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")<=Zo){let i=V(e);return {version:we,projectRoot:i,projectHash:oe(i),markdown:o.markdown,memoryIds:Ht(o.memoryIds,er)?o.memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"ready"}}}catch{}return null}function Mt(e,t){return [...(e??t).replace(/[\r\n\t|]+/gu," ").trim()||t].slice(0,Ha).join("")}function ic(e){if(e.length===0)return "";let t=e.slice(0,$a),n=t.map(o=>{let r=Mt(o.family,"unknown"),i=Mt(o.entity,"unknown"),s=Mt(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
+ ${n.join(`
24
+ `)}`}function sc(e){let t=e.now??Date.now();if(oc(e.configPath)===false)return "";let n=rc(e.projectRoot,e.daemonResponse??"",t),o=n?{snapshot:n,source:"daemon"}:te(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=ic(r.conflicts);return r.markdown?[r.markdown,c,a].filter(Boolean).join(`
24
26
  `):["## Project memory",c,`${a} Memory availability is not yet known; do not conclude that the project has no memories.`].filter(Boolean).join(`
25
- `)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,n,e,t]=process.argv;n!=="session-start"||!e?process.exitCode=2:process.stdout.write(xa({projectRoot:e,configPath:t,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var Ca=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu;function Da(n){let e=n.trim();return e.length>0&&!Ca.test(e)}function Ma(n,e,t=Date.now()){let o=createHash("sha256").update(e.trim()).digest("hex"),r=createHash("sha256").update(`${n}\0${t}\0${o}`).digest("hex").slice(0,24);return {turnId:`turn:${r}`,eventId:`memory-turn:${r}`,promptHash:o,createdAt:t}}function Dt(n,e,t=[]){return `memory-receipt:${createHash("sha256").update(`${n}\0${e}\0${[...t].sort().join("\0")}`).digest("hex").slice(0,24)}`}function qe(n){return `DevFlow memory decision required for ${n.turnId}. Before the final response, semantically decide whether this turn contains durable project knowledge. Call mcp__devflow__memory_commit_turn with evidence-bound candidates, or mcp__devflow__memory_skip_turn with a concrete reason. Do not claim memory success without a canonical receipt. For candidates, preserve exact package names, flags, versions, paths, and identifiers; provide subject, predicate, value, polarity, and entities when known. Do not save assistant echoes, task narration, retries, or unverified guesses. Express a change from an old choice as the new durable value. If the decision tool remains unavailable, explicitly state that the memory was not saved.`}function Ct(n){let e=n.memoryIds.length>0?n.memoryIds.join(","):"none",t=n.status==="committed"?"accepted":n.status,o=n.status==="committed"?"; indexStatus=pending":"",r=n.status==="committed"&&n.source==="explicit_intent"?"; memoryOnlyCompleted=true; skipProjectContext=true; skipMemoryTool=true":"",i=n.status==="committed"&&n.source==="explicit_intent"?" This explicit-memory request is complete. Return the canonical receipt to the user. Do not call a memory tool, project-context tool, domain tool, or native memory write for this request.":"";return `DevFlow canonical memory receipt: status=${t}; receiptId=${n.receiptId??"missing"}; turnId=${n.turnId}; memoryIds=${e}; source=${n.source??"unknown"}${o}${r}.`+i}function Mt(n){if(!Da(n.prompt))return null;let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let t=n.prompt.trim().slice(0,4e3),o=createHash("sha256").update(t).digest("hex"),r=e.listMemoryTurns(n.projectRoot,n.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}:Ma(n.sessionId,t),s=r??e.beginMemoryTurn({...i,projectRoot:n.projectRoot,sessionId:n.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:Ct(s),skipSkillRouting:s.source==="explicit_intent"};let a=Oe(t)??void 0,c=a?"commit_explicit":"capture_prompt";return e.enqueueWork({idempotencyKey:`memory-turn:${c}:${s.turnId}`,kind:a?"memory.explicit_commit":"memory.turn_capture",projectRoot:n.projectRoot,sessionId:n.sessionId,turnId:s.turnId,payload:{operation:c,turnId:s.turnId,eventId:s.eventId,sessionId:n.sessionId,prompt:t,explicitContent:a,createdAt:s.createdAt}}),{turn:s,explicitContent:a,additionalContext:a?`DevFlow explicit memory is durably queued for ${s.turnId}, but no canonical receipt exists yet. Do not claim that it was remembered.`:qe(s),skipSkillRouting:!!a}}finally{e.close();}}async function At(n){let{payload:e,memory:t,projectRoot:o}=n,r=openGlobalDevFlowDatabase();try{let i=r.getMemoryTurn(e.turnId);if(!i)throw new Error(`Memory turn ${e.turnId} does not exist`);if(i.status!=="pending"){if(i.receiptId&&typeof t.reconcileTurnObservationLineage=="function")try{await t.reconcileTurnObservationLineage([i]);}catch{}return {turn:i,additionalContext:Ct(i),skipSkillRouting:i.source==="explicit_intent"}}if(await t.recordUserMessage(e.prompt,e.sessionId,e.prompt.slice(0,200)),await t.recordEvent({id:e.eventId,sessionId:e.sessionId,tool:"UserPromptSubmit",kind:"user_message",payload:{prompt:e.prompt,turnId:e.turnId},createdAt:e.createdAt}),e.operation==="capture_prompt"||!e.explicitContent)return {turn:i,additionalContext:qe(i),skipSkillRouting:!1};let s=await t.saveExplicitMemoryIntent(e.explicitContent,e.sessionId,e.eventId),a=Dt(i.turnId,"committed",[s.id]),c=r.commitMemoryTurn({turnId:i.turnId,receiptId:a,memoryIds:[s.id],source:"explicit_intent",reason:"explicit_user_request"});try{typeof t.finalizeTurnDecision=="function"&&await t.finalizeTurnDecision({turnEventId:i.eventId,sessionId:i.sessionId,turnId:i.turnId,receiptId:a,status:"committed",memoryIds:[s.id],reason:"explicit_user_request"});}catch(l){console.error("[devflow] Canonical memory lineage finalization deferred:",l.message);}try{await t.enrichExplicitMemoryObservation(s.id);}catch(l){console.error("[devflow] Explicit memory enrichment deferred:",l.message),r.enqueueWork({idempotencyKey:`explicit-enrichment:${o}:${s.id}`,kind:"memory.explicit_enrichment",projectRoot:o,sessionId:e.sessionId,turnId:c.turnId,payload:{observationId:s.id},maxAttempts:20});}r.enqueueWork({idempotencyKey:`vector:${o}:${s.id}`,kind:"memory.vector_backfill",projectRoot:o,sessionId:e.sessionId,turnId:c.turnId,payload:{observationId:s.id},maxAttempts:20});try{await Le({projectRoot:o,memory:t,injectConfig:loadConfig(o).sessionStart?.injectMemories,reason:"explicit_memory_commit"});}catch(l){console.error("[devflow] Memory snapshot refresh failed after canonical commit:",l.message);}return {turn:c,explicitContent:e.explicitContent,additionalContext:Ct(c),skipSkillRouting:!0}}finally{r.close();}}var Pa=new Set(["Write","Edit","NotebookEdit"]),Wo="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 Bo(n){if(!Pa.has(n.toolName))return null;let e=ja(n.toolInput);if(!e)return null;let t=Fa(e,n.projectRoot),o=resolve(n.projectRoot,".claude");if(qo(t,o)&&basename(t).toLocaleUpperCase("en-US")==="MEMORY.MD")return Wo;let r=resolve(n.home??homedir(),".claude","projects");return qo(t,r)&&relative(r,t).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?Wo:null}function ja(n){for(let e of ["file_path","notebook_path","path"]){let t=n[e];if(typeof t=="string"&&t.trim())return t.trim()}return null}function Fa(n,e){return resolve(isAbsolute(n)?n:resolve(e,n))}function qo(n,e){let t=relative(e,n);return t===""||!t.startsWith(`..${sep}`)&&t!==".."&&!isAbsolute(t)}var qa=1024*1024;function Ko(n){let e=join(getProjectStateDir(n),"session-start-pending");mkdirSync$1(e,{recursive:true,mode:448});let t=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!t)return null;let o=join(e,t),r=/\.json\.claim-\d+$/u.test(t),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")>qa)throw unlinkSync$1(i),new Error("session_start_spool_input_too_large");return {receiptId:basename(t).replace(/\.json(?:\.claim-\d+)?$/u,""),input:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function Yo(n){unlinkSync$1(n.path);}function Xo(n){let e=n.path.replace(/\.claim-\d+$/u,"");try{renameSync(n.path,e);}catch{}}function Zo(n,e){let t=or(n);mkdirSync$1(t,{recursive:true,mode:448});let o=`memory-turn-spool-${Date.now()}-${process.pid}-${randomUUID$1()}`,r=join(t,`${o}.json`),i=`${r}.tmp`;return writeFileSync$1(i,JSON.stringify({...e,prompt:e.prompt.trim().slice(0,4e3)}),{mode:384}),renameSync(i,r),o}function er(n){let e=or(n);mkdirSync$1(e,{recursive:true,mode:448});let t=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!t)return null;let o=join(e,t),r=/\.json\.claim-\d+$/u.test(t),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(t).replace(/\.json(?:\.claim-\d+)?$/u,""),payload:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function tr(n){unlinkSync$1(n.path);}function nr(n){try{renameSync(n.path,n.path.replace(/\.claim-\d+$/u,""));}catch{}}function or(n){return join(R(n),"memory-turn-pending")}var k=class extends Error{constructor(e,t){super(t),this.name="PermanentWorkError",this.category=e;}},Ya=1e3,Xa=3e4,Qa=1,Za=5*6e4,ze=class{constructor(e){this.timer=null;this.draining=null;this.stopped=true;this.projectRoot=e.projectRoot,this.handlers=e.handlers,this.pollIntervalMs=$t(e.pollIntervalMs,Ya),this.leaseMs=$t(e.leaseMs,Xa),this.batchSize=$t(e.batchSize,Qa),this.owner=e.owner??`hook-daemon:${process.pid}:${randomUUID$1()}`,this.now=e.now??Date.now,this.random=e.random??Math.random,this.openDatabase=e.openDatabase??(()=>openGlobalDevFlowDatabase()),this.afterComplete=e.afterComplete;}start(){this.stopped&&(this.stopped=false,this.schedule(0));}stop(){this.stopped=true,this.timer&&clearTimeout(this.timer),this.timer=null;}drainOnce(){return this.draining?this.draining:(this.draining=this.performDrain().finally(()=>{this.draining=null;}),this.draining)}schedule(e){this.stopped||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null,this.drainOnce().catch(t=>console.error("[devflow-work] Drain failed:",Ht(t))).finally(()=>this.schedule(this.pollIntervalMs));},e),this.timer.unref());}async performDrain(){let e=Object.keys(this.handlers);if(e.length===0)return 0;let t=this.openDatabase();try{let o=this.now();t.recoverExpiredWork(this.projectRoot,o);let r=t.leaseWork({projectRoot:this.projectRoot,owner:this.owner,kinds:e,limit:this.batchSize,leaseMs:this.leaseMs,now:o});for(let i of r)await this.processItem(t,i);return r.length}finally{t.close();}}async processItem(e,t){let o=this.handlers[t.kind];if(!o){e.deadLetterWork(t.id,this.owner,{category:"unsupported_work_kind",message:`No work handler is registered for ${t.kind}`});return}let r=setInterval(()=>{e.heartbeatWork(t.id,this.owner,this.leaseMs,this.now())||console.error(`[devflow-work] Work lease heartbeat was rejected: ${t.id}`);},Math.max(1e3,Math.floor(this.leaseMs/3)));r.unref();try{if(await o({item:t}),!e.completeWork(t.id,this.owner,this.now()))throw new Error(`Work lease was lost before completion: ${t.id}`);try{await this.afterComplete?.({item:t,database:e});}catch(i){console.error("[devflow-work] Completion follow-up failed:",Ht(i));}}catch(i){let s=ec(i);if(i instanceof k||s.permanent){e.deadLetterWork(t.id,this.owner,s);return}let a=this.now()+Math.max(tc(t.attempts,this.random()),s.retryAfterMs??0);if(s.retryWithoutAttempt){e.deferWork(t.id,this.owner,s,a);return}e.retryWork(t.id,this.owner,s,a);}finally{clearInterval(r);}}};function $t(n,e){return Number.isSafeInteger(n)&&n>0?n:e}function ec(n){if(n instanceof k)return {category:n.category,message:n.message};let e=n&&typeof n=="object"?n:null,t=typeof e?.category=="string"?e.category:"runtime_error";return {category:t,message:Ht(n),retryAfterMs:typeof e?.retryAfterMs=="number"&&Number.isFinite(e.retryAfterMs)?Math.max(0,e.retryAfterMs):void 0,retryWithoutAttempt:e?.retryWithoutAttempt===true,permanent:t==="policy_verification_failed"||t==="invalid_payload"}}function tc(n,e){let t=Math.min(Za,500*2**Math.max(0,n-1)),o=Math.floor(t*.2*Math.max(0,Math.min(1,e)));return t+o}function Ht(n){return n instanceof Error?n.message:String(n)}var sc=250;function sr(n,e=process.env){let t=ir(join(homedir(),".devflow","config.json")),o=ir(join(n,".devflow","config.json")),r=Nt(e.DEVFLOW_HOOK_PROFILE)??Nt(o.profile)??Nt(t.profile)??"standard",i=Number(e.DEVFLOW_HOOK_ACK_BUDGET_MS??o.acknowledgementBudgetMs??t.acknowledgementBudgetMs),s=Number.isSafeInteger(i)&&i>0?Math.min(i,5e3):sc,a=new Set([...Lt(t.disabledHandlers),...Lt(o.disabledHandlers),...Lt(e.DEVFLOW_DISABLED_HOOK_HANDLERS?.split(","))].map(dc).filter(c=>!!c));return {profile:r,acknowledgementBudgetMs:s,disabledHandlers:a}}async function ar(n,e,t,o){let r,i=new Promise(s=>{r=setTimeout(()=>{console.error(`[devflow-hook] ${n} exceeded ${e}ms acknowledgement budget`),s(o());},e),r.unref();});try{return await Promise.race([Promise.resolve().then(t),i])}finally{r&&clearTimeout(r);}}async function cr(n,e=process.env){let t=e.DEVFLOW_HOST_ADAPTER??(e.CLAUDE_PROJECT_DIR||e.CLAUDE_PLUGIN_ROOT||e.CLAUDE_CODE_ENTRYPOINT?"claude-code":void 0),o=await selectHostAdapter({projectRoot:n,env:e,explicitHost:t});if(o.status==="failed")throw new Error(`host_adapter_selection_failed:${o.code}:${o.reason}`);let r=await o.adapter.capabilities({projectRoot:n,env:e,explicitHost:t});return {hostId:o.adapter.id,capabilities:new Map(r.map(i=>[i.capability,i])),profiles:new Set(o.adapter.hooks?.profileSupport??[])}}function Wt(n,e,t){let o=lc(n,e.profile);if(!t.profiles.has(e.profile))return {enabled:false,policy:"fail_open",reason:`hook_profile_${e.profile}_unsupported_by_${t.hostId}`,fallback:"host_event_continues_without_devflow_handler"};if(e.disabledHandlers.has(n))return {enabled:false,policy:"fail_open",reason:"hook_handler_disabled",fallback:"host_event_continues_without_devflow_handler"};if(e.profile==="minimal"&&!ac.has(n))return {enabled:false,policy:"fail_open",reason:"hook_handler_not_in_minimal_profile",fallback:"critical_receipts_only"};let r=cc[n];if(!r)return {enabled:true,policy:o};let i=t.capabilities.get(r);return !i||i.status!=="supported"?{enabled:false,policy:"fail_open",reason:i?.reason??`${r}_unsupported_by_${t.hostId}`,fallback:i?.fallback??"host_event_continues_without_native_hook_processing"}:{enabled:true,policy:o}}var ac=new Set(["session-start","user-prompt-submit","stop","session-end","memory-snapshot"]),cc={"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 lc(n,e){return n==="user-prompt-submit"||n==="stop"||n==="session-end"?"enqueue_and_open":n==="pre-tool-use"&&e==="strict"?"fail_closed":"fail_open"}function ir(n){if(!existsSync(n))return {};try{let t=JSON.parse(readFileSync$1(n,"utf8")).hooks;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return {}}}function Nt(n){return n==="minimal"||n==="standard"||n==="strict"?n:void 0}function Lt(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function dc(n){let e=n.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase();return ({sessionstart:"session-start",userpromptsubmit:"user-prompt-submit",pretooluse:"pre-tool-use",posttooluse:"post-tool-use",posttoolusefailure:"post-tool-use-failure",sessionend:"session-end",precompact:"pre-compact",memorysnapshot:"memory-snapshot"}[e.replace(/-/g,"")]??e)||void 0}function lr(n){let e=Object.keys(n.handlers).map(t=>{let o=pc[t];return [t,{requestType:t,eventName:o,capability:mc[t],failurePolicy:n.failurePolicy(t),acknowledgeWithinBudget:uc.has(t),handler:n.handlers[t],timeoutResult:()=>fc(t)}]});return new Map(e)}async function dr(n){let e=n.registry.get(n.requestType);if(!e)return {status:"degraded",reason:"unknown_hook_handler",fallback:"host_event_continues"};let t=()=>Promise.resolve(e.handler(n.rawInput));return e.acknowledgeWithinBudget?ar(e.eventName,n.acknowledgementBudgetMs,t,e.timeoutResult):t()}var uc=new Set(["stop","session-end","user-prompt-submit"]),pc={"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"},mc={"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 fc(n){return n==="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:n==="session-end"?"durable_session_recovery":"background_processing"}}var Be=class{constructor(e){this.records=new Map;this.path=join(R(e),"hook-handler-health.json"),this.load();}recordSuccess(e,t,o=Date.now()){let r={handler:e,host:t,status:"healthy",consecutiveFailures:0,lastSuccessAt:o,updatedAt:o};return this.records.set(Je(e,t),r),this.persist(),r}recordFailure(e,t,o,r,i=Date.now()){let s=this.records.get(Je(e,t)),a=(s?.consecutiveFailures??0)+1,c=Math.min(5*6e4,1e3*2**Math.min(8,a-1)),l={handler:e,host:t,status:"degraded",consecutiveFailures:a,lastFailureCategory:o,lastFailureReason:r.slice(0,500),retryAt:i+c,lastSuccessAt:s?.lastSuccessAt,updatedAt:i};return this.records.set(Je(e,t),l),this.persist(),l}list(){return [...this.records.values()].sort((e,t)=>e.handler.localeCompare(t.handler))}load(){try{let e=JSON.parse(readFileSync$1(this.path,"utf8"));for(let t of e)t?.handler&&t?.host&&this.records.set(Je(t.handler,t.host),t);}catch{}}persist(){try{mkdirSync$1(dirname$1(this.path),{recursive:!0,mode:448});let e=`${this.path}.${process.pid}.tmp`;writeFileSync$1(e,JSON.stringify(this.list(),null,2),{mode:384}),renameSync(e,this.path);}catch{}}};function Je(n,e){return `${e}\0${n}`}function ur(n,e){return e||(n==="post-tool-use"||n==="post-tool-use-failure"?{status:"ok"}:{status:"ok"})}function pr(n){let e=n instanceof Error?n.message:String(n??"hook_handler_failed");return {category:/timeout|budget|deadline/iu.test(e)?"timeout":/sqlite|database|locked|busy/iu.test(e)?"storage":/socket|connect|unreachable/iu.test(e)?"transport":/json|parse|schema|invalid/iu.test(e)?"protocol":"handler",reason:e}}function mr(n){let e=so({projectRoot:n.projectRoot,sessionId:n.sessionId,transcriptPath:n.transcriptPath,runtimeStore:n.runtimeStore}),t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{Ic(n.runtimeStore,n.sessionId,t);let o=t.getPendingMemoryTurn(n.projectRoot,n.sessionId),r=o?t.markMemoryTurnStopPrompted(o.turnId):!1,i=[];e&&i.push(e.reason),o&&r&&i.push(qe(o)),o&&!r&&kc(t,o.turnId)&&Sc(Me(n.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=t.listSessionObligations(n.projectRoot,n.sessionId,["open"]).map(c=>({obligationId:c.obligationId,kind:c.kind,action:c.kind==="memory_decision"?"Call mcp__devflow__memory_decide_turn using the canonical turn ID.":c.kind==="evidence_contract"?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(sc({projectRoot:t,configPath:n,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var cc=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu;function dc(e){let t=e.trim();return t.length>0&&!cc.test(t)}function lc(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 Ze(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 Ye(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 qt(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(d=>d.promptHash===o&&Date.now()-d.createdAt<1e4),i=r?{turnId:r.turnId,eventId:r.eventId,promptHash:r.promptHash,createdAt:r.createdAt}:e.identity??lc(e.sessionId,n),s=r??t.beginMemoryTurn({...i,projectRoot:e.projectRoot,sessionId:e.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:Ye(s),skipSkillRouting:s.source==="explicit_intent"};let a=Ue(n)??void 0,c=a?"commit_explicit":"capture_prompt";if(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}}),a){let d=`raw-memory:${createHash("sha256").update(`${e.projectRoot}\0${i.turnId}\0${a}`).digest("hex").slice(0,24)}`,l=Xe(s.turnId,"committed",[d]),u=t.commitMemoryTurn({turnId:s.turnId,receiptId:l,memoryIds:[d],source:"explicit_intent",reason:"explicit_raw_queued",decidedAt:Date.now()});return emitSemanticControlLog({event:"memory.write.completed",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:s.turnId,actionReceipt:l},level:"info",timestamp:Date.now(),data:{stage:"explicit_fast_ack",durable:!0,rawMemoryId:d,receiptLatencyMs:Date.now()-i.createdAt,asyncReadiness:"queued"}}),{turn:u,explicitContent:a,additionalContext:Ye(u),skipSkillRouting:!0}}return {turn:s,explicitContent:a,additionalContext:Ze(s),skipSkillRouting:!1}}finally{t.close();}}async function Ut(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:Ye(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:Ze(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"});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 Qe({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:Ye(l),skipSkillRouting:!0}}finally{r.close();}}var pc=new Set(["Write","Edit","NotebookEdit"]),rr="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 dr(e){if(!pc.has(e.toolName))return null;let t=fc(e.toolInput);if(!t)return null;let n=gc(t,e.projectRoot),o=resolve(e.projectRoot,".claude");if(ir(n,o)&&basename(n).toLocaleUpperCase("en-US")==="MEMORY.MD")return rr;let r=resolve(e.home??homedir(),".claude","projects");return ir(n,r)&&relative(r,n).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?rr:null}function fc(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 gc(e,t){return resolve(isAbsolute(e)?e:resolve(t,e))}function ir(e,t){let n=relative(t,e);return n===""||!n.startsWith(`..${sep}`)&&n!==".."&&!isAbsolute(n)}var Ic=1024*1024;function mr(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")>Ic)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 pr(e){unlinkSync$1(e.path);}function fr(e){let t=e.path.replace(/\.claim-\d+$/u,"");try{renameSync(e.path,t);}catch{}}function hr(e,t){let n=wr(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 yr(e){let t=wr(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 vr(e){unlinkSync$1(e.path);}function _r(e){try{renameSync(e.path,e.path.replace(/\.claim-\d+$/u,""));}catch{}}function wr(e){return join(D(e),"memory-turn-pending")}var x=class extends Error{constructor(t,n){super(n),this.name="PermanentWorkError",this.category=t;}},Ac=1e3,Cc=3e4,Dc=1,Mc=5*6e4,tt=class{constructor(t){this.timer=null;this.draining=null;this.stopped=true;this.projectRoot=t.projectRoot,this.handlers=t.handlers,this.pollIntervalMs=Vt(t.pollIntervalMs,Ac),this.leaseMs=Vt(t.leaseMs,Cc),this.batchSize=Vt(t.batchSize,Dc),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}`});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}`);try{await this.afterComplete?.({item:n,database:t});}catch(i){this.logDegradation("completion_follow_up",i,n);}}catch(i){let s=Oc(i);if(i instanceof x||s.permanent){t.deadLetterWork(n.id,this.owner,s);return}let a=this.now()+Math.max(Pc(n.attempts,this.random()),s.retryAfterMs??0);if(s.retryWithoutAttempt){t.deferWork(n.id,this.owner,s,a);return}t.retryWork(n.id,this.owner,s,a);}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:Ir(n)}});}};function Vt(e,t){return Number.isSafeInteger(e)&&e>0?e:t}function Oc(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:Ir(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 Pc(e,t){let n=Math.min(Mc,500*2**Math.max(0,e-1)),o=Math.floor(n*.2*Math.max(0,Math.min(1,t)));return n+o}function Ir(e){return e instanceof Error?e.message:String(e)}var Nc=250;function Sr(e,t=process.env){let n=kr(join(homedir(),".devflow","config.json")),o=kr(join(e,".devflow","config.json")),r=Kt(t.DEVFLOW_HOOK_PROFILE)??Kt(o.profile)??Kt(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):Nc,a=new Set([...Qt(n.disabledHandlers),...Qt(o.disabledHandlers),...Qt(t.DEVFLOW_DISABLED_HOOK_HANDLERS?.split(","))].map(Uc).filter(c=>!!c));return {profile:r,acknowledgementBudgetMs:s,disabledHandlers:a}}async function Rr(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 xr(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 Yt(e,t,n){let o=qc(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"&&!Lc.has(e))return {enabled:false,policy:"fail_open",reason:"hook_handler_not_in_minimal_profile",fallback:"critical_receipts_only"};let r=Wc[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 Lc=new Set(["session-start","user-prompt-submit","stop","session-end","memory-snapshot"]),Wc={"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 qc(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 kr(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 Kt(e){return e==="minimal"||e==="standard"||e==="strict"?e:void 0}function Qt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Uc(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 Er(e){let t=Object.keys(e.handlers).map(n=>{let o=Bc[n];return [n,{requestType:n,eventName:o,capability:Jc[n],failurePolicy:e.failurePolicy(n),acknowledgeWithinBudget:zc.has(n),handler:e.handlers[n],timeoutResult:()=>Gc(n)}]});return new Map(t)}async function Tr(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?Rr(t.eventName,e.acknowledgementBudgetMs,n,t.timeoutResult,e.projectRoot):n()}var zc=new Set(["stop","session-end","user-prompt-submit"]),Bc={"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"},Jc={"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 Gc(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 ot=class{constructor(t){this.records=new Map;this.path=join(D(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(nt(t,n),r),this.persist(),r}recordFailure(t,n,o,r,i=Date.now()){let s=this.records.get(nt(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(nt(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(nt(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 nt(e,t){return `${t}\0${e}`}function Ar(e,t){return t||(e==="post-tool-use"||e==="post-tool-use-failure"?{status:"ok"}:{status:"ok"})}function Cr(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 Dr(e){let t=wo({projectRoot:e.projectRoot,sessionId:e.sessionId,transcriptPath:e.transcriptPath,runtimeStore:e.runtimeStore}),n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{rd(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(Ze(o)),o&&!r&&nd(n,o.turnId)&&od(We(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(`
26
28
 
27
- `)}:a.length>0?{decision:"degrade",unresolved:a,additionalContext:"DevFlow terminal obligations remain unresolved after their one-shot correction budget."}:{decision:"allow",unresolved:[]}}finally{t.close();}}function kc(n,e){return !!n.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${e}`)}function Sc(n){if(!n)return false;let e=n.normalize("NFKC").replace(/\s+/gu," ");return /(?:未|没有|无法|失败|暂未|尚未).{0,24}(?:记住|记下|记录|保存|持久化|回执)|(?:memory|receipt).{0,24}(?:failed|missing|pending|degraded|not saved)|status=(?:pending|degraded|rejected|failed)/iu.test(e)?false:/(?:已|已经|成功).{0,20}(?:记住|记下|记录|保存|持久化)|跨会话生效|(?:memory|preference).{0,20}(?:saved|remembered|persisted)|status=(?:accepted|committed)/iu.test(e)}function Ic(n,e,t){let o=n.get(e);if(o){for(let r of o.evidenceObligations)t.upsertSessionObligation({obligationId:`evidence:${r.obligationId}`,projectRoot:o.projectRoot,sessionId:e,executionId:o.executionId,kind:"evidence_contract",state:"open",payload:{contract:r.contract,runtimeObligationId:r.obligationId},createdAt:r.promptedAt,updatedAt:o.lastActivityAt});for(let r of o.evidenceOutcomes){let i=`evidence:${r.obligationId}`,s=t.getSessionObligation(o.projectRoot,e,i);!s||s.state!=="open"||t.resolveSessionObligation({projectRoot:o.projectRoot,sessionId:e,obligationId:i,state:r.status==="resolved"?"satisfied":"degraded",reason:r.reason,resolvedAt:r.completedAt});}}}var Rc=[/\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],Ec=[/\b(?:migration|upgrade|dependency|dependencies|generated files?|write all|rewrite)\b/iu,/(?:迁移|升级|依赖|生成文件|批量写入)/u];function qt(n){let e=`${n.instruction}
28
- ${JSON.stringify(n.trigger)}`,t=[];Rc.some(r=>r.test(e))&&t.push("high_risk_operation"),Ec.some(r=>r.test(e))&&t.push("broad_or_migrating_change"),n.kind==="correction"&&t.push("user_correction_requires_observation");let o=t.includes("high_risk_operation")?"high":t.includes("broad_or_migrating_change")||n.scope==="global"?"medium":"low";return {risk:o,manualOnly:o==="high"||t.includes("broad_or_migrating_change"),reasons:t}}var xc=new Set(["project_convention","user_preference","decision_made","config_discovery"]);function zt(n){let e=n.payload.executionId?n.database.getSkillExecution(n.payload.executionId):n.database.getLatestSkillExecutionForSession(n.payload.sessionId),t=n.database.listHostActionsForSession(n.payload.projectRoot,n.payload.sessionId,n.payload.executionId),o=t.find(d=>d.state==="verified"),r=t.find(d=>["failed","cancelled","degraded"].includes(d.state)),i=r?"negative":o?"positive":"unknown",s=new Set,a=[],c=0,l=0;for(let d of n.evidence){if(!Tc(d)){l+=1;continue}let u=yr(d),p=Cc(d,e?.skillName),f=vr(d),m=Ac(n.payload.projectRoot,u,d.facetKey??d.semanticKey??d.id,p),v=n.database.getLearningCandidate(m),w=qt({scope:"project",kind:u,instruction:f,trigger:p});n.database.upsertLearningCandidate({id:m,projectRoot:n.payload.projectRoot,scope:"project",kind:u,trigger:p,instruction:f,confidence:Dc(d),manualOnly:w.manualOnly,risk:w.risk});v&&v.instruction!==f&&n.database.addLearningCandidateEvidence({id:fr(m,n.payload.sessionId,d.id,"contradicting"),candidateId:m,projectRoot:n.payload.projectRoot,sessionId:n.payload.sessionId,executionId:n.payload.executionId,memoryObservationId:d.id,sourceType:"correction",polarity:"contradicting",outcome:i,evidenceHash:gr(m,n.payload,d,"contradicting"),receipt:n.payload.closureReceipt,payload:{previousInstruction:v.instruction,replacementInstruction:f,projectRevision:n.payload.projectRevision},createdAt:d.createdAt});let I=n.database.addLearningCandidateEvidence({id:fr(m,n.payload.sessionId,d.id,"supporting"),candidateId:m,projectRoot:n.payload.projectRoot,sessionId:n.payload.sessionId,executionId:n.payload.executionId,memoryObservationId:d.id,outcomeId:o?.id??r?.id,sourceType:Mc(d),polarity:"supporting",outcome:i,evidenceHash:gr(m,n.payload,d,"supporting"),receipt:n.payload.closureReceipt,payload:{semanticKey:d.semanticKey,facetKey:d.facetKey,evidenceStatus:d.evidenceStatus,source:d.source,projectRevision:n.payload.projectRevision,executionStatus:e?.status,policyReasons:w.reasons},createdAt:d.createdAt});c+=1,s.add(m),n.rolloutMode!=="off"&&I.state==="candidate"&&I.supportingSessions>=3&&I.successfulOutcomes>=2&&n.database.transitionLearningCandidate(m,{target:"shadow",reason:"evidence_threshold_satisfied"}).state==="shadow"&&a.push(m);}return {considered:n.evidence.length,accepted:c,excluded:l,candidateIds:[...s],promotedToShadow:a}}function Tc(n){return !(!xc.has(n.type)||n.source!=="explicit_intent"&&n.source!=="manual"&&n.evidenceStatus!=="verified"||!n.narrative.trim()&&!n.title.trim())}function yr(n){return n.type==="decision_made"?"workflow":n.type==="user_preference"&&(n.semanticValue.startsWith("--")||n.tools.length>0)?"tool_preference":"convention"}function Cc(n,e){return {...e?{skills:[e]}:{},...n.entities.length>0?{entities:[...new Set(n.entities)].slice(0,8)}:{},...n.files.length>0?{files:[...new Set(n.files)].slice(0,8)}:{},...n.tools.length>0?{commands:[...new Set(n.tools)].slice(0,8)}:{},semantic:{subject:n.semanticSubject,predicate:n.semanticPredicate,value:n.semanticValue,polarity:n.semanticPolarity}}}function vr(n){return (n.narrative.trim()||n.title.trim()).replace(/\s+/gu," ").slice(0,1200)}function Dc(n){let e=n.source==="explicit_intent"?.08:0;return Math.max(0,Math.min(1,n.confidence+e))}function Mc(n){return n.semanticPolarity==="negative"?"correction":yr(n)==="tool_preference"?"tool_preference":n.source==="explicit_intent"?"memory":"convention"}function Ac(n,e,t,o){let r={...o,semantic:void 0};return `learning:${createHash("sha256").update(`${n}\0project\0${e}\0${t}\0${stableLearningJson(r)}`).digest("hex").slice(0,24)}`}function fr(n,e,t,o){return `learning-evidence:${createHash("sha256").update(`${n}\0${e}\0${t}\0${o}`).digest("hex").slice(0,24)}`}function gr(n,e,t,o){return createHash("sha256").update(stableLearningJson({candidateId:n,sessionId:e.sessionId,executionId:e.executionId,closureReceipt:e.closureReceipt,projectRevision:e.projectRevision,observationId:t.id,instruction:vr(t),polarity:o})).digest("hex")}var X=3e4,Gt=1e3,Vc=new Set(["git","npm","pnpm","yarn"]);function wr(n){return {"workflow.worker_start":async({item:e})=>Kc(n,e),"workflow.worker_monitor":async({item:e})=>Yc(n,e),"workflow.worker_verify":async({item:e})=>Xc(n,e),"workflow.worker_merge":async({item:e})=>Qc(n,e),"workflow.worker_cleanup":async({item:e})=>Zc(n,e)}}async function Kc(n,e){await he(n,e,async(t,o)=>{if(o.state==="running"||o.state==="starting"){Jt(t,o);return}if(o.state!=="planned")return;let r=`worker-plane:${process.pid}`;t.leaseWorkflowWorker(n,o.workerId,r,X);let i=await createManagedWorktree({projectRoot:n,runId:o.runId,stepId:o.stepId,baseRevision:o.baseRevision,registered:!0});if(i.worktreePath!==o.worktreePath||i.branch!==o.branch){t.transitionWorkflowWorker({projectRoot:n,workerId:o.workerId,target:"hold",leaseOwner:r,reason:"managed_worktree_identity_mismatch"});return}t.transitionWorkflowWorker({projectRoot:n,workerId:o.workerId,target:"starting",leaseOwner:r});let s=kr(o.workerId),a=el(o);createWorkerArtifacts(s,a);let l=createDefaultHostAdapterRegistry().list().find(f=>f.id===o.host);if(!l)throw new k("unsupported_worker_host",`Unsupported worker host ${o.host}`);let d=Q(o.handoff.actionId,"actionId"),u=t.getHostAction(n,d);if(!u)throw new k("worker_host_action_missing",`Host action ${d} was not found`);u.state==="waiting"&&t.startHostAction({actionId:d,projectRoot:n});let p=launchWorker(l,{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(n,o.workerId,r,X);}catch{}finally{f.close();}}});tl(s,{state:"running",pid:p.child.pid,owner:r,startedAt:Date.now()}),t.transitionWorkflowWorker({projectRoot:n,workerId:o.workerId,target:"running",leaseOwner:r,heartbeatAt:Date.now(),leaseExpiresAt:Date.now()+X}),Jt(t,o),p.completion.finally(()=>{let f=openGlobalDevFlowDatabase();try{Jt(f,o,Date.now());}finally{f.close();}});});}async function Yc(n,e){await he(n,e,async(t,o)=>{if(o.state!=="running"&&o.state!=="starting")return;let r=kr(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}),l=Q(o.handoff.actionId,"actionId");t.reportHostAction({actionId:l,projectRoot:n,report:{workerId:o.workerId,handoff:c},evidenceHash:Ir(c)}),t.transitionWorkflowWorker({projectRoot:n,workerId:o.workerId,target:"reported",leaseOwner:o.leaseOwner,finalRevision:c.finalRevision,handoff:{...o.handoff,terminalHandoff:c}}),t.enqueueWork({idempotencyKey:`workflow-worker-verify:${o.workerId}:${c.finalRevision}`,kind:"workflow.worker_verify",projectRoot:n,payload:{workerId:o.workerId}});return}let i=nl(r),s=typeof i?.pid=="number"?i.pid:void 0;if(s&&rl(s)){let c=typeof i?.startedAt=="number"?i.startedAt:o.updatedAt;if(Date.now()-c>30*6e4){try{process.kill(s,"SIGTERM");}catch{}t.transitionWorkflowWorker({projectRoot:n,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_process_timeout"});let d=Q(o.handoff.actionId,"actionId");t.failHostAction({actionId:d,projectRoot:n,report:{reason:"worker_process_timeout"}});return}let l=o.leaseOwner??(typeof i?.owner=="string"?i.owner:void 0);throw l?(t.heartbeatWorkflowWorker(n,o.workerId,l,X),Sr("worker_running",Gt)):new k("worker_lease_owner_missing","Worker lease owner is missing")}t.transitionWorkflowWorker({projectRoot:n,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_exited_without_handoff"});let a=Q(o.handoff.actionId,"actionId");t.failHostAction({actionId:a,projectRoot:n,report:{reason:"worker_exited_without_handoff"}});});}async function Xc(n,e){await he(n,e,async(t,o)=>{if(o.state!=="reported")return;t.transitionWorkflowWorker({projectRoot:n,workerId:o.workerId,target:"verifying",leaseOwner:o.leaseOwner});let r=o.handoff.terminalHandoff;if(!r)throw new k("worker_handoff_missing","Persisted worker handoff is missing");let i=Q(o.handoff.actionId,"actionId"),s=t.getHostAction(n,i);if(!s)throw new k("worker_host_action_missing",`Host action ${i} was not found`);let a=_r(o),c=new GraderRegistry,l=await br(t,o,async()=>verifyWorkerOutput({workerId:o.workerId,projectRoot:n,worktreePath:o.worktreePath,baseRevision:o.baseRevision,parentRevision:await ol(n),contextReceipt:o.contextReceipt,allowedFiles:o.allowedFiles,handoff:r,hostAction:s,verificationCommands:a,graderIds:["receipt_validity","lifecycle_terminal_state","workflow_evidence"],graderRunner:{run:async d=>{let u=await c.run({taskId:o.stepId,taskKind:d.taskKind,projectRoot:d.projectRoot,acceptanceCriteria:[],evidence:d.evidence});return {...u,unavailableBlocking:u.unavailableRequired}}}}));if(!l.passed){t.transitionWorkflowWorker({projectRoot:n,workerId:o.workerId,target:l.state,leaseOwner:o.leaseOwner,reason:l.reason}),l.state==="failed"&&t.failHostAction({actionId:i,projectRoot:n,outcome:"failed",report:{...s.report,verification:l},evidenceHash:l.simulationHash});return}t.transitionWorkflowWorker({projectRoot:n,workerId:o.workerId,target:"merge_ready",leaseOwner:o.leaseOwner,finalRevision:l.finalRevision,handoff:{...o.handoff,terminalHandoff:r,verification:l}}),t.enqueueWork({idempotencyKey:`workflow-worker-merge:${o.workerId}:${l.finalRevision}`,kind:"workflow.worker_merge",projectRoot:n,payload:{workerId:o.workerId}});});}async function Qc(n,e){await he(n,e,async(t,o)=>{if(o.state!=="merge_ready")return;let r=o.handoff.verification;if(!r?.passed)throw new k("worker_verification_missing","Verified merge evidence is missing");let i=Q(o.handoff.actionId,"actionId"),s=new SerializedWorkerMergeQueue(t,{onMerged:async({mergeCommit:c})=>{t.transitionWorkflowWorker({projectRoot:n,workerId:o.workerId,target:"merged",leaseOwner:o.leaseOwner,finalRevision:o.finalRevision,reason:`merged:${c}`});let l=t.getHostAction(n,i);t.verifyHostAction({actionId:i,projectRoot:n,report:{...l?.report??{},mergeCommit:c,verification:r},evidenceHash:Ir({mergeCommit:c,verification:r})});},scheduleCleanup:()=>{t.enqueueWork({idempotencyKey:`workflow-worker-cleanup:${o.workerId}:merged`,kind:"workflow.worker_cleanup",projectRoot:n,payload:{workerId:o.workerId}});}}),a=await br(t,o,()=>s.enqueueAndMerge({workerId:o.workerId,projectRoot:n,baseRevision:o.baseRevision,verification:r,message:`merge(devflow-worker): ${o.runId}/${o.stepId}`}));a.state==="conflict"&&t.transitionWorkflowWorker({projectRoot:n,workerId:o.workerId,target:"hold",leaseOwner:o.leaseOwner,reason:a.reason??"merge_conflict"});});}async function Zc(n,e){await he(n,e,async(t,o)=>{let r=e.payload,i=await cleanupManagedWorktree({repositoryRoot:n,worktreePath:o.worktreePath,branch:o.branch,registered:!0,handoffDurable:!!o.handoff.terminalHandoff||r.operatorApproved===!0});if(!i.cleaned)throw Sr(`cleanup_${i.reason??"refused"}`,3e4)});}async function br(n,e,t){let o=e.leaseOwner;if(!o)return t();let r=setInterval(()=>{try{n.heartbeatWorkflowWorker(e.projectRoot,e.workerId,o,X);}catch{}},Math.floor(X/3));r.unref();try{return await t()}finally{clearInterval(r);}}async function he(n,e,t){let o=il(e.payload),r=openGlobalDevFlowDatabase();try{let i=r.getWorkflowWorker(n,o);if(!i)throw new k("worker_not_found",`Worker ${o} was not found`);await t(r,i);}finally{r.close();}}function el(n){let e=n.handoff.task;if(!e||typeof e!="object"||Array.isArray(e))throw new k("worker_task_missing","Worker task envelope is missing");let t=_r(n);return {workerId:n.workerId,runId:n.runId,stepId:n.stepId,projectRoot:n.projectRoot,worktreePath:n.worktreePath,baseRevision:n.baseRevision,contextReceipt:n.contextReceipt,retrievalSessionId:n.retrievalSessionId,allowedFiles:n.allowedFiles,requiredTools:[],task:e,verification:{commands:t,graders:["receipt_validity","lifecycle_terminal_state","workflow_evidence"]},constraints:{recursiveWorkers:false,maxContextCycles:3}}}function _r(n){let e=n.handoff.verificationCommands;if(!Array.isArray(e)||e.length===0)throw new k("verification_contract_missing","Worker verification commands are missing");return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new k("verification_contract_invalid","Worker verification command is malformed");let o=t;if(typeof o.command!="string"||!Vc.has(o.command)||!Array.isArray(o.args)||o.args.some(r=>typeof r!="string"))throw new k("verification_contract_invalid","Worker verification command is not allowlisted");return {command:o.command,args:o.args}})}function kr(n){let e=workerCoordinationRoot(n,homedir());return {root:e,taskFile:join(e,"task.json"),handoffFile:join(e,"handoff.json"),statusFile:join(e,"status.json"),stdoutFile:join(e,"stdout.log"),stderrFile:join(e,"stderr.log")}}function tl(n,e){writeJsonAtomic(n.statusFile,e);}function nl(n){try{return JSON.parse(readFileSync$1(n.statusFile,"utf8"))}catch{return null}}function Jt(n,e,t=Date.now()+Gt){n.enqueueWork({idempotencyKey:`workflow-worker-monitor:${e.workerId}:${Math.floor(t/Gt)}`,kind:"workflow.worker_monitor",projectRoot:e.projectRoot,payload:{workerId:e.workerId},nextAttemptAt:t,maxAttempts:1e3});}async function ol(n){let{gitRevision:e}=await import('@devflow-tools/workflow-engine');return e(n,"HEAD")}function rl(n){try{return process.kill(n,0),!0}catch{return false}}function Sr(n,e){return Object.assign(new Error(n),{category:n,retryAfterMs:e,retryWithoutAttempt:true})}function il(n){if(!n||typeof n!="object"||typeof n.workerId!="string")throw new k("invalid_worker_payload","Worker work item requires workerId");return n.workerId}function Q(n,e){if(typeof n!="string"||!n.trim())throw new k("worker_identity_missing",`Worker ${e} is missing`);return n}function Ir(n){return createHash("sha256").update(JSON.stringify(n)).digest("hex")}var cl=new Set(["Write","Edit","NotebookEdit"]);function Tr(n){if(!cl.has(n.toolName)||ml(n.toolResponse))return null;let e=pl(n.projectRoot,n.toolInput);if(!e)return null;let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let o=t.getActiveContextReceipt(n.projectRoot,n.sessionId,n.executionId),r=o?.canonicalAction?.verificationPlan??[];if(!o||r.length===0)return null;let i=[],s=[];for(let c of r){let l=ll({projectRoot:n.projectRoot,targetFile:e,kind:c.kind,mode:c.mode==="write"?"write":"check",required:c.required===!0,contextReceipt:o.contextHash}),d=`${o.contextHash}\0${n.toolUseId??e}\0${c.kind}\0${e}`,u=`policy-verification:${createHash("sha256").update(d).digest("hex")}`,p=Date.now();if(!l){let m=`verification_unavailable:${c.kind}`;t.upsertSessionObligation({obligationId:u,projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:n.executionId,kind:"evidence_contract",state:"degraded",payload:{subtype:"policy_verification",status:"unknown",verificationKind:c.kind,targetFile:e,contextReceipt:o.contextHash},reason:m,createdAt:p,updatedAt:p,resolvedAt:p}),s.push(c.kind);continue}let f={...l,obligationId:u,sessionId:n.sessionId,executionId:n.executionId,requestId:o.requestId};t.upsertSessionObligation({obligationId:u,projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:n.executionId,kind:"evidence_contract",state:"open",payload:{subtype:"policy_verification",status:"scheduled",verificationKind:c.kind,command:l.display,targetFile:e,contextReceipt:o.contextHash,required:c.required===!0},createdAt:p,updatedAt:p}),t.enqueueWork({idempotencyKey:u,kind:"verification.policy",projectRoot:n.projectRoot,sessionId:n.sessionId,payload:f,maxAttempts:2,nextAttemptAt:p}),i.push(l.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(`
29
- `)||null}finally{t.close();}}async function Cr(n,e){let t=dl(n,e.payload),o=await ul(t,n),r=t.kind==="typecheck"?vl(o.output,t.targetFile,n):[],i=Er({command:t.command,args:t.args}),s=openGlobalDevFlowDatabase();try{let a=bl(n),c=t.kind==="typecheck"?s.getPolicyVerificationBaseline(n,t.kind,i):null,l=c&&c.sourceRevision===a?c:null,d=l?r.filter(w=>!l.diagnosticHashes.includes(w)):[],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":t.kind==="typecheck"&&!l?u="unknown":t.kind==="typecheck"&&d.length===0?u="passed":u="failed";let p=createHash("sha256").update(o.output).digest("hex"),f=`verification-receipt:${Er({obligationId:t.obligationId,commandHash:i,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:p,diagnosticHashes:r,introduced:d,status:u})}`,m={status:u,kind:t.kind,command:t.display,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:p,diagnosticHashes:r,introducedDiagnosticHashes:d,baselineAvailable:l!==null,receiptId:f},v=s.getSessionObligation(n,t.sessionId,t.obligationId);if(v?.state==="open"&&(s.upsertSessionObligation({...v,payload:{...v.payload,status:u,outcome:m},updatedAt:Date.now()}),u!=="failed"&&s.resolveSessionObligation({projectRoot:n,sessionId:t.sessionId,obligationId:t.obligationId,state:u==="passed"?"satisfied":"degraded",receiptId:f,reason:u==="unknown"?"verification_result_unknown":u==="unavailable"?"verification_command_unavailable":void 0})),t.kind==="typecheck"&&o.exitCode===0&&s.upsertPolicyVerificationBaseline({projectRoot:n,kind:t.kind,commandHash:i,diagnosticHashes:[],sourceRevision:a,updatedAt:Date.now()}),wl(s,t,m),u==="failed"){let w=new Error(`Policy verification failed: ${t.display}`);throw w.category="policy_verification_failed",w}return m}finally{s.close();}}function ll(n){let e=fl(n.projectRoot),t=gl(n.projectRoot),o=e?.scripts??{},r={...e?.dependencies,...e?.devDependencies},i=null;if(n.kind==="formatter"&&(r.prettier||hl(n.projectRoot)))i=Ge(t,"prettier",[n.mode==="write"?"--write":"--check",n.targetFile],6e4);else if(n.kind==="typecheck"){let s=Yt(o,["typecheck","type-check","check:types"]);s?i=Vt(t,s,12e4):r.typescript&&existsSync(join(n.projectRoot,"tsconfig.json"))&&(i=Ge(t,"tsc",["--noEmit","--pretty","false"],12e4));}else if(n.kind==="lint"){let s=Yt(o,["lint"]);s&&(i=Vt(t,s,12e4));}else if(n.kind==="test"){let s=yl(n.projectRoot,n.targetFile);s&&r.vitest?i=Ge(t,"vitest",["run",s],12e4):s&&(r.jest||r["@jest/core"])&&(i=Ge(t,"jest",["--runTestsByPath",s],12e4));}else if(n.kind==="build"){let s=Yt(o,["build"]);s&&(i=Vt(t,s,18e4));}else n.kind==="generated_files"&&(i={command:"git",args:["diff","--check","--",n.targetFile],timeoutMs:3e4});return i?{kind:n.kind,...i,display:[i.command,...i.args].map(_l).join(" "),required:n.required,targetFile:n.targetFile,contextReceipt:n.contextReceipt}:null}function Vt(n,e,t){return n==="yarn"?{command:"yarn",args:["run",e],timeoutMs:t}:n==="pnpm"?{command:"pnpm",args:["run",e],timeoutMs:t}:n==="bun"?{command:"bun",args:["run",e],timeoutMs:t}:{command:"npm",args:["run",e],timeoutMs:t}}function Ge(n,e,t,o){return n==="pnpm"?{command:"pnpm",args:["exec",e,...t],timeoutMs:o}:n==="yarn"?{command:"yarn",args:[e,...t],timeoutMs:o}:n==="bun"?{command:"bunx",args:[e,...t],timeoutMs:o}:{command:"npx",args:["--no-install",e,...t],timeoutMs:o}}function dl(n,e){if(!e||typeof e!="object"||Array.isArray(e))throw Kt();let t=e,o=new Set(["npm","npx","pnpm","yarn","bun","bunx","git"]);if(!t.command||!o.has(t.command)||!Array.isArray(t.args)||!t.args.every(r=>typeof r=="string")||!t.obligationId||!t.sessionId||!t.kind||!t.targetFile||!t.contextReceipt||!t.display||!Number.isFinite(t.timeoutMs)||!Dr(n,t.targetFile))throw Kt();return t}function Kt(){let n=new Error("Policy verification work payload is invalid");return n.category="invalid_payload",n}function ul(n,e){return new Promise(t=>{let o=spawn$1(n.command,n.args,{cwd:e,shell:false,stdio:["ignore","pipe","pipe"],env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),r="",i=false,s=d=>{i||(i=true,t(d));},a=d=>{r=(r+String(d)).slice(-32768);};o.stdout.on("data",a),o.stderr.on("data",a);let c=false,l=setTimeout(()=>{c=true,o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),1e3).unref();},n.timeoutMs);o.on("error",d=>{clearTimeout(l),s({exitCode:null,timedOut:false,spawnError:true,output:`${r}
30
- ${d.message}`.slice(-32768)});}),o.on("close",d=>{clearTimeout(l),s({exitCode:d,timedOut:c,spawnError:false,output:r});});})}function pl(n,e){let t=e.file_path??e.notebook_path;if(typeof t!="string"||!t.trim())return null;let o=isAbsolute(t)?resolve(t):resolve(n,t);return Dr(n,o)?relative(n,o).split(sep).join("/"):null}function Dr(n,e){let t=isAbsolute(e)?resolve(e):resolve(n,e),o=relative(resolve(n),t);return o!==""&&o!==".."&&!o.startsWith(`..${sep}`)&&!isAbsolute(o)}function ml(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let e=n;return e.ok===false||e.success===false||e.isError===true||!!e.error}function fl(n){try{return JSON.parse(readFileSync$1(join(n,"package.json"),"utf8"))}catch{return null}}function gl(n){return existsSync(join(n,"pnpm-lock.yaml"))?"pnpm":existsSync(join(n,"yarn.lock"))?"yarn":existsSync(join(n,"bun.lockb"))||existsSync(join(n,"bun.lock"))?"bun":"npm"}function hl(n){return [".prettierrc",".prettierrc.json",".prettierrc.js",".prettierrc.cjs","prettier.config.js","prettier.config.cjs"].some(e=>existsSync(join(n,e)))}function Yt(n,e){return e.find(t=>typeof n[t]=="string"&&n[t].trim())??null}function yl(n,e){let t=e.replace(/\.[^.]+$/u,""),o=[".test.ts",".test.tsx",".spec.ts",".spec.tsx",".test.js",".spec.js"];for(let s of o){let a=`${t}${s}`;if(existsSync(join(n,a)))return a}let r=join(n,e.split("/").slice(0,-1).join("/")),i=e.split("/").at(-1)?.replace(/\.[^.]+$/u,"");if(!i||!existsSync(r))return null;try{return readdirSync$1(r).filter(s=>s.startsWith(`${i}.`)&&/\.(?:test|spec)\.[cm]?[jt]sx?$/u.test(s)).map(s=>relative(n,join(r,s)).split(sep).join("/"))[0]??null}catch{return null}}function vl(n,e,t){let o=e.split(sep).join("/"),r=resolve(t,e).split(sep).join("/"),i=n.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 wl(n,e,t){if(!e.executionId)return;let o=n.getSkillExecution(e.executionId);if(!o)return;let r=o.metadata&&typeof o.metadata=="object"?o.metadata:{},i=Array.isArray(r.policyVerificationOutcomes)?r.policyVerificationOutcomes:[];n.updateSkillExecution(e.executionId,{metadata:{...r,policyVerificationOutcomes:[...i,t]}});}function bl(n){try{let e=readFileSync$1(join(n,".git","HEAD"),"utf8").trim();return e.startsWith("ref:")?readFileSync$1(join(n,".git",e.slice(5).trim()),"utf8").trim():e}catch{return}}function Er(n){return createHash("sha256").update(JSON.stringify(n)).digest("hex")}function _l(n){return /^[A-Za-z0-9_./:@=-]+$/u.test(n)?n:JSON.stringify(n)}var Hl=600*1e3,Nl=2e3,Ll=250,Wl=2e3,ql=1e3,Ar=1024*1024,Ul=2*1024*1024,zl=6e4,Jl=100,Bl={Agent:"get_project_context",Bash:"get_project_context",Glob:"get_project_context",Grep:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function Gl(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e=n,t=typeof e.status=="string"?e.status:void 0;if(!(e.ok===false||e.success===false||e.isError===true||t==="failed"||t==="rejected"||t==="unavailable"||t==="warming"||!!e.error))return;let r=e.error;if(typeof r=="string"&&r.trim())return r;if(r&&typeof r=="object"){let i=r;if(typeof i.message=="string"&&i.message.trim())return i.message;if(typeof i.code=="string"&&i.code.trim())return i.code}return t?`Tool response status: ${t}`:"Tool response reported failure"}function Or(n){return /timeout|timed out|deadline|warming/i.test(n)?"timeout":/unavailable|not active|unknown tool|not found|not registered|route not found/i.test(n)?"unavailable":"failed"}function Pr(n,e,t,o,r){let i=n.recordDomainActionOutcome;typeof i=="function"&&i.call(n,e,t,o,r);}function Vl(n){switch(n){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 tn(n){return typeof n=="string"&&n.trim().length>0}function Kl(n,e,t=process.env,o){if(!n.startsWith("mcp__devflow__"))return e;let r=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};if(tn(r.projectRoot))return r;let i=tn(t.CLAUDE_PROJECT_DIR)?t.CLAUDE_PROJECT_DIR:o;return tn(i)&&(r.projectRoot=i),r}var nn=class{constructor(e,t){this.socketIdentity=null;this.pidIdentity=null;this.server=null;this.activeSessionIds=new Set;this.eventMap=[];this.idleTimer=null;this.telemetryFlushTimer=null;this.successfulTelemetryOperations=0;this.shutdownPromise=null;this.explicitMemoryGate=null;this.memoryWarmup=null;this.explicitIntentFlush=null;this.hostRuntime=null;this.memoryTurnSpoolTimer=null;this.sessionFinalizeSpoolTimer=null;this.projectRoot=e,this.socketPath=getDaemonSocketPath(e),this.pidPath=getDaemonPidPath(e),this.telemetry=new U,this.runtimeStore=new M(this.projectRoot),this.serverManager=new Se(e),this.hookRuntime=sr(e),this.hookHealth=new Be(e),this.hookHandlers=lr({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=>Wt(o,this.hookRuntime,this.hostRuntime??{hostId:"unresolved",capabilities:new Map,profiles:new Set(["minimal","standard","strict"])}).policy}),this.initialSessionInput=t,this.workRuntime=new ze({projectRoot:e,handlers:{...wr(e),"memory.explicit_commit":async({item:o})=>{await this.persistMemoryTurnItem(o.payload);},"memory.turn_capture":async({item:o})=>{await this.persistMemoryTurnItem(o.payload);},"memory.explicit_enrichment":async({item:o})=>{let r=o.payload;if(typeof r?.observationId!="string"||!r.observationId)throw new k("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 ce({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 k("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 Cr(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 k("invalid_payload","Learning analysis identity is incomplete");let i=openGlobalDevFlowDatabase();try{let s=await(await this.getMemoryGate()).listLearningEvidence(r.sessionId),a=zt({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})=>{o.sessionId&&this.enqueueLearningAnalysisIfReady(r,o.sessionId);}});}async start(){this.hostRuntime=await cr(this.projectRoot),mkdirSync(dirname(this.socketPath),{recursive:true,mode:448}),await this.cleanStaleStartupResources(),this.server=createServer(e=>this.handleConnection(e));try{await this.listen(),this.writePidFile(),Fn(this.projectRoot,process.pid);}catch(e){throw await this.closeServer(),this.cleanupOwnedResources(),e}if(this.server.on("error",e=>{console.error("[devflow-daemon] Server error:",e.message);}),console.error("[devflow-daemon] Listening on",this.socketPath),await this.telemetry.flushAndAggregate(),this.telemetryFlushTimer=setInterval(()=>{this.flushTelemetry();},zl),this.telemetryFlushTimer.unref(),prepareEmbeddingModel().then(e=>{console.error(`[devflow-daemon] Embedding model ready (${e.source}) at ${e.cacheRoot}`);}).catch(e=>{console.error("[devflow-daemon] Embedding model unavailable; lexical retrieval remains active:",e.message);}),this.workRuntime.start(),this.initialSessionInput){let e=this.initialSessionInput;this.initialSessionInput=void 0,this.handleRequest({type:"session-start",input:e});}this.drainSessionStartSpool(),this.scheduleMemoryTurnSpoolDrain(0),this.scheduleSessionFinalizeSpoolDrain(0),this.resetIdleTimer();}handleConnection(e){let t="",o=false,r=false,i=0,s=Promise.resolve();e.setEncoding("utf8");let a=()=>{r||(r=true,clearTimeout(c),e.destroy());},c=setTimeout(()=>{a();},Nl).unref(),l=async d=>{if(!r){r=true,clearTimeout(c);try{await this.writeFrame(e,d);}catch{}finally{e.destroy();}}};e.on("data",d=>{if(r)return;t+=d;let u=t.split(`
31
- `);if(t=u.pop()??"",Buffer.byteLength(t,"utf8")>Ar){a();return}if(u.length===0)return;let p=0;for(let f of u){let m=Buffer.byteLength(f,"utf8");if(m>Ar){a();return}p+=m+1;}if(i+p>Ul){a();return}i+=p,s=s.then(async()=>{for(let f of u){if(r)return;if(!o){let m;try{m=JSON.parse(f);}catch{await l({error:"handshake_invalid"});return}if(m?.type!=="hello"||typeof m.rootPath!="string"){await l({error:"handshake_invalid"});return}if(m.rootPath!==this.projectRoot){await l({error:"handshake_root_mismatch",expected:this.projectRoot});return}o=true,clearTimeout(c),this.resetIdleTimer();continue}if(f.trim())try{let m=JSON.parse(f),v=await this.handleRequest(m);v!==null&&!r&&await this.writeFrame(e,v);}catch(m){r||await this.writeFrame(e,{error:m.message});}}}).catch(()=>{a();}).finally(()=>{i-=p;});}),e.on("close",()=>clearTimeout(c)),e.on("error",()=>{});}writeFrame(e,t){return new Promise((o,r)=>{if(e.destroyed||!e.writable){r(new Error("Socket is not writable"));return}let i=false,s=true,a=false,c=setTimeout(()=>{e.destroy(),d(new Error("Timed out writing daemon response"));},ql),l=()=>{clearTimeout(c),e.off("close",u),e.off("error",p),e.off("drain",f);},d=v=>{a||!v&&(!i||!s)||(a=true,l(),v?r(v):o());},u=()=>d(new Error("Socket closed during write")),p=v=>d(v),f=()=>{s=true,d();};e.once("close",u),e.once("error",p),e.write(`${JSON.stringify(t)}
32
- `,v=>{if(v){d(v);return}i=true,d();})||(s=false,e.once("drain",f));})}async cleanStaleStartupResources(){let e=this.getPathIdentity(this.socketPath);if(e){if(await this.isSocketAcceptingConnections())throw new Error(`Daemon socket already active for ${this.projectRoot}`);this.removePathIfOwned(this.socketPath,e,"stale socket");}let t=this.getPathIdentity(this.pidPath);t&&this.removePathIfOwned(this.pidPath,t,"stale PID file");}getPathIdentity(e){try{let t=lstatSync(e);return {dev:t.dev,ino:t.ino}}catch(t){if(t.code==="ENOENT")return null;throw t}}pathMatchesIdentity(e,t){if(!t)return false;try{let o=this.getPathIdentity(e);return o?.dev===t.dev&&o.ino===t.ino}catch(o){return console.error("[devflow-daemon] Failed to verify path ownership:",o.message),false}}writePidFile(){let e=openSync(this.pidPath,"wx",384);try{writeFileSync(e,`${process.pid}
33
- `);let t=fstatSync(e);this.pidIdentity={dev:t.dev,ino:t.ino};}finally{closeSync(e);}}removePathIfOwned(e,t,o,r){try{return !this.pathMatchesIdentity(e,t)||r!==void 0&&readFileSync(e,"utf8")!==r||!this.pathMatchesIdentity(e,t)?!1:(unlinkSync(e),!0)}catch(i){return i.code!=="ENOENT"&&console.error(`[devflow-daemon] Failed to remove ${o}:`,i.message),false}}isSocketAcceptingConnections(){return new Promise((e,t)=>{let o=createConnection(this.socketPath),r=setTimeout(()=>{o.destroy(),t(new Error(`Timed out probing daemon socket ${this.socketPath}`));},Ll),i=s=>{clearTimeout(r),o.destroy(),e(s);};o.once("connect",()=>i(true)),o.once("error",s=>{let a=s.code;a==="ENOENT"||a==="ECONNREFUSED"?i(false):(clearTimeout(r),t(s));});})}listen(){return new Promise((e,t)=>{let o=this.server;if(!o){t(new Error("Daemon server is not initialized"));return}let r=s=>{o.off("listening",i),t(s);},i=()=>{o.off("error",r);try{let s=this.getPathIdentity(this.socketPath);if(!s)throw new Error(`Daemon socket missing after listen: ${this.socketPath}`);this.socketIdentity=s,e();}catch(s){t(s);}};o.once("error",r),o.once("listening",i),o.listen(this.socketPath);})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!(this.activeSessionIds.size>0)&&(this.idleTimer=setTimeout(()=>{let e=openGlobalDevFlowDatabase();try{if(e.listWorkflowWorkers(this.projectRoot,{states:["leased","starting","running","reported","verifying","merge_ready"],limit:1}).length>0){console.error("[devflow-daemon] Idle timeout deferred for active workflow worker"),this.resetIdleTimer();return}}finally{e.close();}console.error("[devflow-daemon] Idle timeout, exiting"),this.shutdown();},Hl).unref());}async handleRequest(e){let t=this.hostRuntime;if(!t)return this.hookFailureResponse(e.type,{enabled:false,policy:"fail_open",reason:"host_adapter_not_ready",fallback:"host_event_continues_without_devflow_handler"});let o=Wt(e.type,this.hookRuntime,t);if(!o.enabled)return this.hookFailureResponse(e.type,o);let r=Date.now();try{let i=ur(e.type,await dr({registry:this.hookHandlers,requestType:e.type,rawInput:e.input??"",acknowledgementBudgetMs:this.hookRuntime.acknowledgementBudgetMs})),s="status"in i&&i.status==="degraded";if(s){let a="reason"in i?String(i.reason):"handler_degraded";this.hookHealth.recordFailure(e.type,t.hostId,"degraded",a);}else this.hookHealth.recordSuccess(e.type,t.hostId);return W("hook_handler_outcome",{success:!s,projectRoot:this.projectRoot,host:t.hostId,handler:e.type,degraded:s},Date.now()-r),i}catch(i){let s=pr(i);return this.hookHealth.recordFailure(e.type,t.hostId,s.category,s.reason),W("hook_handler_outcome",{success:false,projectRoot:this.projectRoot,host:t.hostId,handler:e.type,category:s.category,reason:s.reason},Date.now()-r),this.hookFailureResponse(e.type,o,i)}}async drainSessionStartSpool(){for(;;){let e=Ko(this.projectRoot);if(!e)return;try{let t=await this.handleRequest({type:"session-start",input:e.input});if(t&&"status"in t&&t.status==="degraded")throw new Error(`session_start_degraded:${String(t.reason??"unknown")}`);Yo(e),console.error(`[devflow-daemon] SessionStart accepted from durable spool: ${e.receiptId}`);}catch(t){Xo(e),console.error("[devflow-daemon] SessionStart spool deferred:",t.message);return}}}hookFailureResponse(e,t,o){let r=o instanceof Error?o.message:t.reason??"hook_handler_unavailable",i=t.fallback??(t.policy==="enqueue_and_open"?"durable_background_processing":"host_event_continues");return e==="pre-tool-use"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t.policy==="fail_closed"?"deny":"allow",permissionDecisionReason:r,additionalContext:`DevFlow hook degraded: ${r}; fallback=${i}.`}}:e==="user-prompt-submit"?{hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",additionalContext:`DevFlow hook degraded: ${r}; fallback=${i}. Do not claim unreceipted work completed.`}}:{status:"degraded",reason:r,fallback:i}}async handlePreToolUse(e){try{if(!e||e.trim()==="")return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};let t=JSON.parse(e);t.tool_input=Kl(t.tool_name,t.tool_input,process.env,this.projectRoot);let o=this.trackSession(t.session_id),r="";if(t.tool_name==="Skill"){let I=t.tool_input?.skill,E=I?Pe(I):null;E&&(r=this.startSkillExecution(o,E));}let i=this.runtimeStore.get(o);t.tool_name.startsWith("mcp__devflow__")&&(t.tool_input._devflow_session_id=o,t.tool_input._devflow_execution_id=i?.executionId??o,i?.skillName&&(t.tool_input._devflow_active_skill=i.skillName),t.tool_use_id&&(t.tool_input._devflow_tool_use_id=t.tool_use_id));let s=t.tool_name.startsWith("mcp__"),a=s?t.tool_name.replace(/^mcp__[^_]+__/,""):void 0,c=new z(this.projectRoot,o,i?.executionId),l=c.getPhase(),d=Bo({toolName:t.tool_name,toolInput:t.tool_input,projectRoot:this.projectRoot}),u=d?{permissionDecision:"deny",reason:d}:c.evaluate(t.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 I=p.hookSpecificOutput,E=typeof I.additionalContext=="string"?I.additionalContext:"";I.additionalContext=E?`${E}
34
- ${r}`:r;}t.tool_name.startsWith("mcp__devflow__")&&(p.hookSpecificOutput.updatedInput=t.tool_input);let f={...t.tool_input};delete f._devflow_session_id,delete f._devflow_execution_id,delete f._devflow_tool_use_id;let m=i?.executionId??o,w={eventId:pe(o,t.tool_use_id),executionId:m,sessionId:o,projectRoot:this.projectRoot,toolUseId:t.tool_use_id,timestamp:Date.now(),toolName:t.tool_name,toolType:s?"mcp":t.tool_name==="Agent"?"subagent":"direct",isMcpTool:s,mcpToolName:a,mcpEnforced:s&&l==="context_gathering",mcpFallback:!s&&l==="context_gathering",kind:Vl(t.tool_name),input:f,duration:0,blocked:p&&p.hookSpecificOutput?.permissionDecision==="deny"},S=await this.telemetry.sendEvent({...w,blockReason:w.blocked?d?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0,error:w.blocked?d?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0});return S&&!w.blocked&&(this.eventMap.push({toolName:t.tool_name,toolUseId:t.tool_use_id,eventId:S,sessionId:o,timestamp:w.timestamp}),this.noteTelemetryOperation()),S&&w.blocked&&await this.telemetry.completeEvent({eventId:S,sessionId:o,error:d?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED",duration:Date.now()-w.timestamp,completedAt:Date.now()}),p}catch{return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}}trackSession(e){let t=e?.trim()||(this.activeSessionIds.size===1?[...this.activeSessionIds][0]:"");if(!t)throw new Error("session_id_required");return this.registerSession(t),t}registerSession(e){this.activeSessionIds.has(e)||(this.activeSessionIds.size===0&&Re(this.projectRoot,{bypassCount:0}),this.activeSessionIds.add(e),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.serverManager.addRef(e),this.telemetry.sendSessionStart(e,this.projectRoot,Date.now()).catch(()=>{})),this.runtimeStore.registerSession(e);}startSkillExecution(e,t,o){let r=this.runtimeStore.get(e)?.executionId,i=this.runtimeStore.startExecution(e,t,wn(t));return i.executionId&&i.executionId!==r&&this.telemetry.sendExecutionStart(i.executionId,e,t,i.lastActivityAt,this.projectRoot,i.requiredMcpTools).catch(()=>{}),bn(t,this.projectRoot,o)}async handleSessionStart(e){try{let t=JSON.parse(e);if(typeof t.session_id!="string"||!t.session_id.trim())return {error:"session_id_required"};let o=t.session_id.trim();this.registerSession(o);let r=`session-start:${createHash("sha256").update(`${this.projectRoot}\0${o}`).digest("hex").slice(0,24)}`,i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50}),s="pending";try{s=i.enqueueWork({idempotencyKey:r,kind:"session.bootstrap",projectRoot:this.projectRoot,sessionId:o,payload:{sessionId:o}}).state;}finally{i.close();}return {status:s==="completed"?"completed":"accepted",receiptId:r,workState:s}}catch{return {error:"session_start_invalid"}}}popEventFromMap(e,t,o){let r=this.eventMap.filter(s=>s.toolName===e&&s.sessionId===t);if(r.length===0)return null;let i=o?r.find(s=>s.toolUseId===o):r.sort((s,a)=>s.timestamp-a.timestamp)[0];return i?(this.eventMap=this.eventMap.filter(s=>s.eventId!==i.eventId),i):null}enforcePostToolUse(e){if(!Bl[e])return null;let t=Math.floor(Date.now()/1e3),o=at(this.projectRoot,s=>t-(s.lastMcpCall??0)<30?s:{...s,bypassCount:(s.bypassCount??0)+1});if(!o.applied||!o.changed)return null;let r=o.receipt.bypassCount??0;if(r===1)return null;let i;switch(e){case "Agent":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u4F7F\u7528\u4E86 Agent \u5B50\u4EE3\u7406\u6267\u884C\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Bash":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Bash \u547D\u4EE4\u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Glob":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Glob \u5339\u914D\u6587\u4EF6\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Grep":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Grep \u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "WebSearch":case "WebFetch":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86\u7F51\u7EDC\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_knowledge MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;default:i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u8BF7\u4F7F\u7528 DevFlow MCP \u5DE5\u5177\u66FF\u4EE3\u76F4\u63A5\u8C03\u7528\u3002`;}return r>=3?i=`${i} \u5DF2\u8FBE\u5230\u6700\u5927\u8FDD\u89C4\u6B21\u6570\uFF0C\u540E\u7EED\u7ED5\u8FC7\u5C06\u88AB\u786C\u963B\u6B62\u3002`:r>=2?i=`${i} \u4E0B\u6B21\u8FDD\u89C4\u5C06\u88AB\u963B\u6B62\u3002`:i=`${i} \u8BF7\u7ACB\u5373\u7EA0\u6B63\u3002`,i}async handlePostToolUse(e){if(!e)return null;let t;try{t=JSON.parse(e);}catch{return null}let o=t.tool_name||"",r=t.tool_input||{},i=t.tool_response,s=this.trackSession(t.session_id);if(fo({projectRoot:this.projectRoot,sessionId:s,executionId:this.runtimeStore.get(s)?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:t.tool_use_id}),o==="Skill"){let _=r?.skill,h=_?Pe(_):null;h&&(this.startSkillExecution(s,h),Re(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0}));}if(o.startsWith("mcp__")){let _=this.runtimeStore.get(s),h=new z(this.projectRoot,s,_?.executionId??s);h.recordMcpCall();let g=Gl(i);Pr(h,o.replace(/^mcp__[^_]+__/,""),g?Or(g):"succeeded",g,t.tool_use_id);}let a=this.popEventFromMap(o,s,t.tool_use_id);if(a){let _=typeof i=="string"?i:JSON.stringify(i),h=_.length>5e3?{_truncated:true,_originalSize:_.length,text:_.slice(0,5e3)}:i,g=Date.now()-a.timestamp;await this.telemetry.completeEvent({eventId:a.eventId,sessionId:s,output:h,duration:g,completedAt:Date.now()})&&this.noteTelemetryOperation();}let c=typeof i=="object"&&i!==null?i:null,l=c?.exitCode,d=c?.stderr,u=/^\s*(ls|cat|pwd|cd|echo|head|tail|wc|which|whoami|date|env|printenv|id|hostname|uname)\b/,p=r.command||"",f=JSON.stringify(i),m=Buffer.byteLength(f,"utf8"),v=this.countResults(i),w,S,I=true;if(o.startsWith("mcp__"))w="mcp_call",S={mcpTool:o.replace(/^mcp__[^_]+__/,""),query:r.query??null,resultCount:v,resultSizeBytes:m};else if(o==="Read"||o==="Write"||o==="Edit")w=o==="Read"?"file_read":"file_write",S={filePath:r.file_path??null,fileContentSize:m};else if(o==="Bash"){let _=u.test(p),h=l!==void 0&&l!==0;I=!_||h,w=h?"bash_error":"bash_command",S={command:p||o,exitCode:l??null,stderr:d??null};}else o==="Agent"?(w="subagent",S={subagentType:r.subagent_type??null,description:typeof r.description=="string"?r.description.slice(0,200):null}):o==="WebSearch"||o==="WebFetch"?(w=o==="WebSearch"?"web_search":"web_fetch",S={query:typeof r.query=="string"?r.query.slice(0,200):null}):(I=false,w="tool_use",S={});if(I){let _={id:t.tool_use_id?`memory:${pe(s,t.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:s,tool:o,kind:w,payload:S,command:p||void 0,exitCode:l,stderr:d??void 0,durationMs:0,createdAt:Date.now()};this.postMemoryEvent(_);}let E=io({toolName:o,toolResponse:i,sessionId:s,toolUseId:t.tool_use_id,runtimeStore:this.runtimeStore}),C=this.runtimeStore.get(s),P=Tr({projectRoot:this.projectRoot,sessionId:s,executionId:C?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:t.tool_use_id}),N=this.enforcePostToolUse(o);N&&console.error("[devflow-daemon] Enforcement:",N);let D=[E,P,N].filter(_=>!!_).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 nd(e,t){return !!e.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${t}`)}function od(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 rd(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 id=[/\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],sd=[/\b(?:migration|upgrade|dependency|dependencies|generated files?|write all|rewrite)\b/iu,/(?:迁移|升级|依赖|生成文件|批量写入)/u];function Xt(e){let t=`${e.instruction}
30
+ ${JSON.stringify(e.trigger)}`,n=[];id.some(r=>r.test(t))&&n.push("high_risk_operation"),sd.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 ad=new Set(["project_convention","user_preference","decision_made","config_discovery"]);function en(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(!cd(l)){d+=1;continue}let u=jr(l),m=dd(l,t?.skillName),g=Fr(l),p=md(e.payload.projectRoot,u,l.facetKey??l.semanticKey??l.id,m),f=e.database.getLearningCandidate(p),I=Xt({scope:"project",kind:u,instruction:g,trigger:m});e.database.upsertLearningCandidate({id:p,projectRoot:e.payload.projectRoot,scope:"project",kind:u,trigger:m,instruction:g,confidence:ld(l),manualOnly:I.manualOnly,risk:I.risk});f&&f.instruction!==g&&e.database.addLearningCandidateEvidence({id:Mr(p,e.payload.sessionId,l.id,"contradicting"),candidateId:p,projectRoot:e.payload.projectRoot,sessionId:e.payload.sessionId,executionId:e.payload.executionId,memoryObservationId:l.id,sourceType:"correction",polarity:"contradicting",outcome:i,evidenceHash:Or(p,e.payload,l,"contradicting"),receipt:e.payload.closureReceipt,payload:{previousInstruction:f.instruction,replacementInstruction:g,projectRevision:e.payload.projectRevision},createdAt:l.createdAt});let R=e.database.addLearningCandidateEvidence({id:Mr(p,e.payload.sessionId,l.id,"supporting"),candidateId:p,projectRoot:e.payload.projectRoot,sessionId:e.payload.sessionId,executionId:e.payload.executionId,memoryObservationId:l.id,outcomeId:o?.id??r?.id,sourceType:ud(l),polarity:"supporting",outcome:i,evidenceHash:Or(p,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:I.reasons},createdAt:l.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 cd(e){return !(!ad.has(e.type)||e.source!=="explicit_intent"&&e.source!=="manual"&&e.evidenceStatus!=="verified"||!e.narrative.trim()&&!e.title.trim())}function jr(e){return e.type==="decision_made"?"workflow":e.type==="user_preference"&&(e.semanticValue.startsWith("--")||e.tools.length>0)?"tool_preference":"convention"}function dd(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 Fr(e){return (e.narrative.trim()||e.title.trim()).replace(/\s+/gu," ").slice(0,1200)}function ld(e){let t=e.source==="explicit_intent"?.08:0;return Math.max(0,Math.min(1,e.confidence+t))}function ud(e){return e.semanticPolarity==="negative"?"correction":jr(e)==="tool_preference"?"tool_preference":e.source==="explicit_intent"?"memory":"convention"}function md(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 Mr(e,t,n,o){return `learning-evidence:${createHash("sha256").update(`${e}\0${t}\0${n}\0${o}`).digest("hex").slice(0,24)}`}function Or(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:Fr(n),polarity:o})).digest("hex")}var re=3e4,on=1e3,Td=new Set(["git","npm","pnpm","yarn"]);function $r(e){return {"workflow.worker_start":async({item:t})=>Ad(e,t),"workflow.worker_monitor":async({item:t})=>Cd(e,t),"workflow.worker_verify":async({item:t})=>Dd(e,t),"workflow.worker_merge":async({item:t})=>Md(e,t),"workflow.worker_cleanup":async({item:t})=>Od(e,t)}}async function Ad(e,t){await ke(e,t,async(n,o)=>{if(o.state==="running"||o.state==="starting"){tn(n,o);return}if(o.state!=="planned")return;let r=`worker-plane:${process.pid}`;n.leaseWorkflowWorker(e,o.workerId,r,re);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=Lr(o.workerId),a=Pd(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=ie(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 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 g=openGlobalDevFlowDatabase();try{g.heartbeatWorkflowWorker(e,o.workerId,r,re);}catch{}finally{g.close();}}});jd(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()+re}),tn(n,o),m.completion.finally(()=>{let g=openGlobalDevFlowDatabase();try{tn(g,o,Date.now());}finally{g.close();}});});}async function Cd(e,t){await ke(e,t,async(n,o)=>{if(o.state!=="running"&&o.state!=="starting")return;let r=Lr(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=ie(o.handoff.actionId,"actionId");n.reportHostAction({actionId:d,projectRoot:e,report:{workerId:o.workerId,handoff:c},evidenceHash:qr(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=Fd(r),s=typeof i?.pid=="number"?i.pid:void 0;if(s&&Hd(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=ie(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,re),Wr("worker_running",on)):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=ie(o.handoff.actionId,"actionId");n.failHostAction({actionId:a,projectRoot:e,report:{reason:"worker_exited_without_handoff"}});});}async function Dd(e,t){await ke(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=ie(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=Nr(o),c=new GraderRegistry,d=await Hr(n,o,async()=>verifyWorkerOutput({workerId:o.workerId,projectRoot:e,worktreePath:o.worktreePath,baseRevision:o.baseRevision,parentRevision:await $d(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 Md(e,t){await ke(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=ie(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:qr({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 Hr(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 Od(e,t){await ke(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 Wr(`cleanup_${i.reason??"refused"}`,3e4)});}async function Hr(e,t,n){let o=t.leaseOwner;if(!o)return n();let r=setInterval(()=>{try{e.heartbeatWorkflowWorker(t.projectRoot,t.workerId,o,re);}catch{}},Math.floor(re/3));r.unref();try{return await n()}finally{clearInterval(r);}}async function ke(e,t,n){let o=Nd(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 Pd(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=Nr(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 Nr(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"||!Td.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 Lr(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 jd(e,t){writeJsonAtomic(e.statusFile,t);}function Fd(e){try{return JSON.parse(readFileSync$1(e.statusFile,"utf8"))}catch{return null}}function tn(e,t,n=Date.now()+on){e.enqueueWork({idempotencyKey:`workflow-worker-monitor:${t.workerId}:${Math.floor(n/on)}`,kind:"workflow.worker_monitor",projectRoot:t.projectRoot,payload:{workerId:t.workerId},nextAttemptAt:n,maxAttempts:1e3});}async function $d(e){let{gitRevision:t}=await import('@devflow-tools/workflow-engine');return t(e,"HEAD")}function Hd(e){try{return process.kill(e,0),!0}catch{return false}}function Wr(e,t){return Object.assign(new Error(e),{category:e,retryAfterMs:t,retryWithoutAttempt:true})}function Nd(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 ie(e,t){if(typeof e!="string"||!e.trim())throw new x("worker_identity_missing",`Worker ${t} is missing`);return e}function qr(e){return createHash("sha256").update(JSON.stringify(e)).digest("hex")}var qd=new Set(["Write","Edit","NotebookEdit"]);function Jr(e){if(!qd.has(e.toolName)||Gd(e.toolResponse))return null;let t=Jd(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=Ud({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")}`,m=Date.now();if(!d){let p=`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:p,createdAt:m,updatedAt:m,resolvedAt:m}),s.push(c.kind);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:m,updatedAt:m}),n.enqueueWork({idempotencyKey:u,kind:"verification.policy",projectRoot:e.projectRoot,sessionId:e.sessionId,payload:g,maxAttempts:2,nextAttemptAt:m}),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 Gr(e,t){let n=zd(e,t.payload),o=await Bd(n,e),r=n.kind==="typecheck"?Xd(o.output,n.targetFile,e):[],i=zr({command:n.command,args:n.args}),s=openGlobalDevFlowDatabase();try{let a=el(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 m=createHash("sha256").update(o.output).digest("hex"),g=`verification-receipt:${zr({obligationId:n.obligationId,commandHash:i,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:m,diagnosticHashes:r,introduced:l,status:u})}`,p={status:u,kind:n.kind,command:n.display,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:m,diagnosticHashes:r,introducedDiagnosticHashes:l,baselineAvailable:d!==null,receiptId:g},f=s.getSessionObligation(e,n.sessionId,n.obligationId);if(f?.state==="open"&&(s.upsertSessionObligation({...f,payload:{...f.payload,status:u,outcome:p},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()}),Zd(s,n,p),u==="failed"){let I=new Error(`Policy verification failed: ${n.display}`);throw I.category="policy_verification_failed",I}return p}finally{s.close();}}function Ud(e){let t=Vd(e.projectRoot),n=Kd(e.projectRoot),o=t?.scripts??{},r={...t?.dependencies,...t?.devDependencies},i=null;if(e.kind==="formatter"&&(r.prettier||Qd(e.projectRoot)))i=rt(n,"prettier",[e.mode==="write"?"--write":"--check",e.targetFile],6e4);else if(e.kind==="typecheck"){let s=an(o,["typecheck","type-check","check:types"]);s?i=rn(n,s,12e4):r.typescript&&existsSync(join(e.projectRoot,"tsconfig.json"))&&(i=rt(n,"tsc",["--noEmit","--pretty","false"],12e4));}else if(e.kind==="lint"){let s=an(o,["lint"]);s&&(i=rn(n,s,12e4));}else if(e.kind==="test"){let s=Yd(e.projectRoot,e.targetFile);s&&r.vitest?i=rt(n,"vitest",["run",s],12e4):s&&(r.jest||r["@jest/core"])&&(i=rt(n,"jest",["--runTestsByPath",s],12e4));}else if(e.kind==="build"){let s=an(o,["build"]);s&&(i=rn(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(tl).join(" "),required:e.required,targetFile:e.targetFile,contextReceipt:e.contextReceipt}:null}function rn(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 rt(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 zd(e,t){if(!t||typeof t!="object"||Array.isArray(t))throw sn();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)||!Vr(e,n.targetFile))throw sn();return n}function sn(){let e=new Error("Policy verification work payload is invalid");return e.category="invalid_payload",e}function Bd(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 Jd(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 Vr(e,o)?relative(e,o).split(sep).join("/"):null}function Vr(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 Gd(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 Vd(e){try{return JSON.parse(readFileSync$1(join(e,"package.json"),"utf8"))}catch{return null}}function Kd(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 Qd(e){return [".prettierrc",".prettierrc.json",".prettierrc.js",".prettierrc.cjs","prettier.config.js","prettier.config.cjs"].some(t=>existsSync(join(e,t)))}function an(e,t){return t.find(n=>typeof e[n]=="string"&&e[n].trim())??null}function Yd(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 Xd(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 Zd(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 el(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 zr(e){return createHash("sha256").update(JSON.stringify(e)).digest("hex")}function tl(e){return /^[A-Za-z0-9_./:@=-]+$/u.test(e)?e:JSON.stringify(e)}function Qr(e){let t=Date.now(),n=_l(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 k=dl(i,s);return {artifact:pl(s),queryPlan:fl(k),memoryIdentity:Kr(s),reused:!0}}let a=yl(o.rawPrompt,o.command),c=buildRetrievalTaskPlan({query:a,parsedIntent:parseIntent(a,{segmentation:"regex"}),targetAnchors:gl(o.rawPrompt),activeSkill:o.activeSkill,command:o.command}),d=`turn:${Se(`${e.sessionId}\0${r}`)}`,l=`request:${Se(`${n}\0${e.sessionId}\0${d}`)}`,u={projectRoot:n,projectId:`project:${Se(n)}`,hostId:o.hostId,sessionId:e.sessionId,turnId:d,requestId:l},m=[{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(k=>({source:"target_anchor",field:"target",value:k,reason:"explicit_prompt_target",confidence:1}))],g={identity:u,version:1,rawPrompt:o.rawPrompt,normalizedPrompt:vl(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:hl(o.rawPrompt),classificationEvidence:m,sourceEventIds:[o.sourceEventId??`host-event:${r.slice(0,24)}`],sourceHash:r,createdAt:o.timestamp},p={...g,artifactHash:wl(g)},f=buildChannelQueryPlan({artifact:p,taskPlan:c,expandedTerms:e.expandedTerms});i.appendTaskIntentArtifact(ul(p)),i.appendChannelQueryPlan(ml(f));let I=ll(i,p);return emitSemanticControlLog({event:"host.prompt.normalized",identity:u,level:"info",timestamp:Date.now(),data:{sourceHash:r,command:p.command,activeSkill:p.activeSkill,rawPromptBytes:Buffer.byteLength(p.rawPrompt)}}),emitSemanticControlLog({event:"intent.artifact.created",identity:u,level:"info",timestamp:Date.now(),data:{artifactHash:p.artifactHash,intent:p.intent,action:p.action,evidence:p.classificationEvidence,entityCount:p.entities.length,targetCount:p.targetAnchors.length}}),emitSemanticControlLog({event:"intent.artifact.persisted",identity:u,level:"info",timestamp:Date.now(),data:{artifactHash:p.artifactHash,version:p.version,sourceHash:p.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(k=>k.requirement)}}),emitSemanticControlLog({event:"terminal.transition.persisted",identity:u,level:"info",timestamp:Date.now(),data:{state:"intent_bound",receiptId:I,sourceIntentHash:p.artifactHash}}),{artifact:p,queryPlan:f,memoryIdentity:Kr(p),reused:!1}}finally{i.close();}}function dl(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 ll(e,t){let n=e.getLatestTerminalTransition(t.identity.projectRoot,t.identity.sessionId,t.identity.turnId);if(n)return n.receiptId;let o=`terminal:${Se(`${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:${Se(`${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 ml(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 pl(e){return {identity:Yr(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 fl(e){return {identity:Yr(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 Yr(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 Kr(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 gl(e){let t=e.match(/(?:^|[\s`'"(])((?:\.{0,2}\/)?(?:[A-Za-z0-9_@.-]+\/)+[A-Za-z0-9_@.-]+(?:\.[A-Za-z0-9]+)?)/gu)??[];return Xr(t.map(n=>n.trim().replace(/^[`'"(]+|[`'"),.;:,。;:]+$/gu,"")).filter(n=>!n.startsWith("/")||/\.[A-Za-z0-9]+$/u.test(n))).slice(0,16)}function hl(e){let t=e.match(/--[a-z0-9][a-z0-9-]*(?:=[^\s,。;;]+)?/giu)??[];return Xr(t.map(n=>n.normalize("NFKC"))).slice(0,16)}function yl(e,t){return t&&e.trimStart().replace(new RegExp(`^\\/${Il(t)}\\b`,"iu"),"").trim()||e.trim()}function vl(e){return e.normalize("NFKC").replace(/\s+/gu," ").trim().slice(0,4e3)}function Xr(e){return [...new Set(e.filter(Boolean))]}function _l(e){let t=resolve(e);try{return realpathSync(t)}catch{return t}}function wl(e){return createHash("sha256").update(un(e)).digest("hex")}function Se(e){return createHash("sha256").update(e).digest("hex").slice(0,24)}function un(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(un).join(",")}]`;if(!e||typeof e!="object")return JSON.stringify(String(e));let t=e;return `{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${un(t[n])}`).join(",")}}`}function Il(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}var Hl=600*1e3,Nl=2e3,Ll=250,Wl=2e3,ql=1e3,ei=1024*1024,Ul=2*1024*1024,zl=6e4,Bl=100,Jl={Agent:"get_project_context",Bash:"get_project_context",Glob:"get_project_context",Grep:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function Gl(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 ti(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 ni(e,t,n,o,r){let i=e.recordDomainActionOutcome;typeof i=="function"&&i.call(e,t,n,o,r);}function Vl(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 fn(e){return typeof e=="string"&&e.trim().length>0}function Kl(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(fn(r.projectRoot))return r;let i=fn(n.CLAUDE_PROJECT_DIR)?n.CLAUDE_PROJECT_DIR:o;return fn(i)&&(r.projectRoot=i),r}var gn=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 X,this.runtimeStore=new H(this.projectRoot),this.serverManager=new De(t),this.hookRuntime=Sr(t),this.hookHealth=new ot(t),this.hookHandlers=Er({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=>Yt(o,this.hookRuntime,this.hostRuntime??{hostId:"unresolved",capabilities:new Map,profiles:new Set(["minimal","standard","strict"])}).policy}),this.initialSessionInput=n,this.workRuntime=new tt({projectRoot:t,handlers:{...$r(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 fe({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 Gr(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=en({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})=>{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 xr(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(),Kn(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();},zl),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();},Nl).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")>ei){a();return}if(u.length===0)return;let m=0;for(let g of u){let p=Buffer.byteLength(g,"utf8");if(p>ei){a();return}m+=p+1;}if(i+m>Ul){a();return}i+=m,s=s.then(async()=>{for(let g of u){if(r)return;if(!o){let p;try{p=JSON.parse(g);}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(g.trim())try{let p=JSON.parse(g),f=await this.handleRequest(p);f!==null&&!r&&await this.writeFrame(t,f);}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(),l(new Error("Timed out writing daemon response"));},ql),d=()=>{clearTimeout(c),t.off("close",u),t.off("error",m),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")),m=f=>l(f),g=()=>{s=true,l();};t.once("close",u),t.once("error",m),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}`));},Ll),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();},Hl).unref());}async handleRequest(t){let n=this.hostRuntime,o=Ql(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=Yt(t.type,this.hookRuntime,n);if(!r.enabled)return this.hookFailureResponse(t.type,r);let i=Date.now();try{let s=Ar(t.type,await Tr({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 Q("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=Cr(s);return this.hookHealth.recordFailure(t.type,n.hostId,a.category,a.reason),Q("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=mr(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")}`);pr(t),this.logRuntime("info","session_start_spool_accepted",{receiptId:t.receiptId});}catch(n){fr(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=Kl(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,b=R?ze(R):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 Z(this.projectRoot,o,i?.executionId),d=c.getPhase(),l=dr({toolName:n.tool_name,toolInput:n.tool_input,projectRoot:this.projectRoot}),u=l?{permissionDecision:"deny",reason:l}:c.evaluate(n.tool_name,s),m;if(u.permissionDecision==="deny"?m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:u.reason??"MCP context required"}}:u.additionalContext?m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:u.additionalContext}}:m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}},r){let R=m.hookSpecificOutput,b=typeof R.additionalContext=="string"?R.additionalContext:"";R.additionalContext=b?`${b}
36
+ ${r}`:r;}n.tool_name.startsWith("mcp__devflow__")&&(m.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 p=i?.executionId??o,I={eventId:ve(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:Vl(n.tool_name),input:g,duration:0,blocked:m&&m.hookSpecificOutput?.permissionDecision==="deny"},k=await this.telemetry.sendEvent({...I,blockReason:I.blocked?l?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0,error:I.blocked?l?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED":void 0});return k&&!I.blocked&&(this.eventMap.push({toolName:n.tool_name,toolUseId:n.tool_use_id,eventId:k,sessionId:o,timestamp:I.timestamp}),this.noteTelemetryOperation()),k&&I.blocked&&await this.telemetry.completeEvent({eventId:k,sessionId:o,error:l?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED",duration:Date.now()-I.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&&Oe(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,Mn(n));return i.executionId&&i.executionId!==r&&this.telemetry.sendExecutionStart(i.executionId,t,n,i.lastActivityAt,this.projectRoot,i.requiredMcpTools).catch(()=>{}),On(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(!Jl[t])return null;let n=Math.floor(Date.now()/1e3),o=ht(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(Eo({projectRoot:this.projectRoot,sessionId:s,executionId:this.runtimeStore.get(s)?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:n.tool_use_id}),o==="Skill"){let S=r?.skill,A=S?ze(S):null;A&&(this.startSkillExecution(s,A),Oe(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0}));}if(o.startsWith("mcp__")){let S=this.runtimeStore.get(s),A=new Z(this.projectRoot,s,S?.executionId??s);A.recordMcpCall();let E=Gl(i);ni(A,o.replace(/^mcp__[^_]+__/,""),E?ti(E):"succeeded",E,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),A=S.length>5e3?{_truncated:true,_originalSize:S.length,text:S.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/,m=r.command||"",g=JSON.stringify(i),p=Buffer.byteLength(g,"utf8"),f=this.countResults(i),I,k,R=true;if(o.startsWith("mcp__"))I="mcp_call",k={mcpTool:o.replace(/^mcp__[^_]+__/,""),query:r.query??null,resultCount:f,resultSizeBytes:p};else if(o==="Read"||o==="Write"||o==="Edit")I=o==="Read"?"file_read":"file_write",k={filePath:r.file_path??null,fileContentSize:p};else if(o==="Bash"){let S=u.test(m),A=d!==void 0&&d!==0;R=!S||A,I=A?"bash_error":"bash_command",k={command:m||o,exitCode:d??null,stderr:l??null};}else o==="Agent"?(I="subagent",k={subagentType:r.subagent_type??null,description:typeof r.description=="string"?r.description.slice(0,200):null}):o==="WebSearch"||o==="WebFetch"?(I=o==="WebSearch"?"web_search":"web_fetch",k={query:typeof r.query=="string"?r.query.slice(0,200):null}):(R=false,I="tool_use",k={});if(R){let S={id:n.tool_use_id?`memory:${ve(s,n.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:s,tool:o,kind:I,payload:k,command:m||void 0,exitCode:d,stderr:l??void 0,durationMs:0,createdAt:Date.now()};this.postMemoryEvent(S);}let b=_o({toolName:o,toolResponse:i,sessionId:s,toolUseId:n.tool_use_id,runtimeStore:this.runtimeStore}),j=this.runtimeStore.get(s),T=Jr({projectRoot:this.projectRoot,sessionId:s,executionId:j?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:n.tool_use_id}),C=this.enforcePostToolUse(o);C&&this.logRuntime("warn","post_tool_enforcement",{tool:o,reason:C},s);let F=[b,T,C].filter(S=>!!S).join(`
35
37
 
36
- `);return D?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:D}}:null}async handlePostToolUseFailure(e){let t;try{t=JSON.parse(e);}catch{return null}let o=this.trackSession(t.session_id),r=t.tool_name??"unknown",i=t.error??`${r} failed`;if(r.startsWith("mcp__devflow__")){let a=this.runtimeStore.get(o),c=new z(this.projectRoot,o,a?.executionId??o);Pr(c,r.replace(/^mcp__[^_]+__/,""),Or(i),i,t.tool_use_id);}let s=this.popEventFromMap(r,o,t.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=pe(o,t.tool_use_id);await this.telemetry.sendEvent({eventId:a,executionId:this.runtimeStore.get(o)?.executionId??o,sessionId:o,projectRoot:this.projectRoot,toolUseId:t.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:t.tool_input??{},duration:0,error:i,blocked:false});}return this.postMemoryEvent({id:t.tool_use_id?`memory:${pe(o,t.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:o,tool:r,command:typeof t.tool_input?.command=="string"?t.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:t.tool_input?.command??r,exitCode:-1,stderr:i}}),null}countResults(e){if(!e)return 0;let t=e;if(typeof e=="string")try{t=JSON.parse(e);}catch{return 1}let o=t,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 l of r)Array.isArray(s[l])&&(c=true,a+=s[l].length);for(let[,l]of Object.entries(s))l&&typeof l=="object"&&!Array.isArray(l)&&(a+=this.countResults(l));return a>0?a:c?0:Object.keys(s).length>0?1:0}return 0}async postMemoryEvent(e){F(`/api/memory/session-events?rootPath=${encodeURIComponent(this.projectRoot)}`,e);try{await(await this.getMemoryGate()).recordEvent(e);}catch(t){console.error("[devflow-daemon] Local memory event write failed:",t.message);}}async getMemoryGate(){let e=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return this.memoryWarmup??=e.forceWarmUp().catch(t=>{throw this.memoryWarmup=null,t}),await this.memoryWarmup,e}async handleUserPromptSubmit(e){let t=[];try{let o=JSON.parse(e),r=typeof o.prompt=="string"?o.prompt:"",i=typeof o.session_id=="string"&&o.session_id.trim()?this.trackSession(o.session_id):null,s=So(r),a=!1;if(r.trim()&&i)try{let c=Mt({projectRoot:this.projectRoot,sessionId:i,prompt:r});if(c){let l=c;if(c.explicitContent&&c.turn.status==="pending")try{l=await At({projectRoot:this.projectRoot,payload:{operation:"commit_explicit",turnId:c.turn.turnId,eventId:c.turn.eventId,sessionId:i,prompt:r.trim().slice(0,4e3),explicitContent:c.explicitContent,createdAt:c.turn.createdAt},memory:await this.getMemoryGate()});}catch(d){console.error("[devflow-daemon] Explicit memory commit deferred:",d.message);}t.push(l.additionalContext),a=l.skipSkillRouting;}}catch(c){a=!!Oe(r);try{let d=Zo(this.projectRoot,{sessionId:i,prompt:r,createdAt:Date.now()});t.push(`DevFlow memory turn status=accepted; durable=true; receiptId=${d}; canonicalMemory=false; SQLite queue replay pending. Do not claim memory success without a canonical receipt.`),this.scheduleMemoryTurnSpoolDrain(250),console.error("[devflow-daemon] Memory turn spooled after database contention:",c.message);}catch(d){t.push("DevFlow memory turn status=degraded; durable=false; no canonical receipt exists. Do not claim memory success."),console.error("[devflow-daemon] Memory turn persistence unavailable:",d.message);}}if(i&&s&&!a){let c=this.startSkillExecution(i,s.skillName,r);c&&t.push(c);}}catch{}return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...t.length?{additionalContext:t.join(`
37
- `)}:{}}}}async handlePreCompact(e){let t;try{let s=JSON.parse(e);typeof s.session_id=="string"&&s.session_id.trim()&&(t=s.session_id.trim());}catch{}await this.flushTelemetry(),this.startExplicitIntentFlush(),await this.explicitIntentFlush;let o=await this.getMemoryGate(),r=await ce({projectRoot:this.projectRoot,sessionId:t,trigger:"pre_compact",memory:o}),i=Hn(r);return {hookSpecificOutput:{hookEventName:"PreCompact",...i?{additionalContext:i}:{}}}}async persistMemoryTurnItem(e){if(!e||typeof e!="object")throw new Error("memory_turn_payload_invalid");let t=e;if(t.operation!=="capture_prompt"&&t.operation!=="commit_explicit"||typeof t.turnId!="string"||typeof t.eventId!="string"||typeof t.sessionId!="string"||typeof t.prompt!="string"||typeof t.createdAt!="number")throw new Error("memory_turn_payload_invalid");await At({projectRoot:this.projectRoot,payload:t,memory:await this.getMemoryGate()});}scheduleMemoryTurnSpoolDrain(e){this.memoryTurnSpoolTimer||(this.memoryTurnSpoolTimer=setTimeout(()=>{this.memoryTurnSpoolTimer=null,this.drainMemoryTurnSpool();},e),this.memoryTurnSpoolTimer.unref());}async drainMemoryTurnSpool(){for(;;){let e=er(this.projectRoot);if(!e)return;try{Mt({projectRoot:this.projectRoot,sessionId:e.payload.sessionId,prompt:e.payload.prompt}),tr(e),this.workRuntime.drainOnce();}catch(t){nr(e),console.error("[devflow-daemon] Memory turn spool replay deferred:",t.message),this.scheduleMemoryTurnSpoolDrain(1e3);return}}}async bootstrapSessionWork(e){if(!e||typeof e!="object"||typeof e.sessionId!="string")throw new Error("session_bootstrap_payload_invalid");let t=e.sessionId,o=await this.getMemoryGate();await o.ensureSession(t,this.projectRoot,"Host session"),await o.releasePendingDistillLeases(t),await this.refreshMemorySnapshot("session_bootstrap");}noteTelemetryOperation(){this.successfulTelemetryOperations++,this.successfulTelemetryOperations>=Jl&&this.flushTelemetry();}async flushTelemetry(){this.successfulTelemetryOperations=0,await this.telemetry.flushAndAggregate();}startExplicitIntentFlush(){this.explicitIntentFlush||(this.explicitIntentFlush=this.flushExplicitMemoryIntents().finally(()=>{this.explicitIntentFlush=null;}));}async handleStop(e){let t=null,o=false,r;try{let i=JSON.parse(e);typeof i.session_id=="string"&&i.session_id.trim()&&(t=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(t??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null,this.startExplicitIntentFlush(),t){let i=mr({projectRoot:this.projectRoot,sessionId:t,transcriptPath:r,stopHookActive:o,runtimeStore:this.runtimeStore});if(i.decision==="block_once")return {decision:"block",reason:i.additionalContext};let s=this.runtimeStore.completeExecution(t);if(s?.executionId){let a=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50}),c={};try{let l=a.listSessionMemoryTurnsForReconciliation(this.projectRoot,t);c={...ft(l),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(t,s.executionId);}}return null}async flushExplicitMemoryIntents(){this.flushTelemetry();let e=ko(this.projectRoot);if(e)try{let t=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);await t.forceWarmUp();let o=!1;for(;e.intents.length>0;){let r=e.intents[0];if(r.turnId){let s=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let a=s.getMemoryTurn(r.turnId);if(!a||a.status!=="pending"){console.error(`[devflow-daemon] Dropping stale legacy memory intent for ${r.turnId}: ${a?.status??"missing"}`),ht(e);continue}}finally{s.close();}}let i=await t.saveExplicitMemoryIntent(r.content,r.sessionId,r.eventId);if(o=!0,r.turnId){let s=openGlobalDevFlowDatabase();try{let a=s.commitMemoryTurn({turnId:r.turnId,receiptId:Dt(r.turnId,"committed",[i.id]),memoryIds:[i.id],source:"explicit_intent",reason:"explicit_user_request_retry"});if(a.receiptId)try{await t.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){console.error("[devflow-daemon] Canonical memory lineage finalization deferred:",c.message);}try{await t.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}),console.error("[devflow-daemon] Explicit memory enrichment deferred:",c.message);}}finally{s.close();}}ht(e);}o&&await this.refreshMemorySnapshot("legacy_explicit_memory_commit");}catch(t){console.error("[devflow-daemon] Explicit memory intent save failed:",t.message);}}deleteContextReceipt(e,t){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),o.deleteContextReceipt(this.projectRoot,e,t);}catch{}finally{o?.close();}}async refreshMemorySnapshot(e){try{let t=loadConfig(this.projectRoot).sessionStart?.injectMemories??!0,o=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return await Le({projectRoot:this.projectRoot,memory:o,injectConfig:t,reason:e})}catch(t){return console.error("[devflow-daemon] Memory snapshot refresh degraded:",t.message),Tt({projectRoot:this.projectRoot,reason:e,load:async()=>{throw t}})}}async handleMemorySnapshot(){let e=await this.refreshMemorySnapshot("memory_snapshot_request"),{snapshot:t}=e;return {status:t.status==="ready"||t.status==="disabled"?"ok":t.status,enabled:t.status!=="disabled",markdown:t.markdown,memoryIds:t.memoryIds,memoryCount:t.memoryIds.length,conflicts:t.conflicts,snapshot:t,persisted:e.persisted}}async handleSessionEnd(e){let t=null;try{let s=JSON.parse(e);typeof s.session_id=="string"&&s.session_id.trim()&&(t=s.session_id.trim());}catch{}t??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null;let o=t===null?this.activeSessionIds.size<=1:this.activeSessionIds.size<=1&&this.activeSessionIds.has(t),r=t?this.runtimeStore.get(t)?.executionId:void 0,i=Ae(e,this.projectRoot,o,r);return i?.workState==="spooled"&&this.scheduleSessionFinalizeSpoolDrain(250),t&&(this.serverManager.removeRef(t),this.activeSessionIds.delete(t),this.eventMap=this.eventMap.filter(s=>s.sessionId!==t)),this.activeSessionIds.size===0&&i?.workState!=="spooled"?setImmediate(()=>{this.workRuntime.drainOnce().finally(()=>{this.shutdown();});}):this.resetIdleTimer(),i??{status:"ok"}}async finalizeSessionWork(e,t){if(!e||typeof e!="object")throw new Error("session_finalize_payload_invalid");let o=e;if(typeof o.inputJson!="string"||typeof o.sessionId!="string")throw new Error("session_finalize_payload_invalid");let r=await this.getMemoryGate();await vo(o.inputJson,this.projectRoot,o.cleanupSharedState!==false,{telemetry:this.telemetry,memory:r,executionId:o.executionId});try{await this.refreshMemorySnapshot("session_finalization");}catch(s){console.error("[devflow-daemon] Session finalization snapshot refresh degraded:",s.message);}let i=openGlobalDevFlowDatabase();try{i.completeSessionClosure(this.projectRoot,o.sessionId,t);}finally{i.close();}}enqueueLearningAnalysisIfReady(e,t){if(resolveCapabilityRollout(this.projectRoot).config.learningOverlays==="off")return;let r=e.getSessionClosure(this.projectRoot,t);if(!r||r.state!=="closed"||r.pendingWorkCount!==0||e.listSessionObligations(this.projectRoot,t).some(c=>c.state==="open"||c.state==="degraded"))return;let s=e.getLatestSkillExecutionForSession(t);if(s&&s.status==="running")return;let a=Yl(this.projectRoot);e.enqueueWork({idempotencyKey:`learning-analysis:${r.receiptId}:${a}`,kind:"learning.analyze_session",projectRoot:this.projectRoot,sessionId:t,payload:{projectRoot:this.projectRoot,sessionId:t,executionId:s?.executionId,closureReceipt:r.receiptId,projectRevision:a,createdAt:Date.now()},maxAttempts:5});}scheduleSessionFinalizeSpoolDrain(e){this.sessionFinalizeSpoolTimer||(this.sessionFinalizeSpoolTimer=setTimeout(()=>{this.sessionFinalizeSpoolTimer=null,this.drainSessionFinalizeSpool();},e),this.sessionFinalizeSpoolTimer.unref());}async drainSessionFinalizeSpool(){for(;;){let e=Zn(this.projectRoot);if(!e)return;try{if(!Ae(e.payload.inputJson,this.projectRoot,e.payload.cleanupSharedState,e.payload.executionId,!1))throw new Error("session_finalize_spool_rejected");eo(e),this.workRuntime.drainOnce();}catch(t){to(e),console.error("[devflow-daemon] Session finalize spool replay deferred:",t.message),this.scheduleSessionFinalizeSpoolDrain(1e3);return}}}shutdown(){return this.shutdownPromise?this.shutdownPromise:(this.shutdownPromise=this.performShutdown(),this.shutdownPromise)}async performShutdown(){this.workRuntime.stop(),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.telemetryFlushTimer&&(clearInterval(this.telemetryFlushTimer),this.telemetryFlushTimer=null),this.memoryTurnSpoolTimer&&(clearTimeout(this.memoryTurnSpoolTimer),this.memoryTurnSpoolTimer=null),this.sessionFinalizeSpoolTimer&&(clearTimeout(this.sessionFinalizeSpoolTimer),this.sessionFinalizeSpoolTimer=null),await this.flushTelemetry(),await this.closeServer(),this.cleanupOwnedResources(),await this.serverManager.stop(),await this.explicitIntentFlush,this.explicitMemoryGate?.close(),this.explicitMemoryGate=null,this.telemetry.close(),process.exit(0);}closeServer(){let e=this.server;return !e||!e.listening||!this.pathMatchesIdentity(this.socketPath,this.socketIdentity)?Promise.resolve():(this.server=null,new Promise(t=>{let o=false,r=()=>{o||(o=true,clearTimeout(i),t());},i=setTimeout(r,Wl);e.close(r);}))}cleanupOwnedResources(){try{$n(this.projectRoot,process.pid);}catch(e){console.error("[devflow-daemon] Failed to unregister:",e.message);}this.removePathIfOwned(this.socketPath,this.socketIdentity,"socket"),this.removePathIfOwned(this.pidPath,this.pidIdentity,"PID file",`${process.pid}
38
- `);}};function Yl(n){try{return execFileSync("git",["rev-parse","HEAD"],{cwd:n,encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return `unversioned:${createHash("sha256").update(n).digest("hex").slice(0,16)}`}}if(process.env.DEVFLOW_HOOK_DAEMON_DISABLE_AUTOSTART!=="1"){let n=process.argv[2]||process.env.CLAUDE_PROJECT_DIR||process.cwd(),e=new nn(n,process.argv[3]);process.once("SIGTERM",()=>{e.shutdown();}),process.once("SIGINT",()=>{e.shutdown();}),e.start().catch(t=>{console.error("[devflow-daemon] Failed to start:",t),process.exit(1);});}export{nn as HookDaemon,Kl as injectProjectRootIfMissing};
38
+ `);return F?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:F}}: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 Z(this.projectRoot,o,a?.executionId??o);ni(c,r.replace(/^mcp__[^_]+__/,""),ti(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=ve(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:${ve(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){B(`/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=Lo(r),a=!1,c;if(r.trim()&&i){try{c=Qr({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=qt({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 Ut({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=!!Ue(r);try{let u=hr(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 fe({projectRoot:this.projectRoot,sessionId:n,trigger:"pre_compact",memory:o}),i=Yn(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 Ut({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=yr(this.projectRoot);if(!t)return;try{qt({projectRoot:this.projectRoot,sessionId:t.payload.sessionId,prompt:t.payload.prompt}),vr(t),this.workRuntime.drainOnce();}catch(n){_r(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>=Bl&&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=Dr({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={...Et(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=No(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),At(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();}}At(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 Qe({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}),Wt({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=qe(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 jo(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=Yl(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=po(this.projectRoot);if(!t)return;try{if(!qe(t.payload.inputJson,this.projectRoot,t.payload.cleanupSharedState,t.payload.executionId,!1))throw new Error("session_finalize_spool_rejected");fo(t),this.workRuntime.drainOnce();}catch(n){go(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,Wl);t.close(r);}))}cleanupOwnedResources(){try{Qn(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 Ql(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 Yl(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 gn(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{gn as HookDaemon,Kl as injectProjectRootIfMissing};