@vpxa/aikit 0.1.372 → 0.1.373

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.
@@ -552,9 +552,21 @@ interface GlobalRegistry {
552
552
  */
553
553
  declare function getWorkspacePartitionDir(cwd: string): string;
554
554
  declare function migrateLegacyWorkspaceLayout(workspaceRoot: string): void;
555
+ /**
556
+ * Pure path calculation for the state directory — no side effects, no I/O.
557
+ * Always routes to ~/.aikit/workspaces/<partition>/state/.
558
+ *
559
+ * Use this instead of `resolveStateDir` when you only need the path
560
+ * without triggering migration or workspace registration.
561
+ */
562
+ declare function computeStateDir(cwd: string): string;
555
563
  /**
556
564
  * Resolve the state directory for a workspace root.
557
565
  * Always routes to ~/.aikit/workspaces/<partition>/state/.
566
+ *
567
+ * NOTE: This has side effects — it triggers legacy migration and
568
+ * workspace registration (which creates the partition directory).
569
+ * If you only need the path without I/O, use `computeStateDir()` instead.
558
570
  */
559
571
  declare function resolveStateDir(cwd: string): string;
560
572
  /**
@@ -1034,6 +1046,36 @@ declare function safeCwd(): string | null;
1034
1046
  /** Returns `process.cwd()` falling back to `os.homedir()` when unavailable. */
1035
1047
  declare function safeCwdOrHome(): string;
1036
1048
  //#endregion
1049
+ //#region packages/core/src/test-utils.d.ts
1050
+ /**
1051
+ * Test isolation utilities for AI Kit.
1052
+ *
1053
+ * Use `isolateGlobalDataDir()` in beforeEach/afterEach to prevent test
1054
+ * partition helpers from writing into the real ~/.aikit/workspaces/,
1055
+ * which causes orphaned partition directories.
1056
+ *
1057
+ * Usage in vitest:
1058
+ * import { isolateGlobalDataDir } from '@aikit/core';
1059
+ * let restore: () => void;
1060
+ * beforeEach(() => { restore = isolateGlobalDataDir(); });
1061
+ * afterEach(() => restore());
1062
+ */
1063
+ /**
1064
+ * Override AIKIT_GLOBAL_DATA_DIR to a fresh temp directory.
1065
+ *
1066
+ * Call before any partition-helper runs (resolveStateDir,
1067
+ * getPartitionDir, registerWorkspace, computePartitionKey → getPartitionDir).
1068
+ *
1069
+ * Returns the temp directory path. The paired `restoreGlobalDataDir()`
1070
+ * cleanup removes the temp dir and restores the previous env value.
1071
+ */
1072
+ declare function isolateGlobalDataDir(): string;
1073
+ /**
1074
+ * Restore the previous AIKIT_GLOBAL_DATA_DIR and remove the temp dir.
1075
+ * Safe to call even if isolateGlobalDataDir was never called.
1076
+ */
1077
+ declare function restoreGlobalDataDir(): void;
1078
+ //#endregion
1037
1079
  //#region packages/core/src/version-manager.d.ts
1038
1080
  /**
1039
1081
  * Shared version directory management for managed AI Kit installations.
@@ -1061,4 +1103,4 @@ declare function compareVersionDir(a: string, b: string): number;
1061
1103
  */
1062
1104
  declare function cleanupOldVersions(versionsDir: string, keepVersion?: string): void;
1063
1105
  //#endregion
1064
- export { AIKIT_GLOBAL_PATHS, AIKIT_PATHS, AIKIT_RUNTIME_PATHS, AikitConfig, AikitError, BriefingCardMetadataV1, BriefingCardType, CATEGORY_PATTERN, CHUNK_SIZES, CONTENT_TYPES, ChunkMetadata, CircuitBreaker, CircuitBreakerOptions, CircuitOpenError, CircuitState, ConfigError, ContentType, CuratedKnowledgeMetadataV1, DEFAULT_CATEGORIES, DEFAULT_SERVER_NAME, EMBEDDING_DEFAULTS, EmbeddingError, EvidenceGrade, EvidenceMetadataV1, FILE_LIMITS, FlowBacktrackV1, FlowContextMetadataV1, FlowContextProfileName, FlowContextSnapshotV1, FlowContextUpdateV1, FlowLifecycleAuditRecordV1, FlowLifecycleMutationV1, FlowOwnerClaimV1, FlowStepKnowledgeContractV1, GlobalRegistry, HealthBus, HealthEvent, HealthStatus, INDEX_MODES, INSTALL_ARGS, IndexError, IndexMode, IndexStats, InstructionTreatment, KNOWLEDGE_ORIGINS, KnowledgeLayerId, KnowledgeOrigin, KnowledgeRecord, LAYER_FIELD_REQUIREMENTS, LayerValidationResult, LayeredKnowledgeBaseV1, LayeredKnowledgeContractV1, LogLevel, LogListener, MODEL_REGISTRY, PermanentError, RawChunk, RegistryEntry, RetryOptions, SEARCH_DEFAULTS, SOURCE_TYPES, STORE_DEFAULTS, SearchResult, SourceType, StoreError, SubsystemHealth, SupersessionConfig, TOKEN_BUDGETS, TokenBudget, TransientError, addLogListener, cleanupOldVersions, compareVersionDir, computePartitionKey, contentTypeToSourceType, createLogger, detectContentType, getGlobalDataDir, getLogLevel, getPartitionDir, getWorkspacePartitionDir, hashPath, isPermanent, isTransient, isUserInstalled, listWorkspaces, loadRegistry, lookupWorkspace, migrateLegacyWorkspaceLayout, normalizePathForHash, registerWorkspace, resetLogDir, resolveLogDir, resolveStateDir, safeCwd, safeCwdOrHome, saveRegistry, serializeError, setDetailedErrorLoggingEnabled, setFileSinkEnabled, setLogLevel, sourceTypeContentTypes, validateLayerMetadata, withRetry };
1106
+ export { AIKIT_GLOBAL_PATHS, AIKIT_PATHS, AIKIT_RUNTIME_PATHS, AikitConfig, AikitError, BriefingCardMetadataV1, BriefingCardType, CATEGORY_PATTERN, CHUNK_SIZES, CONTENT_TYPES, ChunkMetadata, CircuitBreaker, CircuitBreakerOptions, CircuitOpenError, CircuitState, ConfigError, ContentType, CuratedKnowledgeMetadataV1, DEFAULT_CATEGORIES, DEFAULT_SERVER_NAME, EMBEDDING_DEFAULTS, EmbeddingError, EvidenceGrade, EvidenceMetadataV1, FILE_LIMITS, FlowBacktrackV1, FlowContextMetadataV1, FlowContextProfileName, FlowContextSnapshotV1, FlowContextUpdateV1, FlowLifecycleAuditRecordV1, FlowLifecycleMutationV1, FlowOwnerClaimV1, FlowStepKnowledgeContractV1, GlobalRegistry, HealthBus, HealthEvent, HealthStatus, INDEX_MODES, INSTALL_ARGS, IndexError, IndexMode, IndexStats, InstructionTreatment, KNOWLEDGE_ORIGINS, KnowledgeLayerId, KnowledgeOrigin, KnowledgeRecord, LAYER_FIELD_REQUIREMENTS, LayerValidationResult, LayeredKnowledgeBaseV1, LayeredKnowledgeContractV1, LogLevel, LogListener, MODEL_REGISTRY, PermanentError, RawChunk, RegistryEntry, RetryOptions, SEARCH_DEFAULTS, SOURCE_TYPES, STORE_DEFAULTS, SearchResult, SourceType, StoreError, SubsystemHealth, SupersessionConfig, TOKEN_BUDGETS, TokenBudget, TransientError, addLogListener, cleanupOldVersions, compareVersionDir, computePartitionKey, computeStateDir, contentTypeToSourceType, createLogger, detectContentType, getGlobalDataDir, getLogLevel, getPartitionDir, getWorkspacePartitionDir, hashPath, isPermanent, isTransient, isUserInstalled, isolateGlobalDataDir, listWorkspaces, loadRegistry, lookupWorkspace, migrateLegacyWorkspaceLayout, normalizePathForHash, registerWorkspace, resetLogDir, resolveLogDir, resolveStateDir, restoreGlobalDataDir, safeCwd, safeCwdOrHome, saveRegistry, serializeError, setDetailedErrorLoggingEnabled, setFileSinkEnabled, setLogLevel, sourceTypeContentTypes, validateLayerMetadata, withRetry };
@@ -1 +1 @@
1
- import{EventEmitter as e}from"node:events";import{basename as t,dirname as n,extname as r,join as i,resolve as a,sep as o}from"node:path";import{createHash as s}from"node:crypto";import{appendFileSync as c,closeSync as l,constants as u,copyFileSync as ee,existsSync as d,lstatSync as te,mkdirSync as f,openSync as ne,readFileSync as re,readdirSync as p,renameSync as m,rmSync as h,statSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{homedir as y}from"node:os";import{fileURLToPath as ie}from"node:url";var ae=class t extends e{static registry=new Map;state=`closed`;failures=0;halfOpenAttempts=0;openUntil=0;threshold;cooldownMs;halfOpenMaxAttempts;jitterMs;name;onStateChange;static getAll(){return t.registry}static get(e){return t.registry.get(e)}static clearRegistry(){t.registry.clear()}constructor(e={}){super(),this.threshold=Math.max(1,e.threshold??3),this.cooldownMs=Math.max(0,e.cooldownMs??6e4),this.halfOpenMaxAttempts=Math.max(1,e.halfOpenMaxAttempts??1),this.jitterMs=Math.max(0,e.jitterMs??0),this.name=e.name,this.onStateChange=e.onStateChange,this.name&&t.registry.set(this.name,this)}async execute(e){this.assertNotOpen();try{let t=await e();return this.recordSuccess(),t}catch(e){throw this.recordFailure(),e}}getState(){return this.refreshState(),this.state}getName(){return this.name}isOpen(){return this.getState()===`open`}reset(){this.failures=0,this.halfOpenAttempts=0,this.openUntil=0,this.transitionTo(`closed`,`manual reset`)}dispose(){this.name&&t.registry.get(this.name)===this&&t.registry.delete(this.name),this.removeAllListeners()}setCooldown(e){this.cooldownMs=Math.max(0,e)}getCooldown(){return this.cooldownMs}forceOpen(e){this.failures=this.threshold,this.halfOpenAttempts=0,this.transitionTo(`open`,e??`manual override`)}recordSuccess(){this.refreshState(),this.failures=0,this.halfOpenAttempts=0,this.state===`half-open`&&this.transitionTo(`closed`,`probe succeeded`)}recordFailure(){if(this.refreshState(),this.failures+=1,this.halfOpenAttempts=0,this.state===`half-open`){this.transitionTo(`open`,`probe failed`);return}this.state===`closed`&&this.failures>=this.threshold&&this.transitionTo(`open`,`failure threshold reached`)}remainingCooldownMs(){return this.refreshState(),this.state===`open`?Math.max(0,this.openUntil-Date.now()):0}assertNotOpen(){if(this.refreshState(),this.state===`open`)throw new b(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new b(this.remainingCooldownMs());this.halfOpenAttempts+=1}}refreshState(){this.state===`open`&&Date.now()>=this.openUntil&&(this.halfOpenAttempts=0,this.transitionTo(`half-open`,`cooldown expired`))}transitionTo(e,t){let n=this.state;if(n===e){e===`open`&&(this.openUntil=this.computeOpenUntil());return}this.state=e,e===`open`?(this.openUntil=this.computeOpenUntil(),this.halfOpenAttempts=0):(this.openUntil=0,e===`closed`&&(this.halfOpenAttempts=0)),this.onStateChange?.(n,e),this.emit(e,{from:n,reason:t})}computeOpenUntil(){return Date.now()+this.cooldownMs+Math.floor(Math.random()*this.jitterMs)}},b=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const x={root:`.aikit`,ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit/data`,state:`.aikit/state`,logs:`.aikit/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},S={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`,l0Cards:`memories`},C={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},oe={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},se={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},ce={"mixedbread-ai/mxbai-embed-xsmall-v1":{nativeDim:384,dimensions:384,queryPrefix:``,pooling:`mean`},"mixedbread-ai/mxbai-embed-large-v1":{nativeDim:1024,dimensions:512,queryPrefix:`Represent this sentence for searching relevant passages: `,pooling:`cls`}},le={backend:`sqlite-vec`,path:x.data,tableName:`knowledge`},ue=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],de={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},fe={maxResults:10,minScore:.25},pe=/^[a-z][a-z0-9-]*$/,me=`AI Kit`,he=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],w={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},ge=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],_e=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function ve(e){let n=r(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${x.aiContext}/`)?`produced-knowledge`:e.includes(`${x.aiCurated}/`)?`curated-knowledge`:ge.some(t=>t.test(e))?`test-code`:_e.some(t=>t.test(e))?`cdk-stack`:n in w?w[n]:i.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(n)?`code-other`:`unknown`}const T={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function ye(e){return T[e]??`source`}function be(e){return Object.entries(T).filter(([,t])=>t===e).map(([e])=>e)}var E=class extends Error{code;constructor(e,t,n){super(e,n===void 0?void 0:{cause:n}),this.code=t,this.name=`AikitError`}},xe=class extends E{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},Se=class extends E{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},Ce=class extends E{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},we=class extends E{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},D=class extends E{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},O=class extends E{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function Te(e){return e instanceof D}function Ee(e){return e instanceof O}let k=!1;function De(e){try{return!te(e).isSymbolicLink()}catch{return!1}}function Oe(e,t){if(g(e).isDirectory()){f(t,{recursive:!0});for(let n of p(e))A(a(e,n),a(t,n));h(e,{recursive:!0,force:!0});return}f(a(t,`..`),{recursive:!0}),ee(e,t),_(e)}function ke(e,t){try{m(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!d(e)&&d(t))return;if(r!==`EXDEV`)throw n;Oe(e,t)}}function A(e,t){if(!d(e)||e===t||!De(e))return;let n=g(e);if(!d(t)){f(a(t,`..`),{recursive:!0}),ke(e,t);return}if(!n.isDirectory())return;f(t,{recursive:!0});let r;try{r=p(e)}catch{return}for(let n of r)A(a(e,n),a(t,n));try{h(e,{recursive:!0,force:!0})}catch{}}function j(e){if(d(e))try{p(e).length===0&&h(e,{recursive:!0,force:!0})}catch{}}function Ae(e){let t=a(e,S.data);f(t,{recursive:!0});for(let n of p(e))n!==S.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&A(a(e,n),a(t,n))}function M(e){return B(I(e))}function je(e){if(k)return;k=!0,f(e,{recursive:!0});let t=y(),n=a(t,C.legacyDataRoot),r=a(t,C.legacyStateRoot),i=a(e,C.workspaces),o=a(e,C.logs),s=a(e,C.state);if(d(n)&&n!==e){f(i,{recursive:!0});for(let t of p(n))A(a(n,t),t===C.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?a(e,t):a(i,t));j(n)}if(d(r)&&r!==e){for(let e of p(r))A(a(r,e),e===`logs`?o:a(s,e));j(r)}}function N(e){let t=a(e),n=M(t),r=a(n,S.data),i=a(P(),C.logs),o=[{from:a(t,C.legacyDataRoot),to:r},{from:a(t,C.legacyStateRoot),to:a(n,S.state)},{from:a(t,x.data),to:r},{from:a(t,x.state),to:a(n,S.state)},{from:a(t,x.aiCurated),to:a(n,S.curated)},{from:a(t,x.aiContext),to:a(n,S.onboard)},{from:a(t,x.restorePoints),to:a(n,S.restorePoints)},{from:a(t,x.brainstorm),to:a(n,S.brainstorm)},{from:a(t,x.handoffs),to:a(n,S.handoffs)},{from:a(t,x.logs),to:i}];f(n,{recursive:!0}),f(i,{recursive:!0}),Ae(n);for(let e of o)A(e.from,e.to);j(a(t,x.root)),j(a(t,x.ai)),j(a(t,x.brainstorm)),j(a(t,x.handoffs))}function Me(e){return N(e),a(B(z(e).partition),S.state)}function P(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??a(y(),C.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&je(t),t}function F(e){return Pe()?e.toLowerCase():e}function I(e){let n=a(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${s(`sha256`).update(F(n)).digest(`hex`).slice(0,8)}`}function Ne(e,t=12){let n=a(e);return s(`sha256`).update(F(n)).digest(`hex`).slice(0,t)}function Pe(){return process.platform===`win32`||process.platform===`darwin`}function L(){let e=a(P(),C.registry);if(!d(e))return{version:1,workspaces:{}};let t=re(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Fe(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=ne(n,u.O_CREAT|u.O_EXCL|u.O_WRONLY);return v(e,`${process.pid}\n`),l(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=g(n);if(Date.now()-e>3e4){_(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function Ie(e){try{_(e)}catch{}}function R(e){let t=P();f(t,{recursive:!0});let n=a(t,C.registry),r=Fe(n);try{let t=`${n}.tmp`;v(t,JSON.stringify(e,null,2),`utf-8`),m(t,n)}finally{Ie(r)}}function z(e){let t=L(),n=I(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:a(e),registeredAt:r,lastAccessedAt:r},f(B(n),{recursive:!0}),R(t),t.workspaces[n]}function Le(e){let t=L(),n=I(e);return t.workspaces[n]}function Re(){let e=L();return Object.values(e.workspaces)}function B(e){return a(P(),C.workspaces,e)}function ze(){return d(a(P(),C.registry))}function V(){return a(P(),C.logs)}var Be=class t extends e{static _instance=null;subsystems=new Map;constructor(){super()}static instance(){return t._instance||=new t,t._instance}static reset(){t._instance?.removeAllListeners(),t._instance=null}register(e){this.subsystems.has(e)||this.subsystems.set(e,{name:e,status:`healthy`,since:Date.now()})}reportDegraded(e,t){this.transition(e,`degraded`,t)}reportUnavailable(e,t){this.transition(e,`unavailable`,t)}reportRecovered(e){this.transition(e,`healthy`)}isDegraded(e){let t=this.subsystems.get(e);return t?.status===`degraded`||t?.status===`unavailable`}isHealthy(e){return this.subsystems.get(e)?.status===`healthy`}getAll(){return Array.from(this.subsystems.values(),e=>({...e}))}getSubsystem(e){let t=this.subsystems.get(e);return t?{...t}:void 0}transition(e,t,n){let r=this.subsystems.get(e);if(!r||r.status===t)return;let i={subsystem:e,status:t,previousStatus:r.status,reason:n,timestamp:Date.now()};r.status=t,r.since=i.timestamp,r.reason=n,this.emit(t,i),this.emit(`change`,i)}};function Ve(e,t){let n=H[e];if(!n)return{valid:!1,missingRequired:[`Unknown layer: ${e}`],extraFields:[]};let r=[];for(let e of n.required)(t[e]===void 0||t[e]===null)&&r.push(e);let i=new Set([...n.required,...n.optional]),a=[];for(let e of Object.keys(t))e!==`layer`&&(i.has(e)||a.push(e));return{valid:r.length===0&&a.length===0,missingRequired:r,extraFields:a}}const H={l0:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`cardType`,`tokenBudget`,`selectionReason`],optional:[`topicKey`,`tags`,`taskId`,`flowSlug`,`freshness`,`referenceRefs`,`quality`,`decision`]},l1:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`flowSlug`,`runId`,`stepId`,`stepIndex`,`objective`,`acceptanceCriteria`],optional:[`scope`,`exclusions`,`retrievedRefs`,`verifiedClaims`,`assumedClaims`,`unresolvedClaims`,`decisions`,`rationale`,`artifacts`,`stepSummaries`,`failures`,`successPatterns`,`candidateLearnings`,`verifiedFinalOutcome`,`decision`]},l2:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`topicKey`,`curatedMarkdownPath`,`managedBy`,`promotionState`],optional:[`tags`,`evidenceRefs`,`freshness`,`supersededBy`,`confidence`,`quality`,`rationale`,`decision`]},l3:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`evidenceRefs`,`quality`],optional:[`flowSlug`,`runId`,`stepId`,`recurrence`,`impact`,`sourceDiversity`,`topicKey`,`tags`,`ttlMs`,`decision`]}},U={debug:0,info:1,warn:2,error:3},W=[];let G=process.env.AIKIT_LOG_LEVEL??`info`,K=!1,q=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function He(){return q?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let J;function Y(){return J||=V(),J}function Ue(e){let t=e.toISOString().slice(0,10);return i(Y(),`${t}.jsonl`)}let X=0;function We(){let e=Date.now();if(!(e-X<36e5)){X=e;try{let t=Y(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of p(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{_(i(t,e))}catch{}}catch{}}}function Ge(e,t){try{f(Y(),{recursive:!0}),c(Ue(t),`${e}\n`),We()}catch{}}function Ke(e){G=e}function qe(){return G}function Je(e){q=e}function Ye(){J=void 0}function Xe(e){K=e}function Ze(e){if(e instanceof Error){let t={error:e.message};return K?(e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t):t}return{error:String(e)}}function Qe(e){return W.push(e),()=>{let t=W.indexOf(e);t>=0&&W.splice(t,1)}}function $e(e){function t(t,n,r){if(U[t]<U[G])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);(t===`warn`||t===`error`)&&console.error(o);for(let i of W)try{i({level:t,component:e,message:n,data:r})}catch{}He()&&(t===`warn`||t===`error`)&&Ge(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const Z={maxAttempts:3,baseDelayMs:500,maxDelayMs:3e4,jitterFraction:.25};async function et(e,t={}){let{maxAttempts:n=Z.maxAttempts,baseDelayMs:r=Z.baseDelayMs,maxDelayMs:i=Z.maxDelayMs,jitterFraction:a=Z.jitterFraction}=t,o=t.shouldRetry??(e=>e instanceof D),s;for(let c=1;c<=n;c++)try{return await e()}catch(e){if(s=e,c>=n||!o(e,c))throw e;let l;if(e instanceof D&&e.retryAfterMs!=null&&e.retryAfterMs>0)l=Math.min(e.retryAfterMs,i);else{let e=r*2**(c-1),t=Math.min(e,i),n=t*a*(Math.random()*2-1);l=Math.round(t+n)}t.onRetry?.(e,c,l),await tt(l)}throw s}function tt(e){return new Promise(t=>setTimeout(t,e))}let Q;function nt(){return Q===void 0&&(Q=y()),Q}function rt(){try{return process.cwd()}catch{return null}}function it(){return rt()??nt()}const at=[`indexed`,`curated`,`produced`],ot=[`source`,`documentation`,`test`,`config`,`generated`],st=[`auto`,`manual`,`smart`],ct=[`efficient`,`normal`,`full`],lt=[`documentation`,`code-typescript`,`code-javascript`,`code-python`,`code-other`,`config-json`,`config-yaml`,`config-toml`,`config-env`,`test-code`,`cdk-stack`,`markdown`,`curated-knowledge`,`produced-knowledge`,`unknown`],$=$e(`core:version-manager`);function ut(e,t){let n=e.slice(1).split(`.`).map(Number),r=t.slice(1).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(r[e]??0)-(n[e]??0);if(t!==0)return t}return 0}function dt(e){let t=a(e),r=n(ie(import.meta.url)),i=process.cwd();return a(r).startsWith(t+o)||a(i).startsWith(t+o)||a(r)===t||a(i)===t}function ft(e,t){try{if(!d(e)||!t||t===`0.0.0`)return;let n=p(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>e.name).sort(ut),r=new Set([`v${t}`]),a=n.filter(e=>e!==`v${t}`).slice(0,1);for(let e of a)r.add(e);for(let t of n)if(!r.has(t)){let n=i(e,t);if(dt(n)){$.debug(`Skipping ${t} — currently in use by running process`);continue}h(n,{recursive:!0,force:!0}),$.debug(`Cleaned old version: ${t}`)}}catch(e){$.debug(`Version directory cleanup failed`,{error:e})}}export{C as AIKIT_GLOBAL_PATHS,x as AIKIT_PATHS,S as AIKIT_RUNTIME_PATHS,E as AikitError,pe as CATEGORY_PATTERN,oe as CHUNK_SIZES,lt as CONTENT_TYPES,ae as CircuitBreaker,b as CircuitOpenError,we as ConfigError,he as DEFAULT_CATEGORIES,me as DEFAULT_SERVER_NAME,se as EMBEDDING_DEFAULTS,xe as EmbeddingError,de as FILE_LIMITS,Be as HealthBus,st as INDEX_MODES,ue as INSTALL_ARGS,Ce as IndexError,at as KNOWLEDGE_ORIGINS,H as LAYER_FIELD_REQUIREMENTS,ce as MODEL_REGISTRY,O as PermanentError,fe as SEARCH_DEFAULTS,ot as SOURCE_TYPES,le as STORE_DEFAULTS,Se as StoreError,ct as TOKEN_BUDGETS,D as TransientError,Qe as addLogListener,ft as cleanupOldVersions,ut as compareVersionDir,I as computePartitionKey,ye as contentTypeToSourceType,$e as createLogger,ve as detectContentType,P as getGlobalDataDir,qe as getLogLevel,B as getPartitionDir,M as getWorkspacePartitionDir,Ne as hashPath,Ee as isPermanent,Te as isTransient,ze as isUserInstalled,Re as listWorkspaces,L as loadRegistry,Le as lookupWorkspace,N as migrateLegacyWorkspaceLayout,F as normalizePathForHash,z as registerWorkspace,Ye as resetLogDir,V as resolveLogDir,Me as resolveStateDir,rt as safeCwd,it as safeCwdOrHome,R as saveRegistry,Ze as serializeError,Xe as setDetailedErrorLoggingEnabled,Je as setFileSinkEnabled,Ke as setLogLevel,be as sourceTypeContentTypes,Ve as validateLayerMetadata,et as withRetry};
1
+ import{EventEmitter as e}from"node:events";import{basename as t,dirname as n,extname as r,join as i,resolve as a,sep as o}from"node:path";import{createHash as s}from"node:crypto";import{appendFileSync as c,closeSync as l,constants as u,copyFileSync as ee,existsSync as d,lstatSync as te,mkdirSync as f,openSync as ne,readFileSync as re,readdirSync as p,renameSync as m,rmSync as h,statSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{homedir as y,tmpdir as ie}from"node:os";import{fileURLToPath as ae}from"node:url";var oe=class t extends e{static registry=new Map;state=`closed`;failures=0;halfOpenAttempts=0;openUntil=0;threshold;cooldownMs;halfOpenMaxAttempts;jitterMs;name;onStateChange;static getAll(){return t.registry}static get(e){return t.registry.get(e)}static clearRegistry(){t.registry.clear()}constructor(e={}){super(),this.threshold=Math.max(1,e.threshold??3),this.cooldownMs=Math.max(0,e.cooldownMs??6e4),this.halfOpenMaxAttempts=Math.max(1,e.halfOpenMaxAttempts??1),this.jitterMs=Math.max(0,e.jitterMs??0),this.name=e.name,this.onStateChange=e.onStateChange,this.name&&t.registry.set(this.name,this)}async execute(e){this.assertNotOpen();try{let t=await e();return this.recordSuccess(),t}catch(e){throw this.recordFailure(),e}}getState(){return this.refreshState(),this.state}getName(){return this.name}isOpen(){return this.getState()===`open`}reset(){this.failures=0,this.halfOpenAttempts=0,this.openUntil=0,this.transitionTo(`closed`,`manual reset`)}dispose(){this.name&&t.registry.get(this.name)===this&&t.registry.delete(this.name),this.removeAllListeners()}setCooldown(e){this.cooldownMs=Math.max(0,e)}getCooldown(){return this.cooldownMs}forceOpen(e){this.failures=this.threshold,this.halfOpenAttempts=0,this.transitionTo(`open`,e??`manual override`)}recordSuccess(){this.refreshState(),this.failures=0,this.halfOpenAttempts=0,this.state===`half-open`&&this.transitionTo(`closed`,`probe succeeded`)}recordFailure(){if(this.refreshState(),this.failures+=1,this.halfOpenAttempts=0,this.state===`half-open`){this.transitionTo(`open`,`probe failed`);return}this.state===`closed`&&this.failures>=this.threshold&&this.transitionTo(`open`,`failure threshold reached`)}remainingCooldownMs(){return this.refreshState(),this.state===`open`?Math.max(0,this.openUntil-Date.now()):0}assertNotOpen(){if(this.refreshState(),this.state===`open`)throw new b(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new b(this.remainingCooldownMs());this.halfOpenAttempts+=1}}refreshState(){this.state===`open`&&Date.now()>=this.openUntil&&(this.halfOpenAttempts=0,this.transitionTo(`half-open`,`cooldown expired`))}transitionTo(e,t){let n=this.state;if(n===e){e===`open`&&(this.openUntil=this.computeOpenUntil());return}this.state=e,e===`open`?(this.openUntil=this.computeOpenUntil(),this.halfOpenAttempts=0):(this.openUntil=0,e===`closed`&&(this.halfOpenAttempts=0)),this.onStateChange?.(n,e),this.emit(e,{from:n,reason:t})}computeOpenUntil(){return Date.now()+this.cooldownMs+Math.floor(Math.random()*this.jitterMs)}},b=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const x={root:`.aikit`,ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit/data`,state:`.aikit/state`,logs:`.aikit/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},S={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`,l0Cards:`memories`},C={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},se={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},ce={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},le={"mixedbread-ai/mxbai-embed-xsmall-v1":{nativeDim:384,dimensions:384,queryPrefix:``,pooling:`mean`},"mixedbread-ai/mxbai-embed-large-v1":{nativeDim:1024,dimensions:512,queryPrefix:`Represent this sentence for searching relevant passages: `,pooling:`cls`}},ue={backend:`sqlite-vec`,path:x.data,tableName:`knowledge`},de=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],fe={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},pe={maxResults:10,minScore:.25},me=/^[a-z][a-z0-9-]*$/,he=`AI Kit`,ge=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],_e={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},ve=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],ye=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function be(e){let n=r(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${x.aiContext}/`)?`produced-knowledge`:e.includes(`${x.aiCurated}/`)?`curated-knowledge`:ve.some(t=>t.test(e))?`test-code`:ye.some(t=>t.test(e))?`cdk-stack`:n in _e?_e[n]:i.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(n)?`code-other`:`unknown`}const w={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function xe(e){return w[e]??`source`}function Se(e){return Object.entries(w).filter(([,t])=>t===e).map(([e])=>e)}var T=class extends Error{code;constructor(e,t,n){super(e,n===void 0?void 0:{cause:n}),this.code=t,this.name=`AikitError`}},Ce=class extends T{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},we=class extends T{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},Te=class extends T{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},Ee=class extends T{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},E=class extends T{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},D=class extends T{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function De(e){return e instanceof E}function Oe(e){return e instanceof D}let O=!1;function ke(e){try{return!te(e).isSymbolicLink()}catch{return!1}}function Ae(e,t){if(g(e).isDirectory()){f(t,{recursive:!0});for(let n of p(e))k(a(e,n),a(t,n));h(e,{recursive:!0,force:!0});return}f(a(t,`..`),{recursive:!0}),ee(e,t),_(e)}function je(e,t){try{m(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!d(e)&&d(t))return;if(r!==`EXDEV`)throw n;Ae(e,t)}}function k(e,t){if(!d(e)||e===t||!ke(e))return;let n=g(e);if(!d(t)){f(a(t,`..`),{recursive:!0}),je(e,t);return}if(!n.isDirectory())return;f(t,{recursive:!0});let r;try{r=p(e)}catch{return}for(let n of r)k(a(e,n),a(t,n));try{h(e,{recursive:!0,force:!0})}catch{}}function A(e){if(d(e))try{p(e).length===0&&h(e,{recursive:!0,force:!0})}catch{}}function Me(e){let t=a(e,S.data);f(t,{recursive:!0});for(let n of p(e))n!==S.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&k(a(e,n),a(t,n))}function j(e){return R(F(e))}function Ne(e){if(O)return;O=!0,f(e,{recursive:!0});let t=y(),n=a(t,C.legacyDataRoot),r=a(t,C.legacyStateRoot),i=a(e,C.workspaces),o=a(e,C.logs),s=a(e,C.state);if(d(n)&&n!==e){f(i,{recursive:!0});for(let t of p(n))k(a(n,t),t===C.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?a(e,t):a(i,t));A(n)}if(d(r)&&r!==e){for(let e of p(r))k(a(r,e),e===`logs`?o:a(s,e));A(r)}}function M(e){let t=a(e),n=j(t),r=a(n,S.data),i=a(N(),C.logs),o=[{from:a(t,C.legacyDataRoot),to:r},{from:a(t,C.legacyStateRoot),to:a(n,S.state)},{from:a(t,x.data),to:r},{from:a(t,x.state),to:a(n,S.state)},{from:a(t,x.aiCurated),to:a(n,S.curated)},{from:a(t,x.aiContext),to:a(n,S.onboard)},{from:a(t,x.restorePoints),to:a(n,S.restorePoints)},{from:a(t,x.brainstorm),to:a(n,S.brainstorm)},{from:a(t,x.handoffs),to:a(n,S.handoffs)},{from:a(t,x.logs),to:i}];f(n,{recursive:!0}),f(i,{recursive:!0}),Me(n);for(let e of o)k(e.from,e.to);A(a(t,x.root)),A(a(t,x.ai)),A(a(t,x.brainstorm)),A(a(t,x.handoffs))}function Pe(e){return a(R(F(e)),S.state)}function Fe(e){return M(e),a(R(Be(e).partition),S.state)}function N(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??a(y(),C.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&Ne(t),t}function P(e){return Le()?e.toLowerCase():e}function F(e){let n=a(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${s(`sha256`).update(P(n)).digest(`hex`).slice(0,8)}`}function Ie(e,t=12){let n=a(e);return s(`sha256`).update(P(n)).digest(`hex`).slice(0,t)}function Le(){return process.platform===`win32`||process.platform===`darwin`}function I(){let e=a(N(),C.registry);if(!d(e))return{version:1,workspaces:{}};let t=re(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Re(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=ne(n,u.O_CREAT|u.O_EXCL|u.O_WRONLY);return v(e,`${process.pid}\n`),l(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=g(n);if(Date.now()-e>3e4){_(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function ze(e){try{_(e)}catch{}}function L(e){let t=N();f(t,{recursive:!0});let n=a(t,C.registry),r=Re(n);try{let t=`${n}.tmp`;v(t,JSON.stringify(e,null,2),`utf-8`),m(t,n)}finally{ze(r)}}function Be(e){let t=I(),n=F(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:a(e),registeredAt:r,lastAccessedAt:r},f(R(n),{recursive:!0}),L(t),t.workspaces[n]}function Ve(e){let t=I(),n=F(e);return t.workspaces[n]}function He(){let e=I();return Object.values(e.workspaces)}function R(e){return a(N(),C.workspaces,e)}function Ue(){return d(a(N(),C.registry))}function We(){return a(N(),C.logs)}var Ge=class t extends e{static _instance=null;subsystems=new Map;constructor(){super()}static instance(){return t._instance||=new t,t._instance}static reset(){t._instance?.removeAllListeners(),t._instance=null}register(e){this.subsystems.has(e)||this.subsystems.set(e,{name:e,status:`healthy`,since:Date.now()})}reportDegraded(e,t){this.transition(e,`degraded`,t)}reportUnavailable(e,t){this.transition(e,`unavailable`,t)}reportRecovered(e){this.transition(e,`healthy`)}isDegraded(e){let t=this.subsystems.get(e);return t?.status===`degraded`||t?.status===`unavailable`}isHealthy(e){return this.subsystems.get(e)?.status===`healthy`}getAll(){return Array.from(this.subsystems.values(),e=>({...e}))}getSubsystem(e){let t=this.subsystems.get(e);return t?{...t}:void 0}transition(e,t,n){let r=this.subsystems.get(e);if(!r||r.status===t)return;let i={subsystem:e,status:t,previousStatus:r.status,reason:n,timestamp:Date.now()};r.status=t,r.since=i.timestamp,r.reason=n,this.emit(t,i),this.emit(`change`,i)}};function Ke(e,t){let n=z[e];if(!n)return{valid:!1,missingRequired:[`Unknown layer: ${e}`],extraFields:[]};let r=[];for(let e of n.required)(t[e]===void 0||t[e]===null)&&r.push(e);let i=new Set([...n.required,...n.optional]),a=[];for(let e of Object.keys(t))e!==`layer`&&(i.has(e)||a.push(e));return{valid:r.length===0&&a.length===0,missingRequired:r,extraFields:a}}const z={l0:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`cardType`,`tokenBudget`,`selectionReason`],optional:[`topicKey`,`tags`,`taskId`,`flowSlug`,`freshness`,`referenceRefs`,`quality`,`decision`]},l1:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`flowSlug`,`runId`,`stepId`,`stepIndex`,`objective`,`acceptanceCriteria`],optional:[`scope`,`exclusions`,`retrievedRefs`,`verifiedClaims`,`assumedClaims`,`unresolvedClaims`,`decisions`,`rationale`,`artifacts`,`stepSummaries`,`failures`,`successPatterns`,`candidateLearnings`,`verifiedFinalOutcome`,`decision`]},l2:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`topicKey`,`curatedMarkdownPath`,`managedBy`,`promotionState`],optional:[`tags`,`evidenceRefs`,`freshness`,`supersededBy`,`confidence`,`quality`,`rationale`,`decision`]},l3:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`evidenceRefs`,`quality`],optional:[`flowSlug`,`runId`,`stepId`,`recurrence`,`impact`,`sourceDiversity`,`topicKey`,`tags`,`ttlMs`,`decision`]}},B={debug:0,info:1,warn:2,error:3},V=[];let H=process.env.AIKIT_LOG_LEVEL??`info`,U=!1,W=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function qe(){return W?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let G;function K(){return G||=We(),G}function Je(e){let t=e.toISOString().slice(0,10);return i(K(),`${t}.jsonl`)}let q=0;function Ye(){let e=Date.now();if(!(e-q<36e5)){q=e;try{let t=K(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of p(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{_(i(t,e))}catch{}}catch{}}}function Xe(e,t){try{f(K(),{recursive:!0}),c(Je(t),`${e}\n`),Ye()}catch{}}function Ze(e){H=e}function Qe(){return H}function $e(e){W=e}function et(){G=void 0}function tt(e){U=e}function nt(e){if(e instanceof Error){let t={error:e.message};return U?(e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t):t}return{error:String(e)}}function rt(e){return V.push(e),()=>{let t=V.indexOf(e);t>=0&&V.splice(t,1)}}function J(e){function t(t,n,r){if(B[t]<B[H])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);(t===`warn`||t===`error`)&&console.error(o);for(let i of V)try{i({level:t,component:e,message:n,data:r})}catch{}qe()&&(t===`warn`||t===`error`)&&Xe(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const Y={maxAttempts:3,baseDelayMs:500,maxDelayMs:3e4,jitterFraction:.25};async function it(e,t={}){let{maxAttempts:n=Y.maxAttempts,baseDelayMs:r=Y.baseDelayMs,maxDelayMs:i=Y.maxDelayMs,jitterFraction:a=Y.jitterFraction}=t,o=t.shouldRetry??(e=>e instanceof E),s;for(let c=1;c<=n;c++)try{return await e()}catch(e){if(s=e,c>=n||!o(e,c))throw e;let l;if(e instanceof E&&e.retryAfterMs!=null&&e.retryAfterMs>0)l=Math.min(e.retryAfterMs,i);else{let e=r*2**(c-1),t=Math.min(e,i),n=t*a*(Math.random()*2-1);l=Math.round(t+n)}t.onRetry?.(e,c,l),await at(l)}throw s}function at(e){return new Promise(t=>setTimeout(t,e))}let X;function ot(){return X===void 0&&(X=y()),X}function st(){try{return process.cwd()}catch{return null}}function ct(){return st()??ot()}let Z,Q;function lt(){return Q=process.env.AIKIT_GLOBAL_DATA_DIR,Z=i(ie(),`aikit-test-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),f(Z,{recursive:!0}),process.env.AIKIT_GLOBAL_DATA_DIR=Z,Z}function ut(){if(Q===void 0?delete process.env.AIKIT_GLOBAL_DATA_DIR:process.env.AIKIT_GLOBAL_DATA_DIR=Q,Q=void 0,Z)try{h(Z,{recursive:!0,force:!0})}catch{}Z=void 0}const dt=[`indexed`,`curated`,`produced`],ft=[`source`,`documentation`,`test`,`config`,`generated`],pt=[`auto`,`manual`,`smart`],mt=[`efficient`,`normal`,`full`],ht=[`documentation`,`code-typescript`,`code-javascript`,`code-python`,`code-other`,`config-json`,`config-yaml`,`config-toml`,`config-env`,`test-code`,`cdk-stack`,`markdown`,`curated-knowledge`,`produced-knowledge`,`unknown`],$=J(`core:version-manager`);function gt(e,t){let n=e.slice(1).split(`.`).map(Number),r=t.slice(1).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(r[e]??0)-(n[e]??0);if(t!==0)return t}return 0}function _t(e){let t=a(e),r=n(ae(import.meta.url)),i=process.cwd();return a(r).startsWith(t+o)||a(i).startsWith(t+o)||a(r)===t||a(i)===t}function vt(e,t){try{if(!d(e)||!t||t===`0.0.0`)return;let n=p(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>e.name).sort(gt),r=new Set([`v${t}`]),a=n.filter(e=>e!==`v${t}`).slice(0,1);for(let e of a)r.add(e);for(let t of n)if(!r.has(t)){let n=i(e,t);if(_t(n)){$.debug(`Skipping ${t} — currently in use by running process`);continue}h(n,{recursive:!0,force:!0}),$.debug(`Cleaned old version: ${t}`)}}catch(e){$.debug(`Version directory cleanup failed`,{error:e})}}export{C as AIKIT_GLOBAL_PATHS,x as AIKIT_PATHS,S as AIKIT_RUNTIME_PATHS,T as AikitError,me as CATEGORY_PATTERN,se as CHUNK_SIZES,ht as CONTENT_TYPES,oe as CircuitBreaker,b as CircuitOpenError,Ee as ConfigError,ge as DEFAULT_CATEGORIES,he as DEFAULT_SERVER_NAME,ce as EMBEDDING_DEFAULTS,Ce as EmbeddingError,fe as FILE_LIMITS,Ge as HealthBus,pt as INDEX_MODES,de as INSTALL_ARGS,Te as IndexError,dt as KNOWLEDGE_ORIGINS,z as LAYER_FIELD_REQUIREMENTS,le as MODEL_REGISTRY,D as PermanentError,pe as SEARCH_DEFAULTS,ft as SOURCE_TYPES,ue as STORE_DEFAULTS,we as StoreError,mt as TOKEN_BUDGETS,E as TransientError,rt as addLogListener,vt as cleanupOldVersions,gt as compareVersionDir,F as computePartitionKey,Pe as computeStateDir,xe as contentTypeToSourceType,J as createLogger,be as detectContentType,N as getGlobalDataDir,Qe as getLogLevel,R as getPartitionDir,j as getWorkspacePartitionDir,Ie as hashPath,Oe as isPermanent,De as isTransient,Ue as isUserInstalled,lt as isolateGlobalDataDir,He as listWorkspaces,I as loadRegistry,Ve as lookupWorkspace,M as migrateLegacyWorkspaceLayout,P as normalizePathForHash,Be as registerWorkspace,et as resetLogDir,We as resolveLogDir,Fe as resolveStateDir,ut as restoreGlobalDataDir,st as safeCwd,ct as safeCwdOrHome,L as saveRegistry,nt as serializeError,tt as setDetailedErrorLoggingEnabled,$e as setFileSinkEnabled,Ze as setLogLevel,Se as sourceTypeContentTypes,Ke as validateLayerMetadata,it as withRetry};
@@ -2641,6 +2641,10 @@ interface PruneResult {
2641
2641
  count: number;
2642
2642
  bytesFreed: number;
2643
2643
  };
2644
+ orphanPartitions: {
2645
+ count: number;
2646
+ bytesFreed: number;
2647
+ };
2644
2648
  browserProfiles: {
2645
2649
  count: number;
2646
2650
  bytesFreed: number;
@@ -2649,6 +2653,23 @@ interface PruneResult {
2649
2653
  dryRun: boolean;
2650
2654
  }
2651
2655
  declare function formatBytes(bytes: number): string;
2656
+ /**
2657
+ * Clean unregistered orphan partition directories under the global workspaces dir.
2658
+ *
2659
+ * "Orphan" = a directory in workspaces/ that has no corresponding entry in the
2660
+ * global registry. These are created when test/temp workspace paths are passed
2661
+ * into partition helpers (getPartitionDir, registerWorkspace, resolveStateDir)
2662
+ * without AIKIT_GLOBAL_DATA_DIR isolation.
2663
+ *
2664
+ * @param globalDir The global data directory (workspaces/ lives inside it)
2665
+ * @param maxAgeDays Minimum age in days before cleanup (default 1 day)
2666
+ * @param dryRun If true, only report without deleting
2667
+ * @returns Count of orphans found and bytes freed
2668
+ */
2669
+ declare function cleanOrphanPartitions(globalDir: string, maxAgeDays?: number, dryRun?: boolean): {
2670
+ count: number;
2671
+ bytesFreed: number;
2672
+ };
2652
2673
  declare function prune(options?: PruneOptions): PruneResult;
2653
2674
  declare function shouldRunStartupPrune(): boolean;
2654
2675
  declare function markPruneRun(): void;
@@ -3747,4 +3768,4 @@ declare function addToWorkset(name: string, files: string[], cwd?: string): Work
3747
3768
  */
3748
3769
  declare function removeFromWorkset(name: string, files: string[], cwd?: string): Workset | null;
3749
3770
  //#endregion
3750
- export { type AikitNextHint, type AikitResponse, type AikitResponseMeta, type AikitToolError, type AikitToolErrorCode, type AuditCheck, type AuditData, type AuditOptions, type AuditRecommendation, BRIEFING_CARD_FAMILIES, type BenchmarkReport, type BlastNode, type CardSection, type CardSectionBudget, type ChangelogEntry, type ChangelogFormat, type ChangelogOptions, type ChangelogResult, type CheckOptions, type CheckResult, type CheckSummaryResult, type Checkpoint, type CheckpointSummary, type ClassifyTrigger, type CodemodChange, type CodemodOptions, type CodemodResult, type CodemodRule, type CommunityInfo, type CompactOptions, type CompactResult, type ComplianceReport, type ComplianceRule, type ComplianceScoreOptions, type ComplianceViolation, type CompressOutputOptions, type CompressionContext, type CompressionMode, type CompressionResult, type CompressionRule, type ConstraintRef, type CorpusStats, type DeadSymbol, type DeadSymbolOptions, type DeadSymbolResult, type Definition, type DelegateOptions, type DelegateResult, type DetectedRoute, type DiffChange, type DiffFile, type DiffHunk, type DiffParseOptions, type DiffReport, type DigestFieldEntry, type DigestOptions, type DigestResult, type DigestSource, type DogfoodLogEntry, type DogfoodLogGroupedEntry, type DogfoodLogOptions, type DogfoodLogResult, type Domain, type DomainAnalysisInput, type DomainClassification, type DomainType, type EncodeOperation, type EncodeOptions, type EncodeResult, type EnrichOptions, type EnrichStructureEntry, type EnrichSymbolEntry, type EnvInfoOptions, type EnvInfoResult, type EvalOptions, type EvalResult, type EvidenceEntry, type EvidenceMapAction, type EvidenceMapResult, type EvidenceMapState, type EvidenceStatus, type Example, type ExportMap, ExtractionCache, type ExtractionCacheEntry, FRONTMATTER_OVERHEAD_CHARS, FileCache, type FileCacheEntry, type FileCacheStats, type FileChange, type FileMetrics, type FileSummaryOptions, type FileSummaryResult, type FileSummaryToolCard, type FileSummaryToolOptions, type FileSummaryToolResult, type FindExamplesOptions, type FindExamplesResult, type FindOptions, type FindResult, type FindResults, type Finding, type FindingSeverity, type ForgeClassifyCeremony, type ForgeClassifyOptions, type ForgeClassifyResult, type ForgeGroundOptions, type ForgeGroundResult, type ForgeTier, GIT_REF_SLUG_PATTERN, type GateConfig, type GateDecision, type GateResult, type GitContextOptions, type GitContextResult, type GraphAugmentOptions, type GraphAugmentedResult, type GraphQueryOptions, type GraphQueryResult, type GraphReviewReport, type GraphStats, type GuideRecommendation, type GuideResult, type GuidedTour, type GuidedTourOptions, type HealthCheck, type HealthResult, type HotspotEntry, type HttpMethod, type HttpRequestOptions, type HttpRequestResult, type ImportGraph, type ImportMap, type KnowledgeGraph, type L0CardInput, type L0CardMetadata, LLMEnricher, type LaneDiffEntry, type LaneDiffResult, type LaneMergeResult, type LaneMeta, type LayerDetectionInput, type LayerType, type Lease, type LeaseConflict, type LegacyStashOptions, MAX_CARD_CHARS, type ManagedProcess, type MeasureOptions, type MeasureResult, type ModuleInsight, type OnboardMode, type OnboardOptions, type OnboardResult, type OnboardStepResult, type ParsedError, type ParsedGitStatus, type ParsedOutput, type ParsedTestResult, type ParsedTestSummary, type PipelineResult, type PromotedKnowledgeEntry, type PruneOptions, type PruneResult, type QueueItem, type QueueState, type RefTelemetry, type RegexTestOptions, type RegexTestResult, type RenameChange, type RenameOptions, type RenameResult, type ReplayEntry, type ReplayOptions, type Resolution, type ResolutionMethod, type ResolutionOptions, type ResolvedImport, type RestorePoint, type ReverseGraph, type RouteDetectionResult, SECTION_BUDGETS, SECTION_NAMES, type SafetyGate, type SafetyGateResult, type ScanResult, type ScannedFile, type SchemaValidateOptions, type SchemaValidateResult, type ScopeMapEntry, type ScopeMapOptions, type ScopeMapResult, type SearchResponseData, type SearchResponseItem, type SearchSuccessResponseOptions, type SessionDigestOptions, type SessionDigestResult, type SessionStartSelection, type SkillMatch, type SkillTriggerExamples, type SkillTriggerMeta, type StashEntry, type StashStore, type SymbolGraphContext, type SymbolInfo, type SymbolOptions, type TestRunOptions, type TestRunResult, type TimeOptions, type TimeResult, type TimeoutAction, type TourStep, type TraceNode, type TraceOptions, type TraceResult, type TransformOptions, type TransformResult, type TypedUnknownSeed, type UnknownType, type ValidationError, WORKSPACE_CORE_FILENAME, type WatchEvent, type WatchHandle, type WatchOptions, type WebFetchMode, type WebFetchOptions, type WebFetchResult, type WebSearchOptions, type WebSearchResult, type WebSearchResultItem, type Workset, type WorksetStore, acquireLease, addToWorkset, analyzeDiff, analyzeDomain, analyzeDomains, analyzeFile, audit, autoClaimTestFailures, benchmarkFiles, benchmarkTokenReduction, bookendReorder, bpeSurprise, buildExportMap, buildImportGraph, buildImportMap, buildNodeNameMap, buildReverseGraph, callId, changelog, check, checkEmptyGraph, checkMissingFields, checkSchemaVersion, checkpointDiff, checkpointGC, checkpointHistory, checkpointLatest, checkpointList, checkpointLoad, checkpointSave, classifyDomain, classifyDomains, classifyExitCode, codemod, compact, compressOutput, compressTerminalOutput, computeSourceHash, cosineSimilarity, createRestorePoint, createSearchErrorResponse, createSearchSuccessResponse, dataTransform, delegate, delegateListModels, deleteWorkset, describeBriefingCards, detectLayer, detectLayers, detectOutputTool, detectRoutes, diffParse, digest, dogfoodLog, edgeId, encode, ensureLegacyStashImported, envInfo, errorResponse, escapeRegExp, estimateGraphTokens, estimateSessionTokenBudget, estimateTokens, evaluate, evidenceMap, extractImports, extractRoutesFromFile, fileId, fileSummary, fileSummaryTool, find, findDanglingEdges, findDeadSymbols, findDuplicateIds, findExamples, findOrphanNodes, findSelfLoops, findTour, forgeClassify, forgeGround, formatBytes, formatChangelog, formatDomainReport, formatEmptyResult, formatTour, formatToursIndex, generateGuidedTours, generateL0WorkspaceCoreCard, getRefTelemetry, getRegisteredRules, getReversibleContext, getReversibleContextFresh, getSessionStartCards, getWorkset, gitAvailable, gitCommitToRef, gitContext, gitExec, graphAugmentSearch, graphQuery, groupByDomain, guide, hasReversibleContext, headTailTruncate, health, httpRequest, inferNextjsRoutes, isCardStale, isReversibleContextRef, laneCreate, laneDiff, laneDiscard, laneList, laneMerge, laneStatus, listActiveLeases, listRestorePoints, listWorksets, markPromoteRun, markPruneRun, matchSkills, measure, measureCorpus, normalizePath, okResponse, onboard, orderByDependency, paragraphTruncate, parseBiome, parseCardMetadata, parseGitStatus, parseOutput, parseSearchResults, parseTsc, parseVitest, processList, processLogs, processStart, processStatus, processStop, processStopAll, prune, queueClear, queueCreate, queueDag, queueDelete, queueDone, queueFail, queueGet, queueList, queueNext, queuePush, regexTest, registerRule, registerRules, releaseLease, removeFromWorkset, rename, replayAppend, replayCapture, replayClear, replayList, replayTrim, resetGitCache, resetRefTelemetry, resolveImportPath, resolveL0CardDir, resolveNodeName, resolvePath, resolveSymbol, resolveSymbols, resolveWorkspaceDir, restoreFromPoint, reviewGraph, runPipeline, saveWorkset, scanCodebase, schemaValidate, scopeMap, scoreCompliance, scoreLine, scoreLines, segment, sessionDigest, sessionDigestSampling, shannonEntropy, shouldRunStartupPrune, shouldRunWeeklyPromote, slugForRef, stashClear, stashDelete, stashGet, stashList, stashSet, storeReversibleContext, summarizeCheckResult, symbol, symbolId, testRun, timeUtils, trace, transformCommunities, traverseBlastRadius, truncateToTokenBudget, watchList, watchStart, watchStop, webFetch, webSearch, workspacePath };
3771
+ export { type AikitNextHint, type AikitResponse, type AikitResponseMeta, type AikitToolError, type AikitToolErrorCode, type AuditCheck, type AuditData, type AuditOptions, type AuditRecommendation, BRIEFING_CARD_FAMILIES, type BenchmarkReport, type BlastNode, type CardSection, type CardSectionBudget, type ChangelogEntry, type ChangelogFormat, type ChangelogOptions, type ChangelogResult, type CheckOptions, type CheckResult, type CheckSummaryResult, type Checkpoint, type CheckpointSummary, type ClassifyTrigger, type CodemodChange, type CodemodOptions, type CodemodResult, type CodemodRule, type CommunityInfo, type CompactOptions, type CompactResult, type ComplianceReport, type ComplianceRule, type ComplianceScoreOptions, type ComplianceViolation, type CompressOutputOptions, type CompressionContext, type CompressionMode, type CompressionResult, type CompressionRule, type ConstraintRef, type CorpusStats, type DeadSymbol, type DeadSymbolOptions, type DeadSymbolResult, type Definition, type DelegateOptions, type DelegateResult, type DetectedRoute, type DiffChange, type DiffFile, type DiffHunk, type DiffParseOptions, type DiffReport, type DigestFieldEntry, type DigestOptions, type DigestResult, type DigestSource, type DogfoodLogEntry, type DogfoodLogGroupedEntry, type DogfoodLogOptions, type DogfoodLogResult, type Domain, type DomainAnalysisInput, type DomainClassification, type DomainType, type EncodeOperation, type EncodeOptions, type EncodeResult, type EnrichOptions, type EnrichStructureEntry, type EnrichSymbolEntry, type EnvInfoOptions, type EnvInfoResult, type EvalOptions, type EvalResult, type EvidenceEntry, type EvidenceMapAction, type EvidenceMapResult, type EvidenceMapState, type EvidenceStatus, type Example, type ExportMap, ExtractionCache, type ExtractionCacheEntry, FRONTMATTER_OVERHEAD_CHARS, FileCache, type FileCacheEntry, type FileCacheStats, type FileChange, type FileMetrics, type FileSummaryOptions, type FileSummaryResult, type FileSummaryToolCard, type FileSummaryToolOptions, type FileSummaryToolResult, type FindExamplesOptions, type FindExamplesResult, type FindOptions, type FindResult, type FindResults, type Finding, type FindingSeverity, type ForgeClassifyCeremony, type ForgeClassifyOptions, type ForgeClassifyResult, type ForgeGroundOptions, type ForgeGroundResult, type ForgeTier, GIT_REF_SLUG_PATTERN, type GateConfig, type GateDecision, type GateResult, type GitContextOptions, type GitContextResult, type GraphAugmentOptions, type GraphAugmentedResult, type GraphQueryOptions, type GraphQueryResult, type GraphReviewReport, type GraphStats, type GuideRecommendation, type GuideResult, type GuidedTour, type GuidedTourOptions, type HealthCheck, type HealthResult, type HotspotEntry, type HttpMethod, type HttpRequestOptions, type HttpRequestResult, type ImportGraph, type ImportMap, type KnowledgeGraph, type L0CardInput, type L0CardMetadata, LLMEnricher, type LaneDiffEntry, type LaneDiffResult, type LaneMergeResult, type LaneMeta, type LayerDetectionInput, type LayerType, type Lease, type LeaseConflict, type LegacyStashOptions, MAX_CARD_CHARS, type ManagedProcess, type MeasureOptions, type MeasureResult, type ModuleInsight, type OnboardMode, type OnboardOptions, type OnboardResult, type OnboardStepResult, type ParsedError, type ParsedGitStatus, type ParsedOutput, type ParsedTestResult, type ParsedTestSummary, type PipelineResult, type PromotedKnowledgeEntry, type PruneOptions, type PruneResult, type QueueItem, type QueueState, type RefTelemetry, type RegexTestOptions, type RegexTestResult, type RenameChange, type RenameOptions, type RenameResult, type ReplayEntry, type ReplayOptions, type Resolution, type ResolutionMethod, type ResolutionOptions, type ResolvedImport, type RestorePoint, type ReverseGraph, type RouteDetectionResult, SECTION_BUDGETS, SECTION_NAMES, type SafetyGate, type SafetyGateResult, type ScanResult, type ScannedFile, type SchemaValidateOptions, type SchemaValidateResult, type ScopeMapEntry, type ScopeMapOptions, type ScopeMapResult, type SearchResponseData, type SearchResponseItem, type SearchSuccessResponseOptions, type SessionDigestOptions, type SessionDigestResult, type SessionStartSelection, type SkillMatch, type SkillTriggerExamples, type SkillTriggerMeta, type StashEntry, type StashStore, type SymbolGraphContext, type SymbolInfo, type SymbolOptions, type TestRunOptions, type TestRunResult, type TimeOptions, type TimeResult, type TimeoutAction, type TourStep, type TraceNode, type TraceOptions, type TraceResult, type TransformOptions, type TransformResult, type TypedUnknownSeed, type UnknownType, type ValidationError, WORKSPACE_CORE_FILENAME, type WatchEvent, type WatchHandle, type WatchOptions, type WebFetchMode, type WebFetchOptions, type WebFetchResult, type WebSearchOptions, type WebSearchResult, type WebSearchResultItem, type Workset, type WorksetStore, acquireLease, addToWorkset, analyzeDiff, analyzeDomain, analyzeDomains, analyzeFile, audit, autoClaimTestFailures, benchmarkFiles, benchmarkTokenReduction, bookendReorder, bpeSurprise, buildExportMap, buildImportGraph, buildImportMap, buildNodeNameMap, buildReverseGraph, callId, changelog, check, checkEmptyGraph, checkMissingFields, checkSchemaVersion, checkpointDiff, checkpointGC, checkpointHistory, checkpointLatest, checkpointList, checkpointLoad, checkpointSave, classifyDomain, classifyDomains, classifyExitCode, cleanOrphanPartitions, codemod, compact, compressOutput, compressTerminalOutput, computeSourceHash, cosineSimilarity, createRestorePoint, createSearchErrorResponse, createSearchSuccessResponse, dataTransform, delegate, delegateListModels, deleteWorkset, describeBriefingCards, detectLayer, detectLayers, detectOutputTool, detectRoutes, diffParse, digest, dogfoodLog, edgeId, encode, ensureLegacyStashImported, envInfo, errorResponse, escapeRegExp, estimateGraphTokens, estimateSessionTokenBudget, estimateTokens, evaluate, evidenceMap, extractImports, extractRoutesFromFile, fileId, fileSummary, fileSummaryTool, find, findDanglingEdges, findDeadSymbols, findDuplicateIds, findExamples, findOrphanNodes, findSelfLoops, findTour, forgeClassify, forgeGround, formatBytes, formatChangelog, formatDomainReport, formatEmptyResult, formatTour, formatToursIndex, generateGuidedTours, generateL0WorkspaceCoreCard, getRefTelemetry, getRegisteredRules, getReversibleContext, getReversibleContextFresh, getSessionStartCards, getWorkset, gitAvailable, gitCommitToRef, gitContext, gitExec, graphAugmentSearch, graphQuery, groupByDomain, guide, hasReversibleContext, headTailTruncate, health, httpRequest, inferNextjsRoutes, isCardStale, isReversibleContextRef, laneCreate, laneDiff, laneDiscard, laneList, laneMerge, laneStatus, listActiveLeases, listRestorePoints, listWorksets, markPromoteRun, markPruneRun, matchSkills, measure, measureCorpus, normalizePath, okResponse, onboard, orderByDependency, paragraphTruncate, parseBiome, parseCardMetadata, parseGitStatus, parseOutput, parseSearchResults, parseTsc, parseVitest, processList, processLogs, processStart, processStatus, processStop, processStopAll, prune, queueClear, queueCreate, queueDag, queueDelete, queueDone, queueFail, queueGet, queueList, queueNext, queuePush, regexTest, registerRule, registerRules, releaseLease, removeFromWorkset, rename, replayAppend, replayCapture, replayClear, replayList, replayTrim, resetGitCache, resetRefTelemetry, resolveImportPath, resolveL0CardDir, resolveNodeName, resolvePath, resolveSymbol, resolveSymbols, resolveWorkspaceDir, restoreFromPoint, reviewGraph, runPipeline, saveWorkset, scanCodebase, schemaValidate, scopeMap, scoreCompliance, scoreLine, scoreLines, segment, sessionDigest, sessionDigestSampling, shannonEntropy, shouldRunStartupPrune, shouldRunWeeklyPromote, slugForRef, stashClear, stashDelete, stashGet, stashList, stashSet, storeReversibleContext, summarizeCheckResult, symbol, symbolId, testRun, timeUtils, trace, transformCommunities, traverseBlastRadius, truncateToTokenBudget, watchList, watchStart, watchStop, webFetch, webSearch, workspacePath };