@devflow-tools/cli 0.16.12 → 0.16.13

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