@devflow-tools/devflow 0.18.70 → 0.18.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/dashboard/404.html +1 -1
  2. package/dist/dashboard/__next.__PAGE__.txt +1 -1
  3. package/dist/dashboard/__next._full.txt +1 -1
  4. package/dist/dashboard/__next._tree.txt +1 -1
  5. package/dist/dashboard/_not-found/__next._full.txt +1 -1
  6. package/dist/dashboard/_not-found/__next._not-found.__PAGE__.txt +1 -1
  7. package/dist/dashboard/_not-found/__next._tree.txt +1 -1
  8. package/dist/dashboard/_not-found.html +1 -1
  9. package/dist/dashboard/_not-found.txt +1 -1
  10. package/dist/dashboard/accuracy/__next._full.txt +1 -1
  11. package/dist/dashboard/accuracy/__next._tree.txt +1 -1
  12. package/dist/dashboard/accuracy/__next.accuracy.__PAGE__.txt +1 -1
  13. package/dist/dashboard/accuracy.html +1 -1
  14. package/dist/dashboard/accuracy.txt +1 -1
  15. package/dist/dashboard/benchmark/__next._full.txt +1 -1
  16. package/dist/dashboard/benchmark/__next._tree.txt +1 -1
  17. package/dist/dashboard/benchmark/__next.benchmark.__PAGE__.txt +1 -1
  18. package/dist/dashboard/benchmark.html +1 -1
  19. package/dist/dashboard/benchmark.txt +1 -1
  20. package/dist/dashboard/context/__next._full.txt +1 -1
  21. package/dist/dashboard/context/__next._tree.txt +1 -1
  22. package/dist/dashboard/context/__next.context.__PAGE__.txt +1 -1
  23. package/dist/dashboard/context.html +1 -1
  24. package/dist/dashboard/context.txt +1 -1
  25. package/dist/dashboard/doctor/__next._full.txt +1 -1
  26. package/dist/dashboard/doctor/__next._tree.txt +1 -1
  27. package/dist/dashboard/doctor/__next.doctor.__PAGE__.txt +1 -1
  28. package/dist/dashboard/doctor.html +1 -1
  29. package/dist/dashboard/doctor.txt +1 -1
  30. package/dist/dashboard/executions/__next._full.txt +1 -1
  31. package/dist/dashboard/executions/__next._tree.txt +1 -1
  32. package/dist/dashboard/executions/__next.executions.__PAGE__.txt +1 -1
  33. package/dist/dashboard/executions.html +1 -1
  34. package/dist/dashboard/executions.txt +1 -1
  35. package/dist/dashboard/graph/__next._full.txt +1 -1
  36. package/dist/dashboard/graph/__next._tree.txt +1 -1
  37. package/dist/dashboard/graph/__next.graph.__PAGE__.txt +1 -1
  38. package/dist/dashboard/graph.html +1 -1
  39. package/dist/dashboard/graph.txt +1 -1
  40. package/dist/dashboard/index.html +1 -1
  41. package/dist/dashboard/index.txt +1 -1
  42. package/dist/dashboard/intelligence/__next._full.txt +1 -1
  43. package/dist/dashboard/intelligence/__next._tree.txt +1 -1
  44. package/dist/dashboard/intelligence/__next.intelligence.__PAGE__.txt +1 -1
  45. package/dist/dashboard/intelligence/knowledge/__next._full.txt +1 -1
  46. package/dist/dashboard/intelligence/knowledge/__next._tree.txt +1 -1
  47. package/dist/dashboard/intelligence/knowledge/__next.intelligence.knowledge.__PAGE__.txt +1 -1
  48. package/dist/dashboard/intelligence/knowledge.html +1 -1
  49. package/dist/dashboard/intelligence/knowledge.txt +1 -1
  50. package/dist/dashboard/intelligence/memory/__next._full.txt +1 -1
  51. package/dist/dashboard/intelligence/memory/__next._tree.txt +1 -1
  52. package/dist/dashboard/intelligence/memory/__next.intelligence.memory.__PAGE__.txt +1 -1
  53. package/dist/dashboard/intelligence/memory.html +1 -1
  54. package/dist/dashboard/intelligence/memory.txt +1 -1
  55. package/dist/dashboard/intelligence.html +1 -1
  56. package/dist/dashboard/intelligence.txt +1 -1
  57. package/dist/dashboard/knowledge/__next._full.txt +1 -1
  58. package/dist/dashboard/knowledge/__next._tree.txt +1 -1
  59. package/dist/dashboard/knowledge/__next.knowledge.__PAGE__.txt +1 -1
  60. package/dist/dashboard/knowledge.html +1 -1
  61. package/dist/dashboard/knowledge.txt +1 -1
  62. package/dist/dashboard/memory/__next._full.txt +1 -1
  63. package/dist/dashboard/memory/__next._tree.txt +1 -1
  64. package/dist/dashboard/memory/__next.memory.__PAGE__.txt +1 -1
  65. package/dist/dashboard/memory.html +1 -1
  66. package/dist/dashboard/memory.txt +1 -1
  67. package/dist/dashboard/replay/__next._full.txt +1 -1
  68. package/dist/dashboard/replay/__next._tree.txt +1 -1
  69. package/dist/dashboard/replay/__next.replay.__PAGE__.txt +1 -1
  70. package/dist/dashboard/replay.html +1 -1
  71. package/dist/dashboard/replay.txt +1 -1
  72. package/dist/dashboard/runs/_/__next._full.txt +1 -1
  73. package/dist/dashboard/runs/_/__next._tree.txt +1 -1
  74. package/dist/dashboard/runs/_/__next.runs.$d$id.__PAGE__.txt +1 -1
  75. package/dist/dashboard/runs/_.html +1 -1
  76. package/dist/dashboard/runs/_.txt +1 -1
  77. package/dist/dashboard/runs/__next._full.txt +1 -1
  78. package/dist/dashboard/runs/__next._tree.txt +1 -1
  79. package/dist/dashboard/runs/__next.runs.__PAGE__.txt +1 -1
  80. package/dist/dashboard/runs.html +1 -1
  81. package/dist/dashboard/runs.txt +1 -1
  82. package/dist/dashboard/settings/__next._full.txt +1 -1
  83. package/dist/dashboard/settings/__next._tree.txt +1 -1
  84. package/dist/dashboard/settings/__next.settings.__PAGE__.txt +1 -1
  85. package/dist/dashboard/settings.html +1 -1
  86. package/dist/dashboard/settings.txt +1 -1
  87. package/dist/dashboard/timeline/__next._full.txt +1 -1
  88. package/dist/dashboard/timeline/__next._tree.txt +1 -1
  89. package/dist/dashboard/timeline/__next.timeline.__PAGE__.txt +1 -1
  90. package/dist/dashboard/timeline.html +1 -1
  91. package/dist/dashboard/timeline.txt +1 -1
  92. package/dist/dashboard/tool-metrics/__next._full.txt +1 -1
  93. package/dist/dashboard/tool-metrics/__next._tree.txt +1 -1
  94. package/dist/dashboard/tool-metrics/__next.tool-metrics.__PAGE__.txt +1 -1
  95. package/dist/dashboard/tool-metrics.html +1 -1
  96. package/dist/dashboard/tool-metrics.txt +1 -1
  97. package/dist/dashboard/workflows/__next._full.txt +1 -1
  98. package/dist/dashboard/workflows/__next._tree.txt +1 -1
  99. package/dist/dashboard/workflows/__next.workflows.__PAGE__.txt +1 -1
  100. package/dist/dashboard/workflows.html +1 -1
  101. package/dist/dashboard/workflows.txt +1 -1
  102. package/dist/hooks/hook-daemon.js +1 -1
  103. package/dist/hooks/pre-tool-use.js +3 -3
  104. package/dist/plugin/.claude-plugin/plugin.json +1 -1
  105. package/dist/plugin/dist/command-registry.json +7 -7
  106. package/dist/plugin/dist/hooks/hook-daemon.js +1 -1
  107. package/dist/plugin/dist/hooks/pre-tool-use.js +3 -3
  108. package/dist/plugin/dist/runtime-manifest.json +6 -6
  109. package/dist/plugin/package.json +12 -12
  110. package/package.json +16 -16
  111. package/plugin-registry.json +29 -29
  112. /package/dist/dashboard/_next/static/{ZuLomm-xchj2DMM5zE1K_ → 9Kv9d6_e3jRS6JzuKtY2r}/_buildManifest.js +0 -0
  113. /package/dist/dashboard/_next/static/{ZuLomm-xchj2DMM5zE1K_ → 9Kv9d6_e3jRS6JzuKtY2r}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- import {createHash as createHash$1}from'node:crypto';import {existsSync,readdirSync,readFileSync,unlinkSync,mkdirSync,writeFileSync,rmSync,linkSync,renameSync,statSync}from'fs';import {join as join$1,dirname as dirname$1}from'path';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {getLocalApiKey,getDevFlowStateRoot,projectClaudeToolName,resolveClaudeToolName,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,getProjectStateDir,readRuntimeState}from'@devflow-tools/sdk';import {request}from'node:http';import {existsSync as existsSync$1,mkdirSync as mkdirSync$1,appendFileSync,chmodSync,readFileSync as readFileSync$1,writeFileSync as writeFileSync$1,renameSync as renameSync$1}from'node:fs';import {join,resolve,basename,relative,sep,dirname,isAbsolute,normalize}from'node:path';import {maybeRunDiagnosticLogCleanup,rotateDiagnosticLogFile,emitSemanticControlLog}from'@devflow-tools/telemetry';import {fileURLToPath}from'url';import {randomUUID,createHash}from'crypto';import {homedir}from'node:os';import {DatabaseSync}from'node:sqlite';function $(i,t,e){try{let n=openGlobalDevFlowDatabase();try{n.insertEvent({kind:i,timestamp:Date.now(),duration:e,success:t.success!==!1,metadata:t});}finally{n.close();}}catch{}}var dt=getLocalApiKey(),G=join(getDevFlowStateRoot(),"errors");async function ce(i,t,e={}){let n=e.endpoint??process.env.DEVFLOW_SERVER_URL?.trim()??ut();if(!n)return {delivered:false,suppressed:false,fallbackReason:"runtime_not_ready"};let o=e.timeout??1500,r=e.durableMirror??true,s=e.maxRetries??(r?0:2),c=e.circuitBreaker??true,a=acquireRuntimeHttpCircuit(n,i);if(c&&!a.allowed)return {delivered:false,suppressed:true,fallbackReason:a.state.fallbackReason};let l;for(let u=0;u<=s;u+=1)try{return await pt(n,i,t,o),c&&registerRuntimeHttpSuccess(n,i).transitioned&&$("http_circuit_transition",{endpoint:n,path:new URL(i,n).pathname,previous:a.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(p){l=p instanceof Error?p:new Error(String(p)),u<s&&await gt(Math.min(100*2**u,1e3));}if(!l)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!c)return se(i,l),{delivered:false,suppressed:false,fallbackReason:l.message};let d=registerRuntimeHttpFailure(n,i,e.fallbackReason??(r?"local_durable_mirror":"http_delivery_failed"));return d.transitioned&&(se(i,l),$("http_circuit_transition",{endpoint:n,path:new URL(i,n).pathname,previous:a.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 ut(){let i=readRuntimeState();return i?.status==="ready"&&i.dashboardAvailable?i.url:void 0}function pt(i,t,e,n){return new Promise((o,r)=>{let s=JSON.stringify(e),c=new URL(t,i),a=false,l=u=>{a||(a=true,u?r(u):o());},d=request({hostname:c.hostname,port:c.port,path:c.pathname+c.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":dt,"Content-Length":Buffer.byteLength(s)},timeout:n},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 ${n}ms`))),d.write(s),d.end();})}function se(i,t){try{existsSync$1(G)||mkdirSync$1(G,{recursive:!0});let e=join(G,"http-errors.log"),n=`${new Date().toISOString()} | ${i} | ${t.message}
2
- `;rotateDiagnosticLogFile({path:e,maxBytes:50*1024*1024,maxFiles:5,incomingBytes:Buffer.byteLength(n)}),appendFileSync(e,n);}catch{}}function gt(i){return new Promise(t=>setTimeout(t,i))}var pe=1e4,bt=3e4,U=500,H=class{constructor(t){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=t?.apiUrl,this.cacheDir=t?.cacheDir??join$1(getDevFlowStateRoot(),"global","telemetry-cache"),this.database=t?.database??null,this.ownsDatabase=!t?.database;let e=t?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(e)&&e>=0?e:100;}async sendEvent(t){let e={...t,input:this.truncateInput(t.input)};return this.commitOrCache("tool_call",e)?(this.postHttp("/api/telemetry/tool-call",e),t.eventId):null}async sendExecutionStart(t,e,n,o,r=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let c={executionId:t,sessionId:e,skillName:n,startedAt:o,projectRoot:r,requiredMcpTools:s};this.commitOrCache("execution_start",c)&&this.postHttp("/api/telemetry/skill-execution/start",c);}async sendExecutionComplete(t,e="completed",n=Date.now(),o){let r={executionId:t,status:e,finishedAt:n,metadata:o},s=this.commitOrCache("execution_complete",r);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",r),s}async sendSessionStart(t,e,n){let o={id:t,projectRoot:e,startedAt:n,label:e.split("/").pop()??"unknown"},r=this.commitOrCache("session_start",o);return r&&this.postHttp("/api/telemetry/sessions",o),r}async completeEvent(t){let e=this.commitOrCache("complete_event",t);return e&&(this.postHttp("/api/telemetry/tool-call/output",t),this.scheduleMetricAggregation()),e}async endSession(t,e=Date.now()){let n={sessionId:t,finishedAt:e},o=this.commitOrCache("session_end",n);return o&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:e})),o}async flushCache(){try{let e=this.getDatabase(),n=e.listTelemetryFailures({unresolvedOnly:!0,limit:U}).reverse();for(let o of n)try{this.applyOperation(o.operation,o.payload),e.resolveTelemetryFailure(o.id);}catch{}e.trimTelemetryFailures(U);}catch{}let t=(existsSync(this.cacheDir)?readdirSync(this.cacheDir):[]).filter(e=>e.endsWith(".json")).map(e=>{let n=join$1(this.cacheDir,e);try{return {cacheFile:n,envelope:_t(JSON.parse(readFileSync(n,"utf8")))}}catch{return null}}).filter(e=>e!==null).sort((e,n)=>e.envelope.timestamp-n.envelope.timestamp||ge(e.envelope.operation)-ge(n.envelope.operation));for(let{cacheFile:e,envelope:n}of t)try{let o=this.getDatabase();o.insertTelemetryFailure({id:n.id,operation:n.operation,payload:n.payload,error:n.failure,createdAt:n.timestamp}),this.applyOperation(n.operation,n.payload),o.resolveTelemetryFailure(n.id),unlinkSync(e);}catch{}this.database?.aggregatePendingToolMetrics();}aggregateMetrics(){return this.getDatabase().aggregatePendingToolMetrics()}async flushAndAggregate(){await this.flushCache(),this.aggregateMetrics();}close(){this.ownsDatabase&&this.database?.close(),this.database=null;}getDatabase(){return this.database??=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:this.busyTimeoutMs}),this.database}commitOrCache(t,e){try{return this.applyOperation(t,e),!0}catch(n){return this.cacheOperation(t,e,n),false}}applyOperation(t,e){let n=this.getDatabase();switch(t){case "tool_call":this.ensureParentSession(n,e),n.insertToolCallEvent(e);return;case "execution_start":this.ensureParentSession(n,e),n.insertSkillExecution({executionId:e.executionId,sessionId:e.sessionId,skillName:e.skillName,startedAt:e.startedAt,status:"running",requiredMcpTools:e.requiredMcpTools});return;case "execution_complete":n.reconcileSkillExecution(e.executionId,e.status,e.finishedAt,e.metadata);return;case "session_start":n.ensureSession(e),n.insertRun({id:fe(e.id),source:"hook",tool:"session",input:{projectRoot:e.projectRoot},status:"active",startedAt:e.startedAt,tokenUsed:0,metadata:{sessionId:e.id,projectRoot:e.projectRoot}});return;case "complete_event":if(!n.updateToolCallEvent(e.eventId,{output:e.output===void 0?void 0:JSON.stringify(e.output),error:e.error,failureCategory:e.failureCategory,duration:e.duration}))throw new Error(`Tool call event ${e.eventId} is not available for completion`);return;case "session_end":n.closeSession(e.sessionId,e.finishedAt),n.updateRun(fe(e.sessionId),{status:"completed",finishedAt:e.finishedAt});return}}ensureParentSession(t,e){let n=typeof e.sessionId=="string"?e.sessionId.trim():"";if(!n)throw new Error("Canonical session ID is required for telemetry");let o=typeof e.projectRoot=="string"&&e.projectRoot.trim()?e.projectRoot:typeof e.input?.projectRoot=="string"&&e.input.projectRoot.trim()?e.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";t.ensureSession({id:n,projectRoot:o,label:o==="unknown"?void 0:o.split("/").pop(),startedAt:Number(e.startedAt??e.timestamp??Date.now())});}cacheOperation(t,e,n){let o=Date.now(),r={id:`failure:${o}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:e,failure:n instanceof Error?n.message:String(n),timestamp:o};try{let s=this.getDatabase();s.insertTelemetryFailure({id:r.id,operation:t,payload:e,error:r.failure,createdAt:o}),s.trimTelemetryFailures(U),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${o}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(s,JSON.stringify(r,null,2),{mode:384}),this.trimRetryCache(),this.scheduleRetry();}catch{}}trimRetryCache(){try{let t=readdirSync(this.cacheDir).filter(e=>e.endsWith(".json")).sort();for(let e of t.slice(0,Math.max(0,t.length-U)))unlinkSync(join$1(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},bt).unref());}scheduleMetricAggregation(){if(this.metricAggregationScheduled||process.env.DEVFLOW_HOOK_DEGRADED==="1")return;this.metricAggregationScheduled=true,setTimeout(()=>{this.metricAggregationScheduled=false;try{this.getDatabase().aggregatePendingToolMetrics(50)===50&&this.scheduleMetricAggregation();}catch{}},25).unref();}postHttp(t,e){ce(t,e,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=pe?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,pe)}...`}}};function ge(i){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(i)}function fe(i){return `hook-run:${i}`}function _t(i){if(!i||typeof i!="object")throw new Error("Invalid telemetry cache envelope");let t=i;if(typeof t.id!="string"||typeof t.operation!="string"||t.payload===void 0||typeof t.failure!="string"||typeof t.timestamp!="number")throw new Error("Invalid telemetry cache envelope");return t}function T(i){return i??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function w(i){return getProjectStateDir(T(i))}var D=emitSemanticControlLog;var kt=2,St=1;function Ot(){if(process.env.CLAUDE_PLUGIN_ROOT)return process.env.CLAUDE_PLUGIN_ROOT;try{return join$1(dirname$1(fileURLToPath(import.meta.url)),"..","..")}catch{return process.cwd()}}function me(i=Ot()){let t=[join$1(i,"dist","command-registry.json"),join$1(i,"command-registry.json")];for(let e of t)try{if(!existsSync(e))continue;let n=JSON.parse(readFileSync(e,"utf8"));if(n.version!==kt&&n.version!==St||!At(n.commands)){D({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:e}});continue}return n.commands}catch(n){D({event:"hook.runtime.degraded",identity:{projectRoot:process.env.CLAUDE_PROJECT_DIR||process.cwd()},level:"warn",timestamp:Date.now(),data:{stage:"command_registry",reason:n.message,fallback:"next_registry_candidate"}});}return null}function At(i){return !i||typeof i!="object"||Array.isArray(i)?false:Object.values(i).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return q(e.mcpTools)&&q(e.blockedNative)&&(e.source===void 0||e.source==="core"||e.source==="plugin")&&(e.requiresContext===void 0||typeof e.requiresContext=="boolean")&&(e.runtimePackages===void 0||q(e.runtimePackages))&&(e.hostTools===void 0||Ct(e.hostTools))&&(e.evidenceMode===void 0||["static","runtime","mixed"].includes(e.evidenceMode))})}function Ct(i){return !!i&&typeof i=="object"&&!Array.isArray(i)&&Object.entries(i).every(([t,e])=>t.length>0&&q(e))}function q(i){return Array.isArray(i)&&i.every(t=>typeof t=="string"&&t.length>0)}function he(i){let t=me();return t?t[i]?.mcpTools??[]:[]}function _e(i){return Buffer.from(i,"utf8").toString("base64url")}function jt(i,t,e){let n=t?.trim();if(n){let o=/^[a-zA-Z0-9:._-]{1,192}$/.test(n)?n:`tool-${createHash("sha256").update(n.slice(0,1024)).digest("hex").slice(0,32)}`;return `${i}:${o}`}return `${i}:legacy-${e}-${randomUUID().slice(0,8)}`}function xe(i){return `${i}:legacy-journal`}var S=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(w(t),"hook-sessions");}registerSession(t){let e=t.trim();if(!e)throw new Error("session_id_required");let n=this.get(e);if(n)return n.lastActivityAt=Date.now(),this.persist(n),n;let o=Date.now(),r={sessionId:e,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:o,lastActivityAt:o};return this.sessions.set(e,r),this.persist(r),r}startExecution(t,e,n){let o=this.registerSession(t);return (!o.executionId||o.skillName!==e)&&(o.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),o.skillName=e,o.requiredMcpTools=[...new Set(n)],delete o.contextInitialization,o.lastActivityAt=Date.now(),this.persist(o),o}beginContextInitialization(t,e){let n=this.registerSession(t);return n.contextInitialization={startedAt:Date.now(),...e?{toolUseId:e}:{}},n.lastActivityAt=Date.now(),this.persist(n),n}completeContextInitialization(t,e){let n=this.get(t);return n?(e&&n.contextInitialization?.toolUseId&&n.contextInitialization.toolUseId!==e||(delete n.contextInitialization,n.lastActivityAt=Date.now(),this.persist(n)),n):null}bindTaskIdentity(t,e){let n=this.registerSession(t);return n.activeTurnId=e.turnId,n.activeRequestId=e.requestId,n.intentArtifactHash=e.intentArtifactHash,n.lastActivityAt=Date.now(),this.persist(n),n}get(t){let e=t.trim();if(!e)return null;let n=this.sessions.get(e);if(n)return this.replayEvidenceJournal(n),n;let o=this.snapshotPath(e);if(!existsSync(o))return null;try{let r=JSON.parse(readFileSync(o,"utf8"));return r.sessionId!==e||r.projectRoot!==this.projectRoot?null:(r.requiredMcpTools=Array.isArray(r.requiredMcpTools)?r.requiredMcpTools:[],r.evidenceObligations=Re(r.evidenceObligations),r.evidenceDegradations=Ee(r.evidenceDegradations),r.evidenceOutcomes=we(r.evidenceOutcomes),this.replayEvidenceJournal(r),this.sessions.set(e,r),r)}catch{return null}}completeExecution(t){let e=this.get(t);if(!e)return null;let n=structuredClone(e);return delete e.executionId,delete e.skillName,delete e.contextInitialization,e.requiredMcpTools=[],e.lastActivityAt=Date.now(),this.persist(e),n}addEvidenceObligation(t,e,n=Date.now(),o){let r=this.registerSession(t),c=(o?void 0:r.evidenceObligations.find(l=>l.contractId===e.id))?.obligationId??jt(e.id,o,n);this.appendEvidenceEvent(t,{kind:"add",obligationId:c,contractId:e.id,at:n,contract:e},`add\0${c}`),this.replayEvidenceJournal(r);let a=r.evidenceObligations.find(l=>l.obligationId===c);return a?(r.lastActivityAt=Date.now(),this.persist(r),structuredClone(a)):null}listEvidenceObligations(t){return (this.get(t)?.evidenceObligations??[]).map(e=>structuredClone(e))}markEvidenceCorrection(t,e,n,o,r=Date.now()){let s=this.get(t),c=s?.evidenceObligations.find(d=>d.obligationId===e);if(!s||!c)return null;let a=/^[a-f0-9]{64}$/.test(o)?o:"";if(!a)return null;this.appendEvidenceEvent(t,{kind:"correction",obligationId:e,contractId:c.contractId,at:r,fingerprint:a,violations:n.slice(0,16).map(d=>d.slice(0,240))},`correction\0${e}\0${a}`),this.replayEvidenceJournal(s),s.lastActivityAt=r,this.persist(s);let l=s.evidenceObligations.find(d=>d.obligationId===e);return l?structuredClone(l):null}resolveEvidenceObligation(t,e){let n=this.get(t);if(!n)return false;let o=n.evidenceObligations.find(s=>s.obligationId===e);if(!o)return false;let r=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:o.contractId,at:r},`resolve\0${e}`),this.replayEvidenceJournal(n),n.lastActivityAt=r,this.persist(n),true}resolveDegradedEvidence(t,e){let n=this.get(t),o=n?.evidenceDegradations.find(s=>s.obligationId===e);if(!n||!o)return false;let r=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:o.contractId,at:r},`resolve-degraded\0${e}\0${r}`),this.replayEvidenceJournal(n),n.lastActivityAt=r,this.persist(n),true}degradeEvidenceObligation(t,e,n,o=Date.now()){let r=this.get(t),s=r?.evidenceObligations.find(a=>a.obligationId===e);if(!r||!s)return false;let c=n.slice(0,240);return this.appendEvidenceEvent(t,{kind:"degrade",obligationId:e,contractId:s.contractId,at:o,reason:c},`degrade\0${e}\0${c}`),this.replayEvidenceJournal(r),r.lastActivityAt=o,this.persist(r),true}removeSession(t){let e=t.trim();e&&(this.sessions.delete(e),rmSync(this.snapshotPath(e),{force:true}),rmSync(this.evidenceJournalDir(e),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(t){return join$1(this.sessionsDir,`${_e(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",_e(t))}appendEvidenceEvent(t,e,n){let o=this.evidenceJournalDir(t);mkdirSync(o,{recursive:true,mode:448});let r=createHash("sha256").update(n).digest("hex"),s=join$1(o,`${e.kind}-${r}.json`);if(existsSync(s))return;let c=join$1(o,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync(c,JSON.stringify(e),{mode:384});try{linkSync(c,s);}catch(a){if(a.code!=="EEXIST")throw a}finally{rmSync(c,{force:true});}}replayEvidenceJournal(t){t.evidenceObligations=Re(t.evidenceObligations),t.evidenceDegradations=Ee(t.evidenceDegradations),t.evidenceOutcomes=we(t.evidenceOutcomes);let e=this.evidenceJournalDir(t.sessionId);if(!existsSync(e))return;let n;try{n=readdirSync(e).filter(r=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(r)).slice(0,4096);}catch{return}let o=n.flatMap(r=>{try{let s=readFileSync(join$1(e,r),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let c=Pt(JSON.parse(s));return c?[c]:[]}catch{return []}}).sort((r,s)=>r.at-s.at||De(r.kind)-De(s.kind));for(let r of o)this.applyEvidenceEvent(t,r);t.evidenceObligations=t.evidenceObligations.slice(-8),t.evidenceDegradations=t.evidenceDegradations.slice(-20),t.evidenceOutcomes=t.evidenceOutcomes.slice(-20);}applyEvidenceEvent(t,e){let n=t.evidenceOutcomes.find(s=>s.obligationId===e.obligationId);if(e.kind==="add"){if(n)return;let s=t.evidenceObligations.find(c=>c.obligationId===e.obligationId);s?(s.contract=e.contract,s.promptedAt=Math.min(s.promptedAt,e.at)):t.evidenceObligations.push({obligationId:e.obligationId,contractId:e.contractId,contract:e.contract,promptedAt:e.at,attempt:0,correctionRequested:false,violations:[]});return}let o=t.evidenceObligations.find(s=>s.obligationId===e.obligationId);if(e.kind==="correction"){if(!o||n||o.correctionFingerprint===e.fingerprint)return;o.attempt+=1,o.correctionRequested=true,o.correctionRequestedAt=e.at,o.correctionFingerprint=e.fingerprint,o.violations=e.violations;return}let r=o?.attempt??n?.attempt??0;if(e.kind==="resolve"&&n?.status==="degraded")t.evidenceOutcomes=t.evidenceOutcomes.filter(s=>s.obligationId!==e.obligationId),t.evidenceDegradations=t.evidenceDegradations.filter(s=>s.obligationId!==e.obligationId);else if(n)return;e.kind==="degrade"?(t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==e.obligationId),t.evidenceDegradations.push({obligationId:e.obligationId,contractId:e.contractId,reason:e.reason,degradedAt:e.at,attempt:r,contract:o?.contract})):t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==e.obligationId),t.evidenceOutcomes.push({obligationId:e.obligationId,contractId:e.contractId,status:e.kind==="resolve"?"resolved":"degraded",completedAt:e.at,attempt:r,...e.kind==="degrade"?{reason:e.reason}:{}});}persist(t){mkdirSync(this.sessionsDir,{recursive:true,mode:448});let e=this.snapshotPath(t.sessionId),n=`${e}.${process.pid}.${randomUUID()}.tmp`;writeFileSync(n,JSON.stringify(t),{mode:384}),renameSync(n,e);}};function Re(i){return Array.isArray(i)?i.flatMap(t=>{if(!t||typeof t!="object")return [];let e=t;if(typeof e.contractId!="string"||e.contractId.length===0||e.contractId.length>128||typeof e.promptedAt!="number"||typeof e.attempt!="number"||typeof e.correctionRequested!="boolean"||!Array.isArray(e.violations)||!ke(e.contract))return [];let n=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:xe(e.contractId),o=typeof e.correctionTranscriptHash=="string"?e.correctionTranscriptHash:void 0,r=e.correctionFingerprint??o;return r!==void 0&&!/^[a-f0-9]{64}$/.test(r)?[]:[{...e,obligationId:n,correctionFingerprint:r}]}).slice(-8):[]}function Ee(i){return Array.isArray(i)?i.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&typeof e.reason=="string"&&typeof e.degradedAt=="number"&&typeof e.attempt=="number"}).slice(-20):[]}function we(i){return Array.isArray(i)?i.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&(e.status==="resolved"||e.status==="degraded")&&typeof e.completedAt=="number"&&typeof e.attempt=="number"&&(e.reason===void 0||typeof e.reason=="string")}).slice(-20):[]}function Pt(i){if(!i||typeof i!="object")return null;let t=i,e=t.kind;if(e!=="add"&&e!=="correction"&&e!=="resolve"&&e!=="degrade"||typeof t.contractId!="string"||t.contractId.length>128||typeof t.at!="number")return null;let o={obligationId:typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:xe(t.contractId),contractId:t.contractId,at:t.at};if(e==="add")return ke(t.contract)?{kind:e,...o,contract:t.contract}:null;if(e==="correction"){let r=typeof t.fingerprint=="string"?t.fingerprint:t.transcriptHash;return typeof r=="string"&&/^[a-f0-9]{64}$/.test(r)&&Array.isArray(t.violations)&&t.violations.every(s=>typeof s=="string"&&s.length<=240)?{kind:e,...o,fingerprint:r,violations:t.violations}:null}return e==="resolve"?{kind:e,...o}:typeof t.reason=="string"&&t.reason.length<=240?{kind:e,...o,reason:t.reason}:null}function De(i){return i==="add"?0:i==="correction"?1:2}function ke(i){if(!i||typeof i!="object")return false;let t=i,e=t.requiredSections,n=t.prohibitedClaims;return t.version==="1.0"&&typeof t.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(t.id)&&typeof t.runtimeProfilingOccurred=="boolean"&&typeof t.samplingEvidenceOccurred=="boolean"&&Array.isArray(e)&&e.length===3&&e[0]==="\u5DE5\u5177\u53D1\u73B0"&&e[1]==="\u6A21\u578B\u5047\u8BBE"&&e[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(n)&&n.length<=16&&n.every(o=>typeof o=="string"&&o.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 J(i){if(!i||typeof i!="object"||Array.isArray(i))return {};let t=i,e={};for(let n of ["lastMcpCall","bypassCount"])if(n in t){let o=t[n];if(o==null)continue;e[n]=typeof o=="number"&&Number.isFinite(o)&&o>=0?o:0;}return e}function Mt(i,t){return i.lastMcpCall===t.lastMcpCall&&i.bypassCount===t.bypassCount}function Se(i,t,e){let n=e instanceof Error?e.message:String(e);D({event:"hook.runtime.degraded",identity:{projectRoot:i},level:"warn",timestamp:Date.now(),data:{stage:"enforcement_receipt",operation:t,reason:n,fallback:"fail_open"}});}function Oe(i,t,e){let n;try{n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let o={},r=n.updateHookReceipt(i,c=>(o=J(c),J(t(o)))),s=J(r);return {receipt:s,applied:!0,changed:!Mt(o,s)}}catch(o){return Se(i,e,o),{receipt:{},applied:false,changed:false}}finally{try{n?.close();}catch{}}}function Ae(i){let t;try{return t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),J(t.getHookReceipt(i))}catch(e){return Se(i,"update",e),{}}finally{try{t?.close();}catch{}}}function $t(i,t){return Oe(i,()=>t,"write").applied}function Nt(i,t){return Oe(i,t,"update")}var Q={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},Ut=new Set(["Write","Edit","NotebookEdit"]),Ht=new Set(["failed","timeout","unavailable"]);function qt(i){switch(i){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var B=class{constructor(t,e,n){this.projectRoot=t;this.sessionId=e;this.executionId=n;}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{}}let e=new S(this.projectRoot).get(this.sessionId);return e?.executionId===this.executionId&&e.contextInitialization?"context_initializing":"context_gathering"}getContextReceipt(){if(!this.sessionId||!this.executionId)return null;let t;try{t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let e=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);return e&&e.expiresAt>Date.now()?e:(e&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId),null)}catch{return null}finally{try{t?.close();}catch{}}}evaluate(t,e){let n=this.getPhase();if(e||t==="Skill")return {permissionDecision:"allow"};if(n==="context_initializing"&&Q[t])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_INITIALIZING",reason:`DevFlow context initialization is in progress. Wait for ${projectClaudeToolName("get_project_context")} to complete, then retry ${t}.`};if(n==="context_gathering"&&Q[t])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_REQUIRED",reason:`DevFlow context required. Call ${projectClaudeToolName("get_project_context")}, then retry ${t}.`};if(n==="context_ready"){if(Ut.has(t)){let a=this.evaluateRequiredAction();if(a)return a}return {permissionDecision:"allow"}}let o=Q[t];if(!o)return {permissionDecision:"allow"};let r=Nt(this.projectRoot,a=>({...a,bypassCount:(a.bypassCount??0)+1}));if(!r.applied)return {permissionDecision:"allow"};let s=r.receipt.bypassCount??0,c=qt(t);return s>=c?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \u6B21\u76F4\u63A5\u4F7F\u7528 ${t}\uFF0C\u5EFA\u8BAE\u7528 ${projectClaudeToolName(o)} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){$t(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}recordDomainActionOutcome(t,e,n,o){if(!this.sessionId||!this.executionId)return false;let r;try{r=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let s=r.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(!s||s.expiresAt<=Date.now()||s.canonicalAction?.tool!==t)return !1;let c=Date.now(),a=o?.trim()?`${o.trim()}:${e}`:`${t}:${e}:${c}`,l=s.actionAttempts??[];return r.upsertContextReceipt({...s,actionAttempts:l.some(d=>d.id===a||o&&d.toolUseId===o&&d.status===e)?l:[...l,{id:a,tool:t,status:e,attemptedAt:c,toolUseId:o,reason:n?.slice(0,500)}].slice(-20),actionSatisfiedAt:e==="succeeded"?c:s.actionSatisfiedAt,actionDegradation:e==="succeeded"?void 0:s.actionDegradation}),!0}catch{return false}finally{try{r?.close();}catch{}}}evaluateRequiredAction(){let t=this.getContextReceipt(),e=t?.canonicalAction;if(!t||!e||!e.required||e.status!=="required")return null;let n=e.binding;if(n.requiredContextReceipt!==t.contextHash||n.projectRoot!==this.projectRoot||n.sessionId!==this.sessionId||n.requestId!==t.requestId||n.executionId&&n.executionId!==this.executionId)return {permissionDecision:"deny",reasonCode:"DEVFLOW_ACTION_BINDING_STALE",reason:`DevFlow canonical action binding is stale or mismatched. Call ${projectClaudeToolName("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 o=(t.actionAttempts??[]).filter(r=>r.tool===e.tool&&Ht.has(r.status));if(o.length>0){let r=o.at(-1),s={missedTool:e.tool,failedAttemptCount:o.length,reason:`${r.status}:${r.reason??"canonical domain action did not complete"}`,authorizedByContextReceipt:t.contextHash,authorizedAt:Date.now()};return this.persistDegradation(t,s),{permissionDecision:"allow",additionalContext:`DevFlow canonical tool ${projectClaudeToolName(e.tool)} ${r.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 ${projectClaudeToolName(e.tool)} using context receipt ${t.contextHash}, then retry the write. Direct fallback is allowed only after unavailable, failed, or timeout evidence.`}}persistDegradation(t,e){let n;try{n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let o=n.getContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!o||o.contextHash!==t.contextHash||o.actionDegradation)return;n.upsertContextReceipt({...o,actionDegradation:e});let r=n.getSkillExecution(t.executionId);if(!r)return;let s=r.metadata&&typeof r.metadata=="object"?r.metadata:{},c=Array.isArray(s.requiredActionDegradations)?s.requiredActionDegradations:[];n.updateSkillExecution(t.executionId,{missedMcpTools:[...new Set([...r.missedMcpTools??[],e.missedTool])],failedToolCalls:Math.max(r.failedToolCalls??0,e.failedAttemptCount),fallbackCount:(r.fallbackCount??0)+1,fallbackReasons:[...new Set([...r.fallbackReasons??[],`required_action_${e.reason}`])],metadata:{...s,requiredActionDegradations:[...c,e]}});}catch{}finally{try{n?.close();}catch{}}}};var Xt=10*1024*1024,Qt=5;function Zt(i){return createHash$1("sha256").update(i).digest("hex").slice(0,16)}function Ce(i){return join(homedir(),".devflow","logs","hook-debug",`${Zt(i)}.jsonl`)}function Te(i,t,e={}){let n=e.maxBytes??Xt,o=e.maxFiles??Qt;mkdirSync$1(dirname(i),{recursive:true,mode:448});let r=Buffer.byteLength(t);rotateDiagnosticLogFile({path:i,maxBytes:n,maxFiles:o,incomingBytes:r}),appendFileSync(i,t,{mode:384}),chmodSync(i,384);}var Z="WARNING: DevFlow is in degraded mode (daemon unreachable): 4-Gate enforcement and memory prefetch cache are unavailable. Run `devflow doctor` for details.";function Fe(){return process.env.DEVFLOW_HOOK_DEGRADED==="1"}function Le(i){let t=i.trim().replace(/^\//,"");if(!t.startsWith("devflow:"))return null;let e=t.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(e)?`devflow:${e.toLowerCase()}`:null}function je(i,t){return t?`evt_tool_${createHash("sha256").update(`${i}\0${t}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var rn=new Set(["Write","Edit","NotebookEdit"]),Pe=`Claude native memory writes are disabled for this project. Use DevFlow explicit memory or ${projectClaudeToolName("memory_commit_turn")} so a canonical receipt is created.`;function He(i){if(!rn.has(i.toolName))return null;let t=sn(i.toolInput);if(!t)return null;let e=an(t,i.projectRoot),n=resolve(i.projectRoot,".claude");if(Me(e,n)&&basename(e).toLocaleUpperCase("en-US")==="MEMORY.MD")return Pe;let o=resolve(i.home??homedir(),".claude","projects");return Me(e,o)&&relative(o,e).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?Pe:null}function sn(i){for(let t of ["file_path","notebook_path","path"]){let e=i[t];if(typeof e=="string"&&e.trim())return e.trim()}return null}function an(i,t){return resolve(isAbsolute(i)?i:resolve(t,i))}function Me(i,t){let e=relative(t,i);return e===""||!e.startsWith(`..${sep}`)&&e!==".."&&!isAbsolute(e)}function Be(i){let t=mn(i.toolName,i.toolInput),e=t?hn(i.projectRoot,i.toolName,i.toolInput):void 0;if(!t||!e||!i.toolUseId)return {allowed:true};let n=vn(e),o,r=0,s,c;try{c=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100,readonly:!0});let l=c.getActiveContextReceipt(i.projectRoot,i.sessionId,i.executionId);o=l?.contextHash,r=l?.issuedAt??0,s=l?.canonicalAction?.binding.operationTargets?.find(d=>bn(i.projectRoot,d.path,e));}catch{}finally{try{c?.close();}catch{}}let a={toolUseId:i.toolUseId,sessionId:i.sessionId,executionId:i.executionId,operation:t,path:e,before:n,contextReceipt:o,observedAt:Date.now()};if(En(i.projectRoot,a),t==="edit"||t==="write"||t==="delete"){let l=wn(i.projectRoot,e),d=l?.success&&l.operation==="delete"&&!l.after.exists&&l.completedAt>=r,u=s?.expectedState==="existing"&&!n.exists||s?.expectedState==="missing"&&n.exists||!!(s?.contentHash&&n.hash!==s.contentHash);if(d||s?.expectedState==="existing"&&!n.exists)return qe(i,a,"DEVFLOW_FILE_STATE_DELETED","The target was deleted after the active Context receipt. Refresh project context before editing or recreating it.");if(u)return qe(i,a,"DEVFLOW_FILE_STATE_STALE","The target state no longer matches the active Context receipt. Refresh project context before overwriting it.")}return Ve(i,a,true),{allowed:true,pending:a}}function qe(i,t,e,n){return Ve(i,t,false,e),{allowed:false,reasonCode:e,reason:n,pending:t}}function Ve(i,t,e,n){D({event:"canonical.action.validated",identity:{projectRoot:i.projectRoot,sessionId:i.sessionId,executionId:i.executionId,contextReceipt:t.contextReceipt},level:e?"info":"warn",timestamp:Date.now(),data:{stage:"host_file_state_precondition",valid:e,operation:t.operation,targetPath:relative(i.projectRoot,t.path),targetExists:t.before.exists,targetHash:t.before.hash,reason:n,toolUseId:t.toolUseId}});}function mn(i,t){if(i==="Read")return "read";if(i==="Edit"||i==="NotebookEdit")return "edit";if(i==="Write")return "write";if(i==="Delete"||i==="Bash"&&ze(t.command))return "delete"}function hn(i,t,e){let n=yn(e,["file_path","filePath","notebook_path","path","targetPath"])??(t==="Bash"?ze(e.command):void 0);if(!n)return;let o=isAbsolute(n)?normalize(n):resolve(i,n),r=relative(i,o);return r.startsWith("..")||isAbsolute(r)?void 0:o}function ze(i){return typeof i!="string"?void 0:/(?:^|[;&|]\s*)\s*(?:rm|unlink)\s+(?:-[A-Za-z]+\s+)*(?:--\s+)?(["']?)([^\s;&|"']+)\1/u.exec(i)?.[2]}function yn(i,t){for(let e of t){let n=i[e];if(typeof n=="string"&&n.trim())return n.trim()}}function vn(i){if(!existsSync$1(i))return {exists:false};try{return {exists:!0,hash:createHash$1("sha256").update(readFileSync$1(i)).digest("hex")}}catch{return {exists:true}}}function bn(i,t,e){return (isAbsolute(t)?normalize(t):resolve(i,t))===normalize(e)}function Ge(i){return join(w(i),"file-state")}function Ye(i){return join(Ge(i),"pending.json")}function _n(i){return join(Ge(i),"observations.jsonl")}function Rn(i){try{return JSON.parse(readFileSync$1(Ye(i),"utf8"))}catch{return {}}}function En(i,t){let e=Ye(i);mkdirSync$1(dirname(e),{recursive:true});let n=Rn(i);n[t.toolUseId]=t,Dn(e,JSON.stringify(n));}function wn(i,t){try{let e=readFileSync$1(_n(i),"utf8").trim().split(`
3
- `);for(let n=e.length-1;n>=0;n-=1){let o=JSON.parse(e[n]);if(o.path===t)return o}}catch{}}function Dn(i,t){let e=`${i}.${process.pid}.${Date.now()}.tmp`;writeFileSync$1(e,t,{encoding:"utf8",mode:384}),renameSync$1(e,i);}var Sn=new Set(["delivered","cancelled","rejected"]),On=new Set(["cancelled","rejected"]),An=new Set(["Write","Edit","NotebookEdit","Bash"]);function Cn(i,t){if(i!=="Bash"||typeof t?.command!="string")return false;let n="git show [A-Za-z0-9._/:@{}^~+\\-]+(?: 2>/dev/null)?";return new RegExp(`^${n}(?: \\|\\| ${n})*$`,"u").test(t.command)}function oe(i,t,e,n,o){if(e.includes("delivery_rebind_session")||!An.has(e)||!t.trim()||Cn(e,o))return null;let r=join(i,".devflow","delivery-line","state.db");if(!existsSync$1(r))return null;let s;try{s=new DatabaseSync(r,{readOnly:!0,timeout:250});let c=s.prepare("SELECT id, payload, updated_at FROM delivery_cases").all(),a=new Set;if(!!s.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'delivery_workflow_bindings'").get()){let f=s.prepare("SELECT case_id, source_path, aliases FROM delivery_workflow_bindings WHERE status = 'enforced'").all();for(let g of f){let b=[];try{b=JSON.parse(g.aliases);}catch{}(g.source_path===i||b.includes(i))&&a.add(g.case_id);}}let d=[];for(let f of c){let g=JSON.parse(f.payload),b=a.has(f.id);(g.sessionId===t||t===f.id||b)&&d.push({id:f.id,payload:g,updatedAt:typeof f.updated_at=="number"?f.updated_at:typeof g.updatedAt=="number"?g.updatedAt:0});let y=typeof g.stage=="string"?g.stage:"unknown";if(!Sn.has(y)){if(n&&y==="executing"){let m=s.prepare("SELECT id, lease_owner, fencing_token FROM delivery_tasks WHERE case_id = ? AND lease_expires_at > ? AND lease_owner IS NOT NULL AND fencing_token > 0 LIMIT 1").get(f.id,Date.now()),v=typeof g.sessionId=="string"?g.sessionId:void 0,j=typeof g.executionId=="string"?g.executionId:void 0,x=n===m?.id||n===m?.lease_owner||n===j,P=t===f.id||t===v;if(m?.id&&x&&P)return null}if(g.sessionId===t||t===f.id||b)return {code:"DELIVERY_AUTHORITY_REQUIRED",caseId:f.id,stage:y,message:`Delivery case ${f.id} is ${y}; use the Delivery task lease before modifying files.`}}}let u=d.sort((f,g)=>g.updatedAt-f.updatedAt)[0],p=typeof u?.payload.stage=="string"?u.payload.stage:void 0;return u&&p&&On.has(p)?{code:"DELIVERY_AUTHORITY_REQUIRED",caseId:u.id,stage:p,message:`Delivery case ${u.id} is ${p}; start a new Delivery case or session before modifying files.`}:null}catch{return {code:"DELIVERY_AUTHORITY_UNAVAILABLE",caseId:"unknown",stage:"unknown",message:"Delivery state cannot be read; file writes are blocked until runtime health is restored."}}finally{s?.close();}}function F(){return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}function re(i){return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:i}}}function Nn(i){let t=w(i);return existsSync(t)||mkdirSync(t,{recursive:true}),t}function Un(i,t,e,n,o,r){let s=join$1(Nn(i),"event-map.json"),c=[];try{existsSync(s)&&(c=JSON.parse(readFileSync(s,"utf-8")));}catch{}c.push({sessionId:t,toolName:e,toolUseId:n,eventId:o,timestamp:r}),writeFileSync(s,JSON.stringify(c));}function Hn(i){switch(i){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 qn(i,t,e){if(t!=="Read"||typeof e.file_path!="string"||!e.file_path.trim())return null;let n=e.file_path.startsWith("/")?e.file_path:join$1(i,e.file_path);try{if(statSync(n).isDirectory())return `Read accepts files, but "${e.file_path}" is a directory. Use Glob or Bash ls to inspect directory entries, then Read one file.`}catch{return null}return null}function Wn(){let i=process.env.CLAUDE_PLUGIN_ROOT;if(!i)return null;let t=join$1(i,"package.json"),e=join$1(i,".mcp.json");try{let n=JSON.parse(readFileSync(t,"utf8")),r=JSON.parse(readFileSync(e,"utf8")).mcpServers?.devflow,s=r?.args;if(r?.command==="node"&&Array.isArray(s)&&s[0]==="${CLAUDE_PLUGIN_ROOT}/node_modules/@devflow-tools/mcp-server/bin/devflow-mcp.cjs")return existsSync(join$1(i,"node_modules/@devflow-tools/mcp-server/bin/devflow-mcp.cjs"))?null:"bundled DevFlow MCP runtime is not installed";let a=Array.isArray(s)?s.indexOf("--package"):-1,l=a>=0&&typeof s?.[a+1]=="string"?s[a+1]:void 0,d=typeof n.version=="string"?`@devflow-tools/mcp-server@${n.version}`:void 0;return l?d&&l!==d?`DevFlow MCP version mismatch (${l} vs ${d})`:null:"DevFlow MCP package configuration is missing"}catch{return "DevFlow MCP configuration could not be inspected"}}function Jn(){let i=process.env.CLAUDE_PLUGIN_ROOT?.trim();if(!i)return null;try{let t=join$1(i,"dist","runtime-manifest.json"),e=JSON.parse(readFileSync(t,"utf8")),n=typeof e.bundleHashes?.mcp=="string"?e.bundleHashes.mcp:void 0,o=join$1(i,"node_modules","@devflow-tools","mcp-server","dist","delivery-tools.js"),r=existsSync(o)?createHash$1("sha256").update(readFileSync(o)).digest("hex"):"missing";return !n||n!==r?"DevFlow runtime build does not match the active plugin manifest":null}catch{return "DevFlow runtime manifest is missing or invalid"}}function Bn(i,t,e){return new Set(["Write","Edit","NotebookEdit"]).has(i)?true:i==="Bash"?!Ke(i,t):!!(e?.startsWith("delivery_")&&e!=="delivery_status")}function Ke(i,t){return i==="Grep"||i==="Glob"?true:i!=="Bash"||typeof t.command!="string"?false:/^(?:ls|pwd|find|rg|grep|git\s+(?:status|diff|log|branch)|cat|sed|head|tail|wc)\b/u.test(t.command.trim())}async function Vn(i){let t=Fe();try{if(!i||i.trim()==="")return F();let e=JSON.parse(i),n=Date.now();try{maybeRunDiagnosticLogCleanup(T(),{now:n});}catch{}let o=T(),r=new H,s=resolveClaudeToolName(e.tool_name,e.tool_input),c=s.status==="unsupported"?void 0:s.canonicalName;c&&(typeof e.tool_input.projectRoot!="string"||!e.tool_input.projectRoot.trim())&&(e.tool_input.projectRoot=o);let a=e.session_id?.trim();if(!a)return re(Z);let l=new S(o),d=l.get(a)!==null;if(l.registerSession(a),d||await r.sendSessionStart(a,o,Date.now()),e.tool_name==="Skill"){let _=e.tool_input?.skill,h=_?Le(_):null;if(h){let R=l.get(a)?.executionId,E=l.startExecution(a,h,he(h));E.executionId&&E.executionId!==R&&await r.sendExecutionStart(E.executionId,a,h,E.lastActivityAt,o,E.requiredMcpTools);}}let u=l.get(a);c==="get_project_context"&&l.beginContextInitialization(a,e.tool_use_id),c&&(e.tool_input._devflow_session_id=a,e.tool_input._devflow_execution_id=u?.executionId??a,u?.activeTurnId&&(e.tool_input._devflow_turn_id=u.activeTurnId),u?.activeRequestId&&(e.tool_input._devflow_request_id=u.activeRequestId),u?.intentArtifactHash&&(e.tool_input._devflow_intent_artifact_hash=u.intentArtifactHash),u?.skillName&&(e.tool_input._devflow_active_skill=u.skillName),e.tool_use_id&&(e.tool_input._devflow_tool_use_id=e.tool_use_id));let p=e.tool_name.startsWith("mcp__"),f=c,g=l.get(a),b=new B(o,a,g?.executionId),y=b.getPhase(),m,v,j=qn(o,e.tool_name,e.tool_input),x=oe(o,a,e.tool_name,g?.executionId,e.tool_input),P=!x&&Bn(e.tool_name,e.tool_input,f)?Jn():null;if(P)v="DEVFLOW_RUNTIME_VERSION_MISMATCH",m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${P}. Update or restart the DevFlow plugin before approving, executing, or modifying files.`}};else if(j)v="DEVFLOW_DIRECTORY_READ_INVALID",m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:j}};else if(x)v=x.code,m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${x.message} Resolve the case blocker or obtain an authorized task lease before retrying.`}};else {let _=He({toolName:e.tool_name,toolInput:e.tool_input,projectRoot:o}),h=Be({projectRoot:o,sessionId:a,executionId:g?.executionId,toolUseId:e.tool_use_id,toolName:e.tool_name,toolInput:e.tool_input}),R=_?{permissionDecision:"deny",reason:_}:h.allowed?b.evaluate(e.tool_name,p):{permissionDecision:"deny",reason:h.reason,reasonCode:h.reasonCode},E=R.permissionDecision==="deny"&&!p&&Ke(e.tool_name,e.tool_input)?Wn():null;E?(m=re(`DevFlow MCP is unavailable or stale: ${E}. This read-only fallback is temporary; refresh the plugin installation and call ${projectClaudeToolName("get_project_context")} before editing.`),v=void 0):R.permissionDecision==="deny"?(v=_?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":R.reasonCode??"DEVFLOW_CONTEXT_REQUIRED",m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:R.reason??"MCP context required"}}):R.additionalContext?m=re(R.additionalContext):m=F();}c&&(m.hookSpecificOutput.updatedInput=e.tool_input),t&&m.hookSpecificOutput.permissionDecision==="allow"&&(m.hookSpecificOutput.additionalContext=Z);let Xe=g?.executionId??a,C={eventId:je(a,e.tool_use_id),executionId:Xe,sessionId:a,projectRoot:o,toolUseId:e.tool_use_id,timestamp:Date.now(),toolName:e.tool_name,toolType:p?"mcp":e.tool_name==="Agent"?"subagent":"direct",isMcpTool:p,mcpToolName:f,mcpEnforced:p&&(y==="context_gathering"||y==="context_initializing"),mcpFallback:!p&&(y==="context_gathering"||y==="context_initializing"),kind:Hn(e.tool_name),input:e.tool_input,duration:0,blocked:m.hookSpecificOutput.permissionDecision==="deny",blockReason:m.hookSpecificOutput.permissionDecision==="deny"?v??"DEVFLOW_CONTEXT_REQUIRED":void 0},M=await r.sendEvent(C);M&&!C.blocked&&Un(o,a,e.tool_name,e.tool_use_id,M,C.timestamp),M&&C.blocked&&await r.completeEvent({eventId:M,sessionId:a,error:v??"DEVFLOW_CONTEXT_REQUIRED",duration:Date.now()-C.timestamp,completedAt:Date.now()});try{let _=Ae(o),h={ts:n,tool:e.tool_name,sessionId:a,skill:u?.skillName??"(none)",requiredTools:u?.requiredMcpTools??[],isMcp:p,enforce:u?.executionId!==void 0,stateless:u?.executionId===void 0&&!p&&e.tool_name!=="Skill",bypassCount:_.bypassCount??0,decision:m.hookSpecificOutput.permissionDecision,env_CLAUDE_PLUGIN_ROOT:process.env.CLAUDE_PLUGIN_ROOT??"(unset)",cwd:process.cwd()};Te(Ce(o),`${JSON.stringify(h)}
1
+ import {createHash as createHash$1}from'node:crypto';import {existsSync,readdirSync,readFileSync,unlinkSync,mkdirSync,writeFileSync,rmSync,linkSync,renameSync,statSync}from'fs';import {join as join$1,dirname as dirname$1}from'path';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {getLocalApiKey,getDevFlowStateRoot,projectClaudeToolName,resolveClaudeToolName,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,getProjectStateDir,readRuntimeState}from'@devflow-tools/sdk';import {request}from'node:http';import {existsSync as existsSync$1,mkdirSync as mkdirSync$1,appendFileSync,chmodSync,readFileSync as readFileSync$1,writeFileSync as writeFileSync$1,renameSync as renameSync$1}from'node:fs';import {join,resolve,basename,relative,sep,dirname,isAbsolute,normalize}from'node:path';import {maybeRunDiagnosticLogCleanup,rotateDiagnosticLogFile,emitSemanticControlLog}from'@devflow-tools/telemetry';import {fileURLToPath}from'url';import {randomUUID,createHash}from'crypto';import {homedir}from'node:os';import {DatabaseSync}from'node:sqlite';function M(i,t,e){try{let n=openGlobalDevFlowDatabase();try{n.insertEvent({kind:i,timestamp:Date.now(),duration:e,success:t.success!==!1,metadata:t});}finally{n.close();}}catch{}}var dt=getLocalApiKey(),G=join(getDevFlowStateRoot(),"errors");async function ce(i,t,e={}){let n=e.endpoint??process.env.DEVFLOW_SERVER_URL?.trim()??ut();if(!n)return {delivered:false,suppressed:false,fallbackReason:"runtime_not_ready"};let o=e.timeout??1500,r=e.durableMirror??true,s=e.maxRetries??(r?0:2),c=e.circuitBreaker??true,a=acquireRuntimeHttpCircuit(n,i);if(c&&!a.allowed)return {delivered:false,suppressed:true,fallbackReason:a.state.fallbackReason};let l;for(let u=0;u<=s;u+=1)try{return await pt(n,i,t,o),c&&registerRuntimeHttpSuccess(n,i).transitioned&&M("http_circuit_transition",{endpoint:n,path:new URL(i,n).pathname,previous:a.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(p){l=p instanceof Error?p:new Error(String(p)),u<s&&await gt(Math.min(100*2**u,1e3));}if(!l)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!c)return se(i,l),{delivered:false,suppressed:false,fallbackReason:l.message};let d=registerRuntimeHttpFailure(n,i,e.fallbackReason??(r?"local_durable_mirror":"http_delivery_failed"));return d.transitioned&&(se(i,l),M("http_circuit_transition",{endpoint:n,path:new URL(i,n).pathname,previous:a.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 ut(){let i=readRuntimeState();return i?.status==="ready"&&i.dashboardAvailable?i.url:void 0}function pt(i,t,e,n){return new Promise((o,r)=>{let s=JSON.stringify(e),c=new URL(t,i),a=false,l=u=>{a||(a=true,u?r(u):o());},d=request({hostname:c.hostname,port:c.port,path:c.pathname+c.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":dt,"Content-Length":Buffer.byteLength(s)},timeout:n},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 ${n}ms`))),d.write(s),d.end();})}function se(i,t){try{existsSync$1(G)||mkdirSync$1(G,{recursive:!0});let e=join(G,"http-errors.log"),n=`${new Date().toISOString()} | ${i} | ${t.message}
2
+ `;rotateDiagnosticLogFile({path:e,maxBytes:50*1024*1024,maxFiles:5,incomingBytes:Buffer.byteLength(n)}),appendFileSync(e,n);}catch{}}function gt(i){return new Promise(t=>setTimeout(t,i))}var pe=1e4,bt=3e4,U=500,H=class{constructor(t){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=t?.apiUrl,this.cacheDir=t?.cacheDir??join$1(getDevFlowStateRoot(),"global","telemetry-cache"),this.database=t?.database??null,this.ownsDatabase=!t?.database;let e=t?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(e)&&e>=0?e:100;}async sendEvent(t){let e={...t,input:this.truncateInput(t.input)};return this.commitOrCache("tool_call",e)?(this.postHttp("/api/telemetry/tool-call",e),t.eventId):null}async sendExecutionStart(t,e,n,o,r=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let c={executionId:t,sessionId:e,skillName:n,startedAt:o,projectRoot:r,requiredMcpTools:s};this.commitOrCache("execution_start",c)&&this.postHttp("/api/telemetry/skill-execution/start",c);}async sendExecutionComplete(t,e="completed",n=Date.now(),o){let r={executionId:t,status:e,finishedAt:n,metadata:o},s=this.commitOrCache("execution_complete",r);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",r),s}async sendSessionStart(t,e,n){let o={id:t,projectRoot:e,startedAt:n,label:e.split("/").pop()??"unknown"},r=this.commitOrCache("session_start",o);return r&&this.postHttp("/api/telemetry/sessions",o),r}async completeEvent(t){let e=this.commitOrCache("complete_event",t);return e&&(this.postHttp("/api/telemetry/tool-call/output",t),this.scheduleMetricAggregation()),e}async endSession(t,e=Date.now()){let n={sessionId:t,finishedAt:e},o=this.commitOrCache("session_end",n);return o&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:e})),o}async flushCache(){try{let e=this.getDatabase(),n=e.listTelemetryFailures({unresolvedOnly:!0,limit:U}).reverse();for(let o of n)try{this.applyOperation(o.operation,o.payload),e.resolveTelemetryFailure(o.id);}catch{}e.trimTelemetryFailures(U);}catch{}let t=(existsSync(this.cacheDir)?readdirSync(this.cacheDir):[]).filter(e=>e.endsWith(".json")).map(e=>{let n=join$1(this.cacheDir,e);try{return {cacheFile:n,envelope:_t(JSON.parse(readFileSync(n,"utf8")))}}catch{return null}}).filter(e=>e!==null).sort((e,n)=>e.envelope.timestamp-n.envelope.timestamp||ge(e.envelope.operation)-ge(n.envelope.operation));for(let{cacheFile:e,envelope:n}of t)try{let o=this.getDatabase();o.insertTelemetryFailure({id:n.id,operation:n.operation,payload:n.payload,error:n.failure,createdAt:n.timestamp}),this.applyOperation(n.operation,n.payload),o.resolveTelemetryFailure(n.id),unlinkSync(e);}catch{}this.database?.aggregatePendingToolMetrics();}aggregateMetrics(){return this.getDatabase().aggregatePendingToolMetrics()}async flushAndAggregate(){await this.flushCache(),this.aggregateMetrics();}close(){this.ownsDatabase&&this.database?.close(),this.database=null;}getDatabase(){return this.database??=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:this.busyTimeoutMs}),this.database}commitOrCache(t,e){try{return this.applyOperation(t,e),!0}catch(n){return this.cacheOperation(t,e,n),false}}applyOperation(t,e){let n=this.getDatabase();switch(t){case "tool_call":this.ensureParentSession(n,e),n.insertToolCallEvent(e);return;case "execution_start":this.ensureParentSession(n,e),n.insertSkillExecution({executionId:e.executionId,sessionId:e.sessionId,skillName:e.skillName,startedAt:e.startedAt,status:"running",requiredMcpTools:e.requiredMcpTools});return;case "execution_complete":n.reconcileSkillExecution(e.executionId,e.status,e.finishedAt,e.metadata);return;case "session_start":n.ensureSession(e),n.insertRun({id:fe(e.id),source:"hook",tool:"session",input:{projectRoot:e.projectRoot},status:"active",startedAt:e.startedAt,tokenUsed:0,metadata:{sessionId:e.id,projectRoot:e.projectRoot}});return;case "complete_event":if(!n.updateToolCallEvent(e.eventId,{output:e.output===void 0?void 0:JSON.stringify(e.output),error:e.error,failureCategory:e.failureCategory,duration:e.duration}))throw new Error(`Tool call event ${e.eventId} is not available for completion`);return;case "session_end":n.closeSession(e.sessionId,e.finishedAt),n.updateRun(fe(e.sessionId),{status:"completed",finishedAt:e.finishedAt});return}}ensureParentSession(t,e){let n=typeof e.sessionId=="string"?e.sessionId.trim():"";if(!n)throw new Error("Canonical session ID is required for telemetry");let o=typeof e.projectRoot=="string"&&e.projectRoot.trim()?e.projectRoot:typeof e.input?.projectRoot=="string"&&e.input.projectRoot.trim()?e.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";t.ensureSession({id:n,projectRoot:o,label:o==="unknown"?void 0:o.split("/").pop(),startedAt:Number(e.startedAt??e.timestamp??Date.now())});}cacheOperation(t,e,n){let o=Date.now(),r={id:`failure:${o}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:e,failure:n instanceof Error?n.message:String(n),timestamp:o};try{let s=this.getDatabase();s.insertTelemetryFailure({id:r.id,operation:t,payload:e,error:r.failure,createdAt:o}),s.trimTelemetryFailures(U),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${o}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(s,JSON.stringify(r,null,2),{mode:384}),this.trimRetryCache(),this.scheduleRetry();}catch{}}trimRetryCache(){try{let t=readdirSync(this.cacheDir).filter(e=>e.endsWith(".json")).sort();for(let e of t.slice(0,Math.max(0,t.length-U)))unlinkSync(join$1(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},bt).unref());}scheduleMetricAggregation(){if(this.metricAggregationScheduled||process.env.DEVFLOW_HOOK_DEGRADED==="1")return;this.metricAggregationScheduled=true,setTimeout(()=>{this.metricAggregationScheduled=false;try{this.getDatabase().aggregatePendingToolMetrics(50)===50&&this.scheduleMetricAggregation();}catch{}},25).unref();}postHttp(t,e){ce(t,e,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=pe?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,pe)}...`}}};function ge(i){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(i)}function fe(i){return `hook-run:${i}`}function _t(i){if(!i||typeof i!="object")throw new Error("Invalid telemetry cache envelope");let t=i;if(typeof t.id!="string"||typeof t.operation!="string"||t.payload===void 0||typeof t.failure!="string"||typeof t.timestamp!="number")throw new Error("Invalid telemetry cache envelope");return t}function T(i){return i??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function w(i){return getProjectStateDir(T(i))}var D=emitSemanticControlLog;var kt=2,St=1;function Ot(){if(process.env.CLAUDE_PLUGIN_ROOT)return process.env.CLAUDE_PLUGIN_ROOT;try{return join$1(dirname$1(fileURLToPath(import.meta.url)),"..","..")}catch{return process.cwd()}}function me(i=Ot()){let t=[join$1(i,"dist","command-registry.json"),join$1(i,"command-registry.json")];for(let e of t)try{if(!existsSync(e))continue;let n=JSON.parse(readFileSync(e,"utf8"));if(n.version!==kt&&n.version!==St||!At(n.commands)){D({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:e}});continue}return n.commands}catch(n){D({event:"hook.runtime.degraded",identity:{projectRoot:process.env.CLAUDE_PROJECT_DIR||process.cwd()},level:"warn",timestamp:Date.now(),data:{stage:"command_registry",reason:n.message,fallback:"next_registry_candidate"}});}return null}function At(i){return !i||typeof i!="object"||Array.isArray(i)?false:Object.values(i).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return q(e.mcpTools)&&q(e.blockedNative)&&(e.source===void 0||e.source==="core"||e.source==="plugin")&&(e.requiresContext===void 0||typeof e.requiresContext=="boolean")&&(e.runtimePackages===void 0||q(e.runtimePackages))&&(e.hostTools===void 0||Ct(e.hostTools))&&(e.evidenceMode===void 0||["static","runtime","mixed"].includes(e.evidenceMode))})}function Ct(i){return !!i&&typeof i=="object"&&!Array.isArray(i)&&Object.entries(i).every(([t,e])=>t.length>0&&q(e))}function q(i){return Array.isArray(i)&&i.every(t=>typeof t=="string"&&t.length>0)}function he(i){let t=me();return t?t[i]?.mcpTools??[]:[]}function _e(i){return Buffer.from(i,"utf8").toString("base64url")}function jt(i,t,e){let n=t?.trim();if(n){let o=/^[a-zA-Z0-9:._-]{1,192}$/.test(n)?n:`tool-${createHash("sha256").update(n.slice(0,1024)).digest("hex").slice(0,32)}`;return `${i}:${o}`}return `${i}:legacy-${e}-${randomUUID().slice(0,8)}`}function xe(i){return `${i}:legacy-journal`}var S=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(w(t),"hook-sessions");}registerSession(t){let e=t.trim();if(!e)throw new Error("session_id_required");let n=this.get(e);if(n)return n.lastActivityAt=Date.now(),this.persist(n),n;let o=Date.now(),r={sessionId:e,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:o,lastActivityAt:o};return this.sessions.set(e,r),this.persist(r),r}startExecution(t,e,n){let o=this.registerSession(t);return (!o.executionId||o.skillName!==e)&&(o.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),o.skillName=e,o.requiredMcpTools=[...new Set(n)],delete o.contextInitialization,o.lastActivityAt=Date.now(),this.persist(o),o}beginContextInitialization(t,e){let n=this.registerSession(t);return n.contextInitialization={startedAt:Date.now(),...e?{toolUseId:e}:{}},n.lastActivityAt=Date.now(),this.persist(n),n}completeContextInitialization(t,e){let n=this.get(t);return n?(e&&n.contextInitialization?.toolUseId&&n.contextInitialization.toolUseId!==e||(delete n.contextInitialization,n.lastActivityAt=Date.now(),this.persist(n)),n):null}bindTaskIdentity(t,e){let n=this.registerSession(t);return n.activeTurnId=e.turnId,n.activeRequestId=e.requestId,n.intentArtifactHash=e.intentArtifactHash,n.lastActivityAt=Date.now(),this.persist(n),n}get(t){let e=t.trim();if(!e)return null;let n=this.sessions.get(e);if(n)return this.replayEvidenceJournal(n),n;let o=this.snapshotPath(e);if(!existsSync(o))return null;try{let r=JSON.parse(readFileSync(o,"utf8"));return r.sessionId!==e||r.projectRoot!==this.projectRoot?null:(r.requiredMcpTools=Array.isArray(r.requiredMcpTools)?r.requiredMcpTools:[],r.evidenceObligations=Re(r.evidenceObligations),r.evidenceDegradations=Ee(r.evidenceDegradations),r.evidenceOutcomes=we(r.evidenceOutcomes),this.replayEvidenceJournal(r),this.sessions.set(e,r),r)}catch{return null}}completeExecution(t){let e=this.get(t);if(!e)return null;let n=structuredClone(e);return delete e.executionId,delete e.skillName,delete e.contextInitialization,e.requiredMcpTools=[],e.lastActivityAt=Date.now(),this.persist(e),n}addEvidenceObligation(t,e,n=Date.now(),o){let r=this.registerSession(t),c=(o?void 0:r.evidenceObligations.find(l=>l.contractId===e.id))?.obligationId??jt(e.id,o,n);this.appendEvidenceEvent(t,{kind:"add",obligationId:c,contractId:e.id,at:n,contract:e},`add\0${c}`),this.replayEvidenceJournal(r);let a=r.evidenceObligations.find(l=>l.obligationId===c);return a?(r.lastActivityAt=Date.now(),this.persist(r),structuredClone(a)):null}listEvidenceObligations(t){return (this.get(t)?.evidenceObligations??[]).map(e=>structuredClone(e))}markEvidenceCorrection(t,e,n,o,r=Date.now()){let s=this.get(t),c=s?.evidenceObligations.find(d=>d.obligationId===e);if(!s||!c)return null;let a=/^[a-f0-9]{64}$/.test(o)?o:"";if(!a)return null;this.appendEvidenceEvent(t,{kind:"correction",obligationId:e,contractId:c.contractId,at:r,fingerprint:a,violations:n.slice(0,16).map(d=>d.slice(0,240))},`correction\0${e}\0${a}`),this.replayEvidenceJournal(s),s.lastActivityAt=r,this.persist(s);let l=s.evidenceObligations.find(d=>d.obligationId===e);return l?structuredClone(l):null}resolveEvidenceObligation(t,e){let n=this.get(t);if(!n)return false;let o=n.evidenceObligations.find(s=>s.obligationId===e);if(!o)return false;let r=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:o.contractId,at:r},`resolve\0${e}`),this.replayEvidenceJournal(n),n.lastActivityAt=r,this.persist(n),true}resolveDegradedEvidence(t,e){let n=this.get(t),o=n?.evidenceDegradations.find(s=>s.obligationId===e);if(!n||!o)return false;let r=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:o.contractId,at:r},`resolve-degraded\0${e}\0${r}`),this.replayEvidenceJournal(n),n.lastActivityAt=r,this.persist(n),true}degradeEvidenceObligation(t,e,n,o=Date.now()){let r=this.get(t),s=r?.evidenceObligations.find(a=>a.obligationId===e);if(!r||!s)return false;let c=n.slice(0,240);return this.appendEvidenceEvent(t,{kind:"degrade",obligationId:e,contractId:s.contractId,at:o,reason:c},`degrade\0${e}\0${c}`),this.replayEvidenceJournal(r),r.lastActivityAt=o,this.persist(r),true}removeSession(t){let e=t.trim();e&&(this.sessions.delete(e),rmSync(this.snapshotPath(e),{force:true}),rmSync(this.evidenceJournalDir(e),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(t){return join$1(this.sessionsDir,`${_e(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",_e(t))}appendEvidenceEvent(t,e,n){let o=this.evidenceJournalDir(t);mkdirSync(o,{recursive:true,mode:448});let r=createHash("sha256").update(n).digest("hex"),s=join$1(o,`${e.kind}-${r}.json`);if(existsSync(s))return;let c=join$1(o,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync(c,JSON.stringify(e),{mode:384});try{linkSync(c,s);}catch(a){if(a.code!=="EEXIST")throw a}finally{rmSync(c,{force:true});}}replayEvidenceJournal(t){t.evidenceObligations=Re(t.evidenceObligations),t.evidenceDegradations=Ee(t.evidenceDegradations),t.evidenceOutcomes=we(t.evidenceOutcomes);let e=this.evidenceJournalDir(t.sessionId);if(!existsSync(e))return;let n;try{n=readdirSync(e).filter(r=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(r)).slice(0,4096);}catch{return}let o=n.flatMap(r=>{try{let s=readFileSync(join$1(e,r),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let c=Pt(JSON.parse(s));return c?[c]:[]}catch{return []}}).sort((r,s)=>r.at-s.at||De(r.kind)-De(s.kind));for(let r of o)this.applyEvidenceEvent(t,r);t.evidenceObligations=t.evidenceObligations.slice(-8),t.evidenceDegradations=t.evidenceDegradations.slice(-20),t.evidenceOutcomes=t.evidenceOutcomes.slice(-20);}applyEvidenceEvent(t,e){let n=t.evidenceOutcomes.find(s=>s.obligationId===e.obligationId);if(e.kind==="add"){if(n)return;let s=t.evidenceObligations.find(c=>c.obligationId===e.obligationId);s?(s.contract=e.contract,s.promptedAt=Math.min(s.promptedAt,e.at)):t.evidenceObligations.push({obligationId:e.obligationId,contractId:e.contractId,contract:e.contract,promptedAt:e.at,attempt:0,correctionRequested:false,violations:[]});return}let o=t.evidenceObligations.find(s=>s.obligationId===e.obligationId);if(e.kind==="correction"){if(!o||n||o.correctionFingerprint===e.fingerprint)return;o.attempt+=1,o.correctionRequested=true,o.correctionRequestedAt=e.at,o.correctionFingerprint=e.fingerprint,o.violations=e.violations;return}let r=o?.attempt??n?.attempt??0;if(e.kind==="resolve"&&n?.status==="degraded")t.evidenceOutcomes=t.evidenceOutcomes.filter(s=>s.obligationId!==e.obligationId),t.evidenceDegradations=t.evidenceDegradations.filter(s=>s.obligationId!==e.obligationId);else if(n)return;e.kind==="degrade"?(t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==e.obligationId),t.evidenceDegradations.push({obligationId:e.obligationId,contractId:e.contractId,reason:e.reason,degradedAt:e.at,attempt:r,contract:o?.contract})):t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==e.obligationId),t.evidenceOutcomes.push({obligationId:e.obligationId,contractId:e.contractId,status:e.kind==="resolve"?"resolved":"degraded",completedAt:e.at,attempt:r,...e.kind==="degrade"?{reason:e.reason}:{}});}persist(t){mkdirSync(this.sessionsDir,{recursive:true,mode:448});let e=this.snapshotPath(t.sessionId),n=`${e}.${process.pid}.${randomUUID()}.tmp`;writeFileSync(n,JSON.stringify(t),{mode:384}),renameSync(n,e);}};function Re(i){return Array.isArray(i)?i.flatMap(t=>{if(!t||typeof t!="object")return [];let e=t;if(typeof e.contractId!="string"||e.contractId.length===0||e.contractId.length>128||typeof e.promptedAt!="number"||typeof e.attempt!="number"||typeof e.correctionRequested!="boolean"||!Array.isArray(e.violations)||!ke(e.contract))return [];let n=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:xe(e.contractId),o=typeof e.correctionTranscriptHash=="string"?e.correctionTranscriptHash:void 0,r=e.correctionFingerprint??o;return r!==void 0&&!/^[a-f0-9]{64}$/.test(r)?[]:[{...e,obligationId:n,correctionFingerprint:r}]}).slice(-8):[]}function Ee(i){return Array.isArray(i)?i.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&typeof e.reason=="string"&&typeof e.degradedAt=="number"&&typeof e.attempt=="number"}).slice(-20):[]}function we(i){return Array.isArray(i)?i.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&(e.status==="resolved"||e.status==="degraded")&&typeof e.completedAt=="number"&&typeof e.attempt=="number"&&(e.reason===void 0||typeof e.reason=="string")}).slice(-20):[]}function Pt(i){if(!i||typeof i!="object")return null;let t=i,e=t.kind;if(e!=="add"&&e!=="correction"&&e!=="resolve"&&e!=="degrade"||typeof t.contractId!="string"||t.contractId.length>128||typeof t.at!="number")return null;let o={obligationId:typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:xe(t.contractId),contractId:t.contractId,at:t.at};if(e==="add")return ke(t.contract)?{kind:e,...o,contract:t.contract}:null;if(e==="correction"){let r=typeof t.fingerprint=="string"?t.fingerprint:t.transcriptHash;return typeof r=="string"&&/^[a-f0-9]{64}$/.test(r)&&Array.isArray(t.violations)&&t.violations.every(s=>typeof s=="string"&&s.length<=240)?{kind:e,...o,fingerprint:r,violations:t.violations}:null}return e==="resolve"?{kind:e,...o}:typeof t.reason=="string"&&t.reason.length<=240?{kind:e,...o,reason:t.reason}:null}function De(i){return i==="add"?0:i==="correction"?1:2}function ke(i){if(!i||typeof i!="object")return false;let t=i,e=t.requiredSections,n=t.prohibitedClaims;return t.version==="1.0"&&typeof t.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(t.id)&&typeof t.runtimeProfilingOccurred=="boolean"&&typeof t.samplingEvidenceOccurred=="boolean"&&Array.isArray(e)&&e.length===3&&e[0]==="\u5DE5\u5177\u53D1\u73B0"&&e[1]==="\u6A21\u578B\u5047\u8BBE"&&e[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(n)&&n.length<=16&&n.every(o=>typeof o=="string"&&o.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 J(i){if(!i||typeof i!="object"||Array.isArray(i))return {};let t=i,e={};for(let n of ["lastMcpCall","bypassCount"])if(n in t){let o=t[n];if(o==null)continue;e[n]=typeof o=="number"&&Number.isFinite(o)&&o>=0?o:0;}return e}function $t(i,t){return i.lastMcpCall===t.lastMcpCall&&i.bypassCount===t.bypassCount}function Se(i,t,e){let n=e instanceof Error?e.message:String(e);D({event:"hook.runtime.degraded",identity:{projectRoot:i},level:"warn",timestamp:Date.now(),data:{stage:"enforcement_receipt",operation:t,reason:n,fallback:"fail_open"}});}function Oe(i,t,e){let n;try{n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let o={},r=n.updateHookReceipt(i,c=>(o=J(c),J(t(o)))),s=J(r);return {receipt:s,applied:!0,changed:!$t(o,s)}}catch(o){return Se(i,e,o),{receipt:{},applied:false,changed:false}}finally{try{n?.close();}catch{}}}function Ae(i){let t;try{return t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),J(t.getHookReceipt(i))}catch(e){return Se(i,"update",e),{}}finally{try{t?.close();}catch{}}}function Mt(i,t){return Oe(i,()=>t,"write").applied}function Nt(i,t){return Oe(i,t,"update")}var Q={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},Ut=new Set(["Write","Edit","NotebookEdit"]),Ht=new Set(["failed","timeout","unavailable"]);function qt(i){switch(i){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var B=class{constructor(t,e,n){this.projectRoot=t;this.sessionId=e;this.executionId=n;}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{}}let e=new S(this.projectRoot).get(this.sessionId);return e?.executionId===this.executionId&&e.contextInitialization?"context_initializing":"context_gathering"}getContextReceipt(){if(!this.sessionId||!this.executionId)return null;let t;try{t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let e=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);return e&&e.expiresAt>Date.now()?e:(e&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId),null)}catch{return null}finally{try{t?.close();}catch{}}}evaluate(t,e){let n=this.getPhase();if(e||t==="Skill")return {permissionDecision:"allow"};if(n==="context_initializing"&&Q[t])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_INITIALIZING",reason:`DevFlow context initialization is in progress. Wait for ${projectClaudeToolName("get_project_context")} to complete, then retry ${t}.`};if(n==="context_gathering"&&Q[t])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_REQUIRED",reason:`DevFlow context required. Call ${projectClaudeToolName("get_project_context")}, then retry ${t}.`};if(n==="context_ready"){if(Ut.has(t)){let a=this.evaluateRequiredAction();if(a)return a}return {permissionDecision:"allow"}}let o=Q[t];if(!o)return {permissionDecision:"allow"};let r=Nt(this.projectRoot,a=>({...a,bypassCount:(a.bypassCount??0)+1}));if(!r.applied)return {permissionDecision:"allow"};let s=r.receipt.bypassCount??0,c=qt(t);return s>=c?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \u6B21\u76F4\u63A5\u4F7F\u7528 ${t}\uFF0C\u5EFA\u8BAE\u7528 ${projectClaudeToolName(o)} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){Mt(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}recordDomainActionOutcome(t,e,n,o){if(!this.sessionId||!this.executionId)return false;let r;try{r=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let s=r.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(!s||s.expiresAt<=Date.now()||s.canonicalAction?.tool!==t)return !1;let c=Date.now(),a=o?.trim()?`${o.trim()}:${e}`:`${t}:${e}:${c}`,l=s.actionAttempts??[];return r.upsertContextReceipt({...s,actionAttempts:l.some(d=>d.id===a||o&&d.toolUseId===o&&d.status===e)?l:[...l,{id:a,tool:t,status:e,attemptedAt:c,toolUseId:o,reason:n?.slice(0,500)}].slice(-20),actionSatisfiedAt:e==="succeeded"?c:s.actionSatisfiedAt,actionDegradation:e==="succeeded"?void 0:s.actionDegradation}),!0}catch{return false}finally{try{r?.close();}catch{}}}evaluateRequiredAction(){let t=this.getContextReceipt(),e=t?.canonicalAction;if(!t||!e||!e.required||e.status!=="required")return null;let n=e.binding;if(n.requiredContextReceipt!==t.contextHash||n.projectRoot!==this.projectRoot||n.sessionId!==this.sessionId||n.requestId!==t.requestId||n.executionId&&n.executionId!==this.executionId)return {permissionDecision:"deny",reasonCode:"DEVFLOW_ACTION_BINDING_STALE",reason:`DevFlow canonical action binding is stale or mismatched. Call ${projectClaudeToolName("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 o=(t.actionAttempts??[]).filter(r=>r.tool===e.tool&&Ht.has(r.status));if(o.length>0){let r=o.at(-1),s={missedTool:e.tool,failedAttemptCount:o.length,reason:`${r.status}:${r.reason??"canonical domain action did not complete"}`,authorizedByContextReceipt:t.contextHash,authorizedAt:Date.now()};return this.persistDegradation(t,s),{permissionDecision:"allow",additionalContext:`DevFlow canonical tool ${projectClaudeToolName(e.tool)} ${r.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 ${projectClaudeToolName(e.tool)} using context receipt ${t.contextHash}, then retry the write. Direct fallback is allowed only after unavailable, failed, or timeout evidence.`}}persistDegradation(t,e){let n;try{n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let o=n.getContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!o||o.contextHash!==t.contextHash||o.actionDegradation)return;n.upsertContextReceipt({...o,actionDegradation:e});let r=n.getSkillExecution(t.executionId);if(!r)return;let s=r.metadata&&typeof r.metadata=="object"?r.metadata:{},c=Array.isArray(s.requiredActionDegradations)?s.requiredActionDegradations:[];n.updateSkillExecution(t.executionId,{missedMcpTools:[...new Set([...r.missedMcpTools??[],e.missedTool])],failedToolCalls:Math.max(r.failedToolCalls??0,e.failedAttemptCount),fallbackCount:(r.fallbackCount??0)+1,fallbackReasons:[...new Set([...r.fallbackReasons??[],`required_action_${e.reason}`])],metadata:{...s,requiredActionDegradations:[...c,e]}});}catch{}finally{try{n?.close();}catch{}}}};var Xt=10*1024*1024,Qt=5;function Zt(i){return createHash$1("sha256").update(i).digest("hex").slice(0,16)}function Ce(i){return join(homedir(),".devflow","logs","hook-debug",`${Zt(i)}.jsonl`)}function Te(i,t,e={}){let n=e.maxBytes??Xt,o=e.maxFiles??Qt;mkdirSync$1(dirname(i),{recursive:true,mode:448});let r=Buffer.byteLength(t);rotateDiagnosticLogFile({path:i,maxBytes:n,maxFiles:o,incomingBytes:r}),appendFileSync(i,t,{mode:384}),chmodSync(i,384);}var Z="WARNING: DevFlow is in degraded mode (daemon unreachable): 4-Gate enforcement and memory prefetch cache are unavailable. Run `devflow doctor` for details.";function Fe(){return process.env.DEVFLOW_HOOK_DEGRADED==="1"}function Le(i){let t=i.trim().replace(/^\//,"");if(!t.startsWith("devflow:"))return null;let e=t.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(e)?`devflow:${e.toLowerCase()}`:null}function je(i,t){return t?`evt_tool_${createHash("sha256").update(`${i}\0${t}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var rn=new Set(["Write","Edit","NotebookEdit"]),Pe=`Claude native memory writes are disabled for this project. Use DevFlow explicit memory or ${projectClaudeToolName("memory_commit_turn")} so a canonical receipt is created.`;function He(i){if(!rn.has(i.toolName))return null;let t=sn(i.toolInput);if(!t)return null;let e=an(t,i.projectRoot),n=resolve(i.projectRoot,".claude");if($e(e,n)&&basename(e).toLocaleUpperCase("en-US")==="MEMORY.MD")return Pe;let o=resolve(i.home??homedir(),".claude","projects");return $e(e,o)&&relative(o,e).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?Pe:null}function sn(i){for(let t of ["file_path","notebook_path","path"]){let e=i[t];if(typeof e=="string"&&e.trim())return e.trim()}return null}function an(i,t){return resolve(isAbsolute(i)?i:resolve(t,i))}function $e(i,t){let e=relative(t,i);return e===""||!e.startsWith(`..${sep}`)&&e!==".."&&!isAbsolute(e)}function Be(i){let t=mn(i.toolName,i.toolInput),e=t?hn(i.projectRoot,i.toolName,i.toolInput):void 0;if(!t||!e||!i.toolUseId)return {allowed:true};let n=vn(e),o,r=0,s,c;try{c=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100,readonly:!0});let l=c.getActiveContextReceipt(i.projectRoot,i.sessionId,i.executionId);o=l?.contextHash,r=l?.issuedAt??0,s=l?.canonicalAction?.binding.operationTargets?.find(d=>bn(i.projectRoot,d.path,e));}catch{}finally{try{c?.close();}catch{}}let a={toolUseId:i.toolUseId,sessionId:i.sessionId,executionId:i.executionId,operation:t,path:e,before:n,contextReceipt:o,observedAt:Date.now()};if(En(i.projectRoot,a),t==="edit"||t==="write"||t==="delete"){let l=wn(i.projectRoot,e),d=l?.success&&l.operation==="delete"&&!l.after.exists&&l.completedAt>=r,u=s?.expectedState==="existing"&&!n.exists||s?.expectedState==="missing"&&n.exists||!!(s?.contentHash&&n.hash!==s.contentHash);if(d||s?.expectedState==="existing"&&!n.exists)return qe(i,a,"DEVFLOW_FILE_STATE_DELETED","The target was deleted after the active Context receipt. Refresh project context before editing or recreating it.");if(u)return qe(i,a,"DEVFLOW_FILE_STATE_STALE","The target state no longer matches the active Context receipt. Refresh project context before overwriting it.")}return Ve(i,a,true),{allowed:true,pending:a}}function qe(i,t,e,n){return Ve(i,t,false,e),{allowed:false,reasonCode:e,reason:n,pending:t}}function Ve(i,t,e,n){D({event:"canonical.action.validated",identity:{projectRoot:i.projectRoot,sessionId:i.sessionId,executionId:i.executionId,contextReceipt:t.contextReceipt},level:e?"info":"warn",timestamp:Date.now(),data:{stage:"host_file_state_precondition",valid:e,operation:t.operation,targetPath:relative(i.projectRoot,t.path),targetExists:t.before.exists,targetHash:t.before.hash,reason:n,toolUseId:t.toolUseId}});}function mn(i,t){if(i==="Read")return "read";if(i==="Edit"||i==="NotebookEdit")return "edit";if(i==="Write")return "write";if(i==="Delete"||i==="Bash"&&ze(t.command))return "delete"}function hn(i,t,e){let n=yn(e,["file_path","filePath","notebook_path","path","targetPath"])??(t==="Bash"?ze(e.command):void 0);if(!n)return;let o=isAbsolute(n)?normalize(n):resolve(i,n),r=relative(i,o);return r.startsWith("..")||isAbsolute(r)?void 0:o}function ze(i){return typeof i!="string"?void 0:/(?:^|[;&|]\s*)\s*(?:rm|unlink)\s+(?:-[A-Za-z]+\s+)*(?:--\s+)?(["']?)([^\s;&|"']+)\1/u.exec(i)?.[2]}function yn(i,t){for(let e of t){let n=i[e];if(typeof n=="string"&&n.trim())return n.trim()}}function vn(i){if(!existsSync$1(i))return {exists:false};try{return {exists:!0,hash:createHash$1("sha256").update(readFileSync$1(i)).digest("hex")}}catch{return {exists:true}}}function bn(i,t,e){return (isAbsolute(t)?normalize(t):resolve(i,t))===normalize(e)}function Ge(i){return join(w(i),"file-state")}function Ye(i){return join(Ge(i),"pending.json")}function _n(i){return join(Ge(i),"observations.jsonl")}function Rn(i){try{return JSON.parse(readFileSync$1(Ye(i),"utf8"))}catch{return {}}}function En(i,t){let e=Ye(i);mkdirSync$1(dirname(e),{recursive:true});let n=Rn(i);n[t.toolUseId]=t,Dn(e,JSON.stringify(n));}function wn(i,t){try{let e=readFileSync$1(_n(i),"utf8").trim().split(`
3
+ `);for(let n=e.length-1;n>=0;n-=1){let o=JSON.parse(e[n]);if(o.path===t)return o}}catch{}}function Dn(i,t){let e=`${i}.${process.pid}.${Date.now()}.tmp`;writeFileSync$1(e,t,{encoding:"utf8",mode:384}),renameSync$1(e,i);}var Sn=new Set(["delivered","cancelled","rejected"]),On=new Set(["cancelled","rejected"]),An=new Set(["Write","Edit","NotebookEdit","Bash"]);function Cn(i,t){if(i!=="Bash"||typeof t?.command!="string")return false;let e=t.command.trim(),o="git show [A-Za-z0-9._/:@{}^~+\\-]+(?: 2>/dev/null)?";return new RegExp(`^${o}(?: \\|\\| ${o})*$`,"u").test(e)?true:/[;&|<>`$()]|\\/u.test(e)?false:/^(?:ls|pwd|find|rg|grep|cat|sed|head|tail|wc)(?:\s|$)/u.test(e)||/^git\s+(?:show|status|diff|log|branch)(?:\s|$)/u.test(e)}function oe(i,t,e,n,o){if(e.includes("delivery_rebind_session")||!An.has(e)||!t.trim()||Cn(e,o))return null;let r=join(i,".devflow","delivery-line","state.db");if(!existsSync$1(r))return null;let s;try{s=new DatabaseSync(r,{readOnly:!0,timeout:250});let c=s.prepare("SELECT id, payload, updated_at FROM delivery_cases").all(),a=new Set;if(!!s.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'delivery_workflow_bindings'").get()){let f=s.prepare("SELECT case_id, source_path, aliases FROM delivery_workflow_bindings WHERE status = 'enforced'").all();for(let g of f){let b=[];try{b=JSON.parse(g.aliases);}catch{}(g.source_path===i||b.includes(i))&&a.add(g.case_id);}}let d=[];for(let f of c){let g=JSON.parse(f.payload),b=a.has(f.id);(g.sessionId===t||t===f.id||b)&&d.push({id:f.id,payload:g,updatedAt:typeof f.updated_at=="number"?f.updated_at:typeof g.updatedAt=="number"?g.updatedAt:0});let y=typeof g.stage=="string"?g.stage:"unknown";if(!Sn.has(y)){if(n&&y==="executing"){let m=s.prepare("SELECT id, lease_owner, fencing_token FROM delivery_tasks WHERE case_id = ? AND lease_expires_at > ? AND lease_owner IS NOT NULL AND fencing_token > 0 LIMIT 1").get(f.id,Date.now()),v=typeof g.sessionId=="string"?g.sessionId:void 0,j=typeof g.executionId=="string"?g.executionId:void 0,x=n===m?.id||n===m?.lease_owner||n===j,P=t===f.id||t===v;if(m?.id&&x&&P)return null}if(g.sessionId===t||t===f.id||b)return {code:"DELIVERY_AUTHORITY_REQUIRED",caseId:f.id,stage:y,message:`Delivery case ${f.id} is ${y}; use the Delivery task lease before modifying files.`}}}let u=d.sort((f,g)=>g.updatedAt-f.updatedAt)[0],p=typeof u?.payload.stage=="string"?u.payload.stage:void 0;return u&&p&&On.has(p)?{code:"DELIVERY_AUTHORITY_REQUIRED",caseId:u.id,stage:p,message:`Delivery case ${u.id} is ${p}; start a new Delivery case or session before modifying files.`}:null}catch{return {code:"DELIVERY_AUTHORITY_UNAVAILABLE",caseId:"unknown",stage:"unknown",message:"Delivery state cannot be read; file writes are blocked until runtime health is restored."}}finally{s?.close();}}function F(){return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}function re(i){return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:i}}}function Nn(i){let t=w(i);return existsSync(t)||mkdirSync(t,{recursive:true}),t}function Un(i,t,e,n,o,r){let s=join$1(Nn(i),"event-map.json"),c=[];try{existsSync(s)&&(c=JSON.parse(readFileSync(s,"utf-8")));}catch{}c.push({sessionId:t,toolName:e,toolUseId:n,eventId:o,timestamp:r}),writeFileSync(s,JSON.stringify(c));}function Hn(i){switch(i){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 qn(i,t,e){if(t!=="Read"||typeof e.file_path!="string"||!e.file_path.trim())return null;let n=e.file_path.startsWith("/")?e.file_path:join$1(i,e.file_path);try{if(statSync(n).isDirectory())return `Read accepts files, but "${e.file_path}" is a directory. Use Glob or Bash ls to inspect directory entries, then Read one file.`}catch{return null}return null}function Wn(){let i=process.env.CLAUDE_PLUGIN_ROOT;if(!i)return null;let t=join$1(i,"package.json"),e=join$1(i,".mcp.json");try{let n=JSON.parse(readFileSync(t,"utf8")),r=JSON.parse(readFileSync(e,"utf8")).mcpServers?.devflow,s=r?.args;if(r?.command==="node"&&Array.isArray(s)&&s[0]==="${CLAUDE_PLUGIN_ROOT}/node_modules/@devflow-tools/mcp-server/bin/devflow-mcp.cjs")return existsSync(join$1(i,"node_modules/@devflow-tools/mcp-server/bin/devflow-mcp.cjs"))?null:"bundled DevFlow MCP runtime is not installed";let a=Array.isArray(s)?s.indexOf("--package"):-1,l=a>=0&&typeof s?.[a+1]=="string"?s[a+1]:void 0,d=typeof n.version=="string"?`@devflow-tools/mcp-server@${n.version}`:void 0;return l?d&&l!==d?`DevFlow MCP version mismatch (${l} vs ${d})`:null:"DevFlow MCP package configuration is missing"}catch{return "DevFlow MCP configuration could not be inspected"}}function Jn(){let i=process.env.CLAUDE_PLUGIN_ROOT?.trim();if(!i)return null;try{let t=join$1(i,"dist","runtime-manifest.json"),e=JSON.parse(readFileSync(t,"utf8")),n=typeof e.bundleHashes?.mcp=="string"?e.bundleHashes.mcp:void 0,o=join$1(i,"node_modules","@devflow-tools","mcp-server","dist","delivery-tools.js"),r=existsSync(o)?createHash$1("sha256").update(readFileSync(o)).digest("hex"):"missing";return !n||n!==r?"DevFlow runtime build does not match the active plugin manifest":null}catch{return "DevFlow runtime manifest is missing or invalid"}}function Bn(i,t,e){return new Set(["Write","Edit","NotebookEdit"]).has(i)?true:i==="Bash"?!Ke(i,t):!!(e?.startsWith("delivery_")&&e!=="delivery_status")}function Ke(i,t){return i==="Grep"||i==="Glob"?true:i!=="Bash"||typeof t.command!="string"?false:/^(?:ls|pwd|find|rg|grep|git\s+(?:status|diff|log|branch)|cat|sed|head|tail|wc)\b/u.test(t.command.trim())}async function Vn(i){let t=Fe();try{if(!i||i.trim()==="")return F();let e=JSON.parse(i),n=Date.now();try{maybeRunDiagnosticLogCleanup(T(),{now:n});}catch{}let o=T(),r=new H,s=resolveClaudeToolName(e.tool_name,e.tool_input),c=s.status==="unsupported"?void 0:s.canonicalName;c&&(typeof e.tool_input.projectRoot!="string"||!e.tool_input.projectRoot.trim())&&(e.tool_input.projectRoot=o);let a=e.session_id?.trim();if(!a)return re(Z);let l=new S(o),d=l.get(a)!==null;if(l.registerSession(a),d||await r.sendSessionStart(a,o,Date.now()),e.tool_name==="Skill"){let _=e.tool_input?.skill,h=_?Le(_):null;if(h){let R=l.get(a)?.executionId,E=l.startExecution(a,h,he(h));E.executionId&&E.executionId!==R&&await r.sendExecutionStart(E.executionId,a,h,E.lastActivityAt,o,E.requiredMcpTools);}}let u=l.get(a);c==="get_project_context"&&l.beginContextInitialization(a,e.tool_use_id),c&&(e.tool_input._devflow_session_id=a,e.tool_input._devflow_execution_id=u?.executionId??a,u?.activeTurnId&&(e.tool_input._devflow_turn_id=u.activeTurnId),u?.activeRequestId&&(e.tool_input._devflow_request_id=u.activeRequestId),u?.intentArtifactHash&&(e.tool_input._devflow_intent_artifact_hash=u.intentArtifactHash),u?.skillName&&(e.tool_input._devflow_active_skill=u.skillName),e.tool_use_id&&(e.tool_input._devflow_tool_use_id=e.tool_use_id));let p=e.tool_name.startsWith("mcp__"),f=c,g=l.get(a),b=new B(o,a,g?.executionId),y=b.getPhase(),m,v,j=qn(o,e.tool_name,e.tool_input),x=oe(o,a,e.tool_name,g?.executionId,e.tool_input),P=!x&&Bn(e.tool_name,e.tool_input,f)?Jn():null;if(P)v="DEVFLOW_RUNTIME_VERSION_MISMATCH",m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${P}. Update or restart the DevFlow plugin before approving, executing, or modifying files.`}};else if(j)v="DEVFLOW_DIRECTORY_READ_INVALID",m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:j}};else if(x)v=x.code,m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${x.message} Resolve the case blocker or obtain an authorized task lease before retrying.`}};else {let _=He({toolName:e.tool_name,toolInput:e.tool_input,projectRoot:o}),h=Be({projectRoot:o,sessionId:a,executionId:g?.executionId,toolUseId:e.tool_use_id,toolName:e.tool_name,toolInput:e.tool_input}),R=_?{permissionDecision:"deny",reason:_}:h.allowed?b.evaluate(e.tool_name,p):{permissionDecision:"deny",reason:h.reason,reasonCode:h.reasonCode},E=R.permissionDecision==="deny"&&!p&&Ke(e.tool_name,e.tool_input)?Wn():null;E?(m=re(`DevFlow MCP is unavailable or stale: ${E}. This read-only fallback is temporary; refresh the plugin installation and call ${projectClaudeToolName("get_project_context")} before editing.`),v=void 0):R.permissionDecision==="deny"?(v=_?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":R.reasonCode??"DEVFLOW_CONTEXT_REQUIRED",m={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:R.reason??"MCP context required"}}):R.additionalContext?m=re(R.additionalContext):m=F();}c&&(m.hookSpecificOutput.updatedInput=e.tool_input),t&&m.hookSpecificOutput.permissionDecision==="allow"&&(m.hookSpecificOutput.additionalContext=Z);let Xe=g?.executionId??a,C={eventId:je(a,e.tool_use_id),executionId:Xe,sessionId:a,projectRoot:o,toolUseId:e.tool_use_id,timestamp:Date.now(),toolName:e.tool_name,toolType:p?"mcp":e.tool_name==="Agent"?"subagent":"direct",isMcpTool:p,mcpToolName:f,mcpEnforced:p&&(y==="context_gathering"||y==="context_initializing"),mcpFallback:!p&&(y==="context_gathering"||y==="context_initializing"),kind:Hn(e.tool_name),input:e.tool_input,duration:0,blocked:m.hookSpecificOutput.permissionDecision==="deny",blockReason:m.hookSpecificOutput.permissionDecision==="deny"?v??"DEVFLOW_CONTEXT_REQUIRED":void 0},$=await r.sendEvent(C);$&&!C.blocked&&Un(o,a,e.tool_name,e.tool_use_id,$,C.timestamp),$&&C.blocked&&await r.completeEvent({eventId:$,sessionId:a,error:v??"DEVFLOW_CONTEXT_REQUIRED",duration:Date.now()-C.timestamp,completedAt:Date.now()});try{let _=Ae(o),h={ts:n,tool:e.tool_name,sessionId:a,skill:u?.skillName??"(none)",requiredTools:u?.requiredMcpTools??[],isMcp:p,enforce:u?.executionId!==void 0,stateless:u?.executionId===void 0&&!p&&e.tool_name!=="Skill",bypassCount:_.bypassCount??0,decision:m.hookSpecificOutput.permissionDecision,env_CLAUDE_PLUGIN_ROOT:process.env.CLAUDE_PLUGIN_ROOT??"(unset)",cwd:process.cwd()};Te(Ce(o),`${JSON.stringify(h)}
4
4
  `);}catch{}return m}catch{try{let e=JSON.parse(i),n=T(),o=oe(n,String(e.session_id??""),String(e.tool_name??""),void 0,e.tool_input);if(o)return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:o.message}}}catch{}return F()}}if(process.argv[1]?.endsWith("pre-tool-use")||process.argv[1]?.endsWith("pre-tool-use.js")){let i=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{t+=e;}),process.stdin.on("end",async()=>{let e=await Vn(t);i(JSON.stringify(e));}),process.stdin.on("error",()=>{i(JSON.stringify(F())),process.exit(0);}),setTimeout(()=>{i(JSON.stringify(F())),process.exit(0);},4e3).unref();}export{Vn as handlePreToolUse};
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "manifestVersion": "devflow-runtime.v1",
3
- "packageVersion": "0.18.70",
4
- "sourceCommit": "d1a22d1198ea6319c56863ac60401d8906788faf",
3
+ "packageVersion": "0.18.72",
4
+ "sourceCommit": "80b9c86844a51e78437d1af52986aa0a5ae54142",
5
5
  "bundleHashes": {
6
- "hooks": "ffe59e9d1472cd9d3b16fe75be86bbba71af2ea70d8940b4269f52ba11e5b40f",
6
+ "hooks": "e485758b1e17bc6054b00ce5f4a67118222b601601dbc246f26236744e6c3d3f",
7
7
  "mcp": "ae638ba33e7807efad1554deadd8517002e7e6a263a4f4745ff7cb2081671997",
8
8
  "cli": "abcdd6c9bba7abbc43f7584bfa24fd42af5ac303a901c4440a289bd62970e38e"
9
9
  },
10
- "registryHash": "492a3acf18cbb2f01a28861141842ca4c97f67a4fcdffd7c32b8701fe9a8fc85",
10
+ "registryHash": "f130880d3ef519d039b7f045efc09d6d1a8133dd5d4ffcefe30df0f2d65d1b66",
11
11
  "stateDbPath": "<projectRoot>/.devflow/delivery-line/state.db",
12
- "builtAt": 1792225183331,
13
- "manifestHash": "87d6f408c481d69a2440700b407e425f671537bd472e13988a3ebcaaa32661b7"
12
+ "builtAt": 1792229940396,
13
+ "manifestHash": "19586f4e623e3d8487d4f099eacf4ca213be8ea4da86b19dfa3f74125b2b28c9"
14
14
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devflow-tools/claude-code-plugin",
3
- "version": "0.18.70",
3
+ "version": "0.18.72",
4
4
  "description": "Claude Code hooks and skills for the DevFlow development intelligence runtime.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -12,17 +12,17 @@
12
12
  "verify:runtime-dependencies": "node --import tsx scripts/verify-runtime-dependencies.ts"
13
13
  },
14
14
  "dependencies": {
15
- "@devflow-tools/benchmark": "0.18.70",
16
- "@devflow-tools/context-engine": "0.18.70",
17
- "@devflow-tools/database": "0.18.70",
18
- "@devflow-tools/mcp-server": "0.18.70",
19
- "@devflow-tools/memory-engine": "0.18.70",
20
- "@devflow-tools/sdk": "0.18.70",
21
- "@devflow-tools/semantic-engine": "0.18.70",
22
- "@devflow-tools/server": "0.18.70",
23
- "@devflow-tools/task-runtime": "0.18.70",
24
- "@devflow-tools/telemetry": "0.18.70",
25
- "@devflow-tools/workflow-engine": "0.18.70"
15
+ "@devflow-tools/benchmark": "0.18.72",
16
+ "@devflow-tools/context-engine": "0.18.72",
17
+ "@devflow-tools/database": "0.18.72",
18
+ "@devflow-tools/mcp-server": "0.18.72",
19
+ "@devflow-tools/memory-engine": "0.18.72",
20
+ "@devflow-tools/sdk": "0.18.72",
21
+ "@devflow-tools/semantic-engine": "0.18.72",
22
+ "@devflow-tools/server": "0.18.72",
23
+ "@devflow-tools/task-runtime": "0.18.72",
24
+ "@devflow-tools/telemetry": "0.18.72",
25
+ "@devflow-tools/workflow-engine": "0.18.72"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@devflow-tools/devflow": "0.18.65"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devflow-tools/devflow",
3
- "version": "0.18.70",
3
+ "version": "0.18.72",
4
4
  "type": "module",
5
5
  "description": "Installable DevFlow distribution containing the CLI, runtime hooks, and Claude plugin.",
6
6
  "bin": {
@@ -21,21 +21,21 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@colbymchenry/codegraph": "^1.1.1",
24
- "@devflow-tools/adapters": "0.18.70",
25
- "@devflow-tools/benchmark": "0.18.70",
26
- "@devflow-tools/context-engine": "0.18.70",
27
- "@devflow-tools/database": "0.18.70",
28
- "@devflow-tools/delivery-line": "0.18.70",
29
- "@devflow-tools/knowledge-engine": "0.18.70",
30
- "@devflow-tools/mcp-server": "0.18.70",
31
- "@devflow-tools/memory-engine": "0.18.70",
32
- "@devflow-tools/retrieval-engine": "0.18.70",
33
- "@devflow-tools/sdk": "0.18.70",
34
- "@devflow-tools/semantic-engine": "0.18.70",
35
- "@devflow-tools/server": "0.18.70",
36
- "@devflow-tools/task-runtime": "0.18.70",
37
- "@devflow-tools/telemetry": "0.18.70",
38
- "@devflow-tools/workflow-engine": "0.18.70",
24
+ "@devflow-tools/adapters": "0.18.72",
25
+ "@devflow-tools/benchmark": "0.18.72",
26
+ "@devflow-tools/context-engine": "0.18.72",
27
+ "@devflow-tools/database": "0.18.72",
28
+ "@devflow-tools/delivery-line": "0.18.72",
29
+ "@devflow-tools/knowledge-engine": "0.18.72",
30
+ "@devflow-tools/mcp-server": "0.18.72",
31
+ "@devflow-tools/memory-engine": "0.18.72",
32
+ "@devflow-tools/retrieval-engine": "0.18.72",
33
+ "@devflow-tools/sdk": "0.18.72",
34
+ "@devflow-tools/semantic-engine": "0.18.72",
35
+ "@devflow-tools/server": "0.18.72",
36
+ "@devflow-tools/task-runtime": "0.18.72",
37
+ "@devflow-tools/telemetry": "0.18.72",
38
+ "@devflow-tools/workflow-engine": "0.18.72",
39
39
  "@inquirer/prompts": "^7.10.1",
40
40
  "@modelcontextprotocol/sdk": "^1.32.1",
41
41
  "@nestjs/common": "^12.1.2",
@@ -1,118 +1,118 @@
1
1
  {
2
2
  "version": "1.0.0",
3
- "lastUpdated": "2026-10-17T08:11:05.190Z",
3
+ "lastUpdated": "2026-10-17T09:33:13.711Z",
4
4
  "plugins": [
5
5
  {
6
6
  "name": "@devflow-tools/plugin-animation",
7
- "version": "0.18.70",
7
+ "version": "0.18.72",
8
8
  "description": "Animation analysis and generation tools for DevFlow.",
9
9
  "tags": [],
10
10
  "compatibleStacks": [
11
11
  "animation"
12
12
  ],
13
- "size": "88612 B",
13
+ "size": "88964 B",
14
14
  "author": "DevFlow Team",
15
15
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
16
16
  },
17
17
  {
18
18
  "name": "@devflow-tools/plugin-css",
19
- "version": "0.18.70",
19
+ "version": "0.18.72",
20
20
  "description": "CSS analysis and selector audit tools for DevFlow.",
21
21
  "tags": [],
22
22
  "compatibleStacks": [
23
23
  "css"
24
24
  ],
25
- "size": "75511 B",
25
+ "size": "75851 B",
26
26
  "author": "DevFlow Team",
27
27
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
28
28
  },
29
29
  {
30
30
  "name": "@devflow-tools/plugin-docker",
31
- "version": "0.18.70",
31
+ "version": "0.18.72",
32
32
  "description": "Docker configuration and diagnostic tools for DevFlow.",
33
33
  "tags": [],
34
34
  "compatibleStacks": [
35
35
  "docker"
36
36
  ],
37
- "size": "104377 B",
37
+ "size": "104723 B",
38
38
  "author": "DevFlow Team",
39
39
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
40
40
  },
41
41
  {
42
42
  "name": "@devflow-tools/plugin-electron",
43
- "version": "0.18.70",
43
+ "version": "0.18.72",
44
44
  "description": "Electron application analysis and implementation tools for DevFlow.",
45
45
  "tags": [],
46
46
  "compatibleStacks": [
47
47
  "electron"
48
48
  ],
49
- "size": "120275 B",
49
+ "size": "120625 B",
50
50
  "author": "DevFlow Team",
51
51
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
52
52
  },
53
53
  {
54
54
  "name": "@devflow-tools/plugin-git",
55
- "version": "0.18.70",
55
+ "version": "0.18.72",
56
56
  "description": "Git repository analysis and workflow tools for DevFlow.",
57
57
  "tags": [],
58
58
  "compatibleStacks": [
59
59
  "git"
60
60
  ],
61
- "size": "85832 B",
61
+ "size": "86172 B",
62
62
  "author": "DevFlow Team",
63
63
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
64
64
  },
65
65
  {
66
66
  "name": "@devflow-tools/plugin-graphql",
67
- "version": "0.18.70",
67
+ "version": "0.18.72",
68
68
  "description": "GraphQL schema and operation tools for DevFlow.",
69
69
  "tags": [],
70
70
  "compatibleStacks": [
71
71
  "graphql"
72
72
  ],
73
- "size": "88167 B",
73
+ "size": "88515 B",
74
74
  "author": "DevFlow Team",
75
75
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
76
76
  },
77
77
  {
78
78
  "name": "@devflow-tools/plugin-nest",
79
- "version": "0.18.70",
79
+ "version": "0.18.72",
80
80
  "description": "NestJS analysis and implementation tools for DevFlow.",
81
81
  "tags": [],
82
82
  "compatibleStacks": [
83
83
  "nest"
84
84
  ],
85
- "size": "124720 B",
85
+ "size": "125062 B",
86
86
  "author": "DevFlow Team",
87
87
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
88
88
  },
89
89
  {
90
90
  "name": "@devflow-tools/plugin-nextjs",
91
- "version": "0.18.70",
91
+ "version": "0.18.72",
92
92
  "description": "Next.js analysis and implementation tools for DevFlow.",
93
93
  "tags": [],
94
94
  "compatibleStacks": [
95
95
  "nextjs"
96
96
  ],
97
- "size": "86476 B",
97
+ "size": "86822 B",
98
98
  "author": "DevFlow Team",
99
99
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
100
100
  },
101
101
  {
102
102
  "name": "@devflow-tools/plugin-performance",
103
- "version": "0.18.70",
103
+ "version": "0.18.72",
104
104
  "description": "Web performance audit and optimization tools for DevFlow.",
105
105
  "tags": [],
106
106
  "compatibleStacks": [
107
107
  "performance"
108
108
  ],
109
- "size": "137062 B",
109
+ "size": "137418 B",
110
110
  "author": "DevFlow Team",
111
111
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
112
112
  },
113
113
  {
114
114
  "name": "@devflow-tools/plugin-react",
115
- "version": "0.18.70",
115
+ "version": "0.18.72",
116
116
  "description": "React analysis, audit, and component tools for DevFlow.",
117
117
  "tags": [],
118
118
  "compatibleStacks": [
@@ -124,55 +124,55 @@
124
124
  "path": "scripts/run-capability.mjs",
125
125
  "timeoutMs": 30000
126
126
  },
127
- "size": "283329 B",
127
+ "size": "283673 B",
128
128
  "author": "DevFlow Team",
129
129
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
130
130
  },
131
131
  {
132
132
  "name": "@devflow-tools/plugin-tailwind",
133
- "version": "0.18.70",
133
+ "version": "0.18.72",
134
134
  "description": "Tailwind CSS analysis and component tools for DevFlow.",
135
135
  "tags": [],
136
136
  "compatibleStacks": [
137
137
  "tailwind"
138
138
  ],
139
- "size": "92963 B",
139
+ "size": "93313 B",
140
140
  "author": "DevFlow Team",
141
141
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
142
142
  },
143
143
  {
144
144
  "name": "@devflow-tools/plugin-taro",
145
- "version": "0.18.70",
145
+ "version": "0.18.72",
146
146
  "description": "Taro application analysis and implementation tools for DevFlow.",
147
147
  "tags": [],
148
148
  "compatibleStacks": [
149
149
  "taro"
150
150
  ],
151
- "size": "96405 B",
151
+ "size": "96747 B",
152
152
  "author": "DevFlow Team",
153
153
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
154
154
  },
155
155
  {
156
156
  "name": "@devflow-tools/plugin-ui-layout",
157
- "version": "0.18.70",
157
+ "version": "0.18.72",
158
158
  "description": "UI layout analysis and implementation tools for DevFlow.",
159
159
  "tags": [],
160
160
  "compatibleStacks": [
161
161
  "ui-layout"
162
162
  ],
163
- "size": "73990 B",
163
+ "size": "74342 B",
164
164
  "author": "DevFlow Team",
165
165
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
166
166
  },
167
167
  {
168
168
  "name": "@devflow-tools/plugin-vue",
169
- "version": "0.18.70",
169
+ "version": "0.18.72",
170
170
  "description": "Vue analysis, audit, and component tools for DevFlow.",
171
171
  "tags": [],
172
172
  "compatibleStacks": [
173
173
  "vue"
174
174
  ],
175
- "size": "104483 B",
175
+ "size": "104823 B",
176
176
  "author": "DevFlow Team",
177
177
  "homepage": "https://github.com/shilongfeicool/dev-flow#readme"
178
178
  }