From e6bdb1a37b8607efe56cc8dcd278d0324facaeef Mon Sep 17 00:00:00 2001 From: Andrei Hasna Date: Mon, 10 Aug 2026 20:56:33 +0300 Subject: [PATCH] chore(release): knowledge 0.2.103 Prepare @hasna/knowledge 0.2.103 from the merged project resource-link implementation, including the version-bearing generated package artifacts. Agent: Theophrastus --- CHANGELOG.md | 8 ++++++++ bin/knowledge-mcp.js | 2 +- bin/knowledge.js | 2 +- dist/index.js | 2 +- package.json | 2 +- 5 files changed, 12 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78f6147..5c9784b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 0.2.103 + +- Add package-owned Knowledge project and collection aggregates with + deterministic stable IDs, explicit item membership, immutable forward and + inverse receipts, and exact readback. +- Add bounded complete project, collection, item, and taxonomy enumeration + across SQLite, PostgreSQL, REST/OpenAPI, SDK, CLI, and generated packages. + ## 0.2.102 - Republish the same reviewed bounded-query product code through the isolated diff --git a/bin/knowledge-mcp.js b/bin/knowledge-mcp.js index 9688f17..c34ab99 100755 --- a/bin/knowledge-mcp.js +++ b/bin/knowledge-mcp.js @@ -14997,7 +14997,7 @@ import { existsSync as existsSync15, readFileSync as readFileSync14, writeFileSy // package.json var package_default = { name: "@hasna/knowledge", - version: "0.2.102", + version: "0.2.103", description: "Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions", type: "module", exports: { diff --git a/bin/knowledge.js b/bin/knowledge.js index 1200ffb..e5fd8ee 100755 --- a/bin/knowledge.js +++ b/bin/knowledge.js @@ -1413,7 +1413,7 @@ Pages should be concise, cited, and organized for both humans and agents. WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ? AND item_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$.collection_id,$.item_id]))throw new a("KNOWLEDGE_PROJECT_LINKS_CONFLICT","item-binding inverse verification found the membership still present.");return{accepted_receipt_id:_.accepted_receipt_id,target_id:$.item_id,absent:!0,digest:$.result_digest}}async buildResources(_){let $=await this.getAggregateByProject(this.sql,k_(_,"project_id"));if(!$)throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge project aggregate was not found by source or stable project id.");let D=await this.sql.many(`SELECT * FROM knowledge_project_collection_memberships WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ? - ORDER BY item_id ASC`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$.collection_id]),I=await Promise.all(D.map(async(S)=>{let L=await this.itemResolver(S.item_id);if(!L||L.id!==S.item_id)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","collection membership points at a missing Knowledge item; refusing a partial resource population.",{collection_id:$.collection_id,item_id:S.item_id});return L})),U=`r${Number($.revision)}`,E={project_id:$.project_id,source_project_id:$.source_project_id,collection_id:$.collection_id,revision:U},j=[],N={...E,kind:"project",id:$.project_id,title:$.project_name,locator:{kind:"canonical_uri",value:`knowledge:project:${$.project_id}`},metadata:{source_project_id:$.source_project_id,slug:$.project_slug,collection_count:1}};j.push({...N,key:`project:${$.project_id}`,digest:v_(N)});let A={...E,kind:"collection",id:$.collection_id,title:$.collection_name,locator:{kind:"external_uuid",value:$.collection_id},metadata:{slug:$.collection_slug,membership_rule:ND,member_count:I.length}};j.push({...A,key:`collection:${$.collection_id}`,digest:v_(A)});for(let S of I){let L={...E,kind:"item",id:S.id,revision:`v${S.version??1}`,title:S.title,locator:{kind:"canonical_uri",value:`knowledge:item:${encodeURIComponent(S.id)}`},metadata:{tags:[...S.tags??[]],archived:S.archived===!0,updated_at:S.updated_at}};j.push({...L,key:`item:${S.id}`,digest:v_(L)})}let O=new Map;for(let S of I)for(let L of S.tags??[]){let P=L.trim().toLowerCase();if(!P)continue;let z=O.get(P)??{label:L.trim(),itemIds:[]};z.itemIds.push(S.id),O.set(P,z)}for(let[S,L]of[...O.entries()].sort(([P],[z])=>P.localeCompare(z))){let P=NN(`${$.collection_id}\x00taxonomy\x00${S}`),z={...E,kind:"taxonomy",id:P,title:L.label,locator:{kind:"external_uuid",value:P},metadata:{tag:L.label,normalized_tag:S,item_count:L.itemIds.length,member_digest:v_([...L.itemIds].sort())}};j.push({...z,key:`taxonomy:${P}`,digest:v_(z)})}return j.sort((S,L)=>S.key.localeCompare(L.key)),{aggregate:$,resources:j}}async listProjectResources(_,$={}){let D=ZH($.limit),I=HH($.kinds),{aggregate:U,resources:E}=await this.buildResources(_),j=`r${Number(U.revision)}`,N=E.filter((G)=>I.includes(G.kind)),A=v_(N.map((G)=>({key:G.key,digest:G.digest}))),O="";if($.cursor){let G;try{G=JSON.parse(Buffer.from($.cursor,"base64url").toString("utf8"))}catch{throw new a("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","cursor is not a valid Knowledge project-resources cursor.")}if(G.version!==1||G.project_id!==U.project_id||G.collection_id!==U.collection_id||G.collection_revision!==j||G.population_digest!==A||gD(G.kinds)!==gD(I)||typeof G.after!=="string")throw new a("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed or the cursor belongs to a different project/kind selection; restart from the first page.");O=G.after}let S=O?N.filter((G)=>G.key>O):N,L=S.slice(0,D),P=S.length>L.length,z=P&&L.length>0?Buffer.from(JSON.stringify({version:1,project_id:U.project_id,collection_id:U.collection_id,collection_revision:j,population_digest:A,kinds:I,after:L.at(-1).key})).toString("base64url"):null;return{schema:"knowledge.project-resources.page.v1",authority:"knowledge",route:sR,...this.identity,project_id:U.project_id,source_project_id:U.source_project_id,collection_id:U.collection_id,collection_revision:j,population_digest:A,resource_kinds:I,resources:L,count:L.length,total:N.length,limit:D,cursor:$.cursor??null,next_cursor:z,has_more:P,complete:!P,truncated:!1}}async readProjectResource(_,$,D){let{resources:I}=await this.buildResources(_),U=I.find((E)=>E.kind===$&&E.id===D);if(!U)throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge project resource was not found by exact kind and id.");return U}async readAllProjectResources(_,$={}){let D=[],I=new Set,U=null,E=null;do{let j=await this.listProjectResources(_,{...$,cursor:U}),N={project_id:j.project_id,collection_id:j.collection_id,collection_revision:j.collection_revision,population_digest:j.population_digest,total:j.total,kinds:gD(j.resource_kinds)};if(E&&gD(E)!==gD(N))throw new a("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed while the complete population was being read.");E??=N;for(let A of j.resources){if(I.has(A.key))throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resource pagination returned a duplicate stable resource key.",{key:A.key});I.add(A.key),D.push(A)}if(j.has_more&&!j.next_cursor)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resource page claims more data without a continuation cursor.");U=j.next_cursor}while(U);if(!E||D.length!==E.total)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","complete project resource enumeration did not match the producer total.",{expected_total:E?.total??null,received:D.length});return D}}function ON(_){if(_.databasePath!==":memory:")u$(_.databasePath);let $=new BH(_.databasePath,{create:!0});return $.exec(bH()),new E9(new U9($),(D)=>_.itemStore.get(D),_.options)}class j9{options;fetchImpl;root;constructor(_){this.options=_;this.fetchImpl=_.fetch??P0,this.root=_.baseUrl.replace(/\/+$/,"")}async close(){}headers(_={}){let $=new Headers(this.options.headers);if($.set("accept","application/json"),this.options.apiKey)$.set("x-api-key",this.options.apiKey);for(let[D,I]of Object.entries(_))$.set(D,I);return $}async request(_,$={}){let D=await this.fetchImpl(`${this.root}${_}`,{...$,headers:this.headers($.body?{"content-type":"application/json"}:{})}),I=await D.json().catch(()=>({}));if(!D.ok)throw new a(typeof I.error==="string"?I.error:"KNOWLEDGE_PROJECT_LINKS_CONFLICT",typeof I.message==="string"?I.message:`Knowledge project-links HTTP ${D.status}`,I.details&&typeof I.details==="object"?I.details:{});return I}async capability(){return(await this.request("/v1/project-registration/capability")).capability}async registerCollection(_){return(await this.request("/v1/project-registration/create",{method:"POST",body:JSON.stringify(_)})).receipt}async readCollection(_){return(await this.request("/v1/project-registration/read-exact",{method:"POST",body:JSON.stringify({collection_id:_})})).record}async lookupReceipt(_){return(await this.request("/v1/project-registration/receipts/lookup",{method:"POST",body:JSON.stringify(_)})).receipt}async compensateRegistration(_){return(await this.request("/v1/project-registration/compensate",{method:"POST",body:JSON.stringify(_)})).receipt}async verifyRegistrationInverse(_){return(await this.request("/v1/project-registration/verify-inverse",{method:"POST",body:JSON.stringify(_)})).verification}async bindItem(_){return(await this.request("/v1/project-registration/items/bind",{method:"POST",body:JSON.stringify(_)})).receipt}async readItemBinding(_,$){return(await this.request("/v1/project-registration/items/read-exact",{method:"POST",body:JSON.stringify({collection_id:_,item_id:$})})).record}async compensateItemBinding(_){return(await this.request("/v1/project-registration/items/compensate",{method:"POST",body:JSON.stringify(_)})).receipt}async verifyItemBindingInverse(_){return(await this.request("/v1/project-registration/items/verify-inverse",{method:"POST",body:JSON.stringify(_)})).verification}async listProjectResources(_,$={}){let D=new URLSearchParams;if($.limit!==void 0)D.set("limit",String($.limit));if($.cursor)D.set("cursor",$.cursor);for(let U of $.kinds??[])D.append("kind",U);let I=D.size>0?`?${D.toString()}`:"";return this.request(`/v1/projects/${encodeURIComponent(_)}/resources${I}`)}async readProjectResource(_,$,D){return(await this.request(`/v1/projects/${encodeURIComponent(_)}/resources/${$}/${encodeURIComponent(D)}`)).resource}async readAllProjectResources(_,$={}){let D=[],I=new Set,U=null,E=null,j=null,N=null;do{let A=await this.listProjectResources(_,{...$,cursor:U});if(E??=A.total,j??=A.collection_revision,N??=A.population_digest,A.total!==E||A.collection_revision!==j||A.population_digest!==N)throw new a("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed while the complete HTTP population was being read.");for(let O of A.resources){if(I.has(O.key))throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resources HTTP pagination returned a duplicate stable key.");I.add(O.key),D.push(O)}if(A.has_more&&!A.next_cursor)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resources HTTP page claims more data without a cursor.");U=A.next_cursor}while(U);if(E===null||D.length!==E)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","complete HTTP resource enumeration did not match the producer total.");return D}}function N9(_){return new j9(_)}var E$={name:"@hasna/knowledge",version:"0.2.102",description:"Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions",type:"module",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./storage":{import:"./dist/storage.js",types:"./dist/storage.d.ts"},"./serve":{import:"./dist/serve.js",types:"./dist/serve.d.ts"}},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{knowledge:"bin/knowledge.js","knowledge-mcp":"bin/knowledge-mcp.js","knowledge-serve":"bin/knowledge-serve.js"},files:["bin","dist","scripts/apply-cloud-migrations.mjs","scripts/live-private-query.mjs","scripts/lib/remote-temp-dir.mjs","scripts/smoke-machine-sync-release.mjs","scripts/smoke-machines-adapter.mjs","scripts/smoke-open-files-installed-boundary.mjs","scripts/strip-generated-trailing-whitespace.mjs","scripts/verify-generated-artifacts.mjs","docs/architecture/ai-native-knowledge-base.md","docs/architecture/hosted-wrapper-responsibilities.md","docs/architecture/hybrid-semantic-search.md","docs/architecture/machine-sync-schema.md","docs/examples/app-project-wiki-standard.md","docs/examples/company-wiki-workflow.md","docs/migration/global-rules-provenance-import.md","docs/migration/json-to-sqlite.md","LICENSE","README.md"],scripts:{test:"bun test","test:cli":"bun test tests/cli.test.ts","test:package":"bun test tests/package-release.test.ts","release:pack:check":"node scripts/validate-public-package.mjs","smoke:machines-adapter":"bun scripts/smoke-machines-adapter.mjs","smoke:machine-sync-release":"bun scripts/smoke-machine-sync-release.mjs","smoke:open-files-installed-boundary":"bun scripts/smoke-open-files-installed-boundary.mjs","migrate:cloud":"bun scripts/apply-cloud-migrations.mjs","live:private-query":"bun scripts/live-private-query.mjs",serve:"bun src/serve-entry.ts","verify:generated":"bun scripts/verify-generated-artifacts.mjs","contracts:conformance":"contracts conformance fixtures",build:"rm -rf dist && bun build --target=bun --outfile=bin/knowledge.js --minify --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/cli.ts && bun build --target=bun --outfile=bin/knowledge-mcp.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @modelcontextprotocol/sdk --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/mcp.js && bun build --target=bun --outfile=bin/knowledge-serve.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/serve-entry.ts && bun build ./src/index.ts ./src/storage.ts ./src/serve.ts --outdir ./dist --target bun --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek && bun scripts/strip-generated-trailing-whitespace.mjs && bunx tsc -p tsconfig.build.json",prepublishOnly:"bun run contracts:conformance && contracts no-cloud-scan . && bun run build && node scripts/validate-public-package.mjs"},keywords:["knowledge","cli","agents","json","notes","local","store"],license:"Apache-2.0",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},repository:{type:"git",url:"git+https://github.com/hasna/knowledge.git"},bugs:{url:"https://github.com/hasna/knowledge/issues"},author:"Hasna Inc. ",engines:{bun:">=1.0",node:">=18"},dependencies:{"@ai-sdk/anthropic":"^3.0.81","@ai-sdk/deepseek":"^2.0.35","@ai-sdk/openai":"^3.0.68","@aws-sdk/client-s3":"^3.1063.0","@aws-sdk/credential-providers":"^3.1063.0","@hasna/events":"^0.1.3","@modelcontextprotocol/sdk":"^1.29.0","@types/json-schema":"^7.0.15",ai:"^6.0.197",commander:"^13.1.0",pg:"^8.16.3",zod:"^4.3.6"},devDependencies:{"@electric-sql/pglite":"^0.5.4","@hasna/contracts":"0.8.5","@types/bun":"^1.3.14","@types/pg":"^8.15.6"}};function wH(_){let $=K9(_);if(X_(g9($,"knowledge.db"))||X_(g9($,"config.json")))return g0($);return g0(j$(xN($)).home)}function hW(_){return`${vH()}:${G1("sha256").update(_.home).digest("hex").slice(0,12)}`}function dW(_){return`'${_.replace(/'/g,"'\\''")}'`}function rH(_){return["knowledge",..._].map(dW).join(" ")}function A9(_,$){return`cd ${dW(_)} && knowledge ${$.map(dW).join(" ")}`}function T9(_){return!_||_==="local"||_==="localhost"}function X1(_,$){return{source:_.source,adapter:_.adapter,project_root:$,project_root_source:_.project_root_source,workspace_root:_.workspace_root,workspace_root_source:_.workspace_root_source,open_files_root:_.open_files_root,open_files_root_source:_.open_files_root_source,trust_status:_.trust_status,auth_status:_.auth_status,current:_.current,primary:_.primary,diagnostics:_.diagnostics,repair_hints:_.repair_hints,evidence:_.evidence,cacheability:_.cacheability,warnings:_.warnings}}function cW(_){return{source:_.source,adapter:_.adapter,target:_.target,route:_.route,target_kind:_.targetKind,confidence:_.confidence,evidence:_.evidence,cacheability:_.cacheability}}function fH(_){try{let $=JSON.parse(_);return Array.isArray($)?$.filter((D)=>typeof D==="string"):[]}catch{return[]}}function R1(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function q_(_){return typeof _==="string"&&_.length>0?_:null}function xH(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function SN(_){return typeof _==="boolean"?_:null}function uH(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function F9(_,$,D){let I=R1(_),U=q_(I.observed_at)??q_($[`${D}_observed_at`]),E=q_(I.source_authority)??q_($[`${D}_source_authority`]);if(!U||!E)return null;return{observed_at:U,verified_at:q_(I.verified_at),expires_at:q_(I.expires_at)??q_($[`${D}_expires_at`]),ttl_ms:xH(I.ttl_ms),source_authority:E,confidence:q_(I.confidence)??(D==="route"?q_($.route_confidence):null),cacheable:SN(I.cacheable)??SN($[`${D}_cacheable`])??!1,stale:SN(I.stale)??SN($[`${D}_stale`])??!1,reasons:uH(I.reasons)}}function yH(_,$){return _.machine_id===$||_.hostname===$||_.ssh_target===$||_.tailscale_dns===$||fH(_.tailscale_ips_json).includes($)}function O9(_,$){return sg(_).find((D)=>yH(D,$))??null}function V9(_){return R1(i4(_.metadata_json).resolver_evidence)}function Y1(_){return R1(i4(_.capabilities_json).resolver)}function B9(_){let $=Y1(_),D=q_($.route_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;if(_.tailscale_dns&&_.ssh_target===_.tailscale_dns)return"tailscale";return _.ssh_target?"ssh":"unknown"}function hH(_){let $=Y1(_),D=q_($.route_target_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;return B9(_)}function cH(_){return q_(Y1(_).route_confidence)??"medium"}function S9(_,$,D){let I=V9(_),U=R1(I.route),E=Y1(_);return{target:_.ssh_target??_.tailscale_dns??_.hostname??_.machine_id,route:B9(_),targetKind:hH(_),confidence:cH(_),source:"registry",adapter:D.adapter,evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,route:U},cacheability:F9(U.cacheability,E,"route")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_route_fallback"])]}}function L9(_,$,D){if(!_.workspace_home)return null;let I=V9(_),U=R1(I.workspace),E=Y1(_);return{ok:!0,source:"registry",adapter:D.adapter,requested_machine_id:$,machine_id:_.machine_id,project_id:q_(U.project_id)??D.project_id,repo_name:q_(U.repo_name)??D.repo_name,project_root:_.workspace_home,project_root_source:q_(E.project_root_source)??"registry",workspace_root:q_(U.workspace_root),workspace_root_source:q_(E.workspace_root_source)??"registry",open_files_root:q_(U.open_files_root),open_files_root_source:q_(E.open_files_root_source)??"registry",trust_status:q_(E.trust_status)??"unknown",auth_status:q_(E.auth_status)??"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,workspace:U},cacheability:F9(U.cacheability,E,"workspace")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_workspace_fallback"])]}}function J9(_){if(!_)return null;let $=_.diagnostics.filter((I)=>I.severity!=="ok"),D=_.repair_hints[0];if(!$.length&&!_.warnings.length&&!D)return null;return[$.length?`workspace diagnostics: ${$.map((I)=>`${I.id}=${I.status}`).join(", ")}`:null,_.warnings.length?`warnings: ${_.warnings.join(", ")}`:null,D?`repair: ${D.shell_command}`:null].filter(Boolean).join("; ")}function LN(_){return{id:_.id,reason:_.reason,command:["knowledge",..._.args],shell_command:rH(_.args)}}function JN(_,$){let D=w(_);try{return Number(D.query($).get()?.count??0)}finally{D.close()}}function nH(_,$){let D=JN(_,"SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"),I=JN(_,"SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"),U=JN(_,"SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"),E=JN(_,["SELECT COUNT(*) AS count FROM sources","WHERE metadata_json LIKE '%raw_bytes%'","OR metadata_json LIKE '%raw_content%'","OR metadata_json LIKE '%content_base64%'","OR metadata_json LIKE '%source_bytes%'"].join(" ")),j=E===0;return{ok:j,source_of_truth:"open-files",configured_root:$?.open_files_root??null,configured_root_source:$?.open_files_root_source??null,source_refs:{open_files:D,metadata_mentions:I},extracted_text_artifacts:U,raw_source_bytes_owned_by:"open-files",raw_payload_sentinel_hits:E,message:j?`${D} open-files source ref(s); raw source bytes remain owned by open-files`:`${E} raw source payload metadata sentinel(s) found`}}var dH=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body","body_bytes"]);function mW(_,$=0){if($>8)return!1;if(!_||typeof _!=="object")return!1;if(Array.isArray(_))return _.some((D)=>mW(D,$+1));for(let[D,I]of Object.entries(_)){if(dH.has(D.toLowerCase()))return!0;if(mW(I,$+1))return!0}return!1}function i4(_){try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function W9(_,$=20,D=200){if(!Number.isFinite(_)||_<=0)return $;return Math.min(Math.floor(_),D)}function mH(_,$=220){let D=_??"";return D.length>$?`${D.slice(0,$)}...`:D}function G$(_,$=["metadata_json"]){return _.map((D)=>{let I={...D};for(let U of $){let E=I[U];if(typeof E==="string"){let j=U.endsWith("_json")?U.slice(0,-5):U;I[j]=i4(E),delete I[U]}}return I})}function PN(_){if(typeof _!=="string")return[];try{let $=JSON.parse(_);return Array.isArray($)?$:[]}catch{return[]}}function lW(_){if(typeof _!=="string")return{};return i4(_)}function lH(_){let $={..._};return $.source_refs=PN($.source_refs_json),$.evidence_refs=PN($.evidence_refs_json),$.requires_approval=$.requires_approval===1||$.requires_approval===!0,$.checks=lW($.checks_json),$.metadata=lW($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.checks_json,delete $.metadata_json,$}function iH(_){let $={..._};return $.source_refs=PN($.source_refs_json),$.evidence_refs=PN($.evidence_refs_json),$.metadata=lW($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.metadata_json,$}function e_(_,$,D=[]){return _.query($).all(...D)}function tH(_){if(!X_(_))return{exists:!1,read_error:null,items:[]};try{let $=JSON.parse(CH(_,"utf8"));if(!$||!Array.isArray($.items))return{exists:!0,read_error:"invalid_store_shape",items:[]};return{exists:!0,read_error:null,items:$.items}}catch($){return{exists:!0,read_error:$ instanceof Error?$.message:String($),items:[]}}}function P9(_){return{id:_.id,short_id:_.short_id??null,title:_.title,content_preview:mH(_.content),url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:_.archived===!0,created_at:_.created_at,updated_at:_.updated_at}}function z9(){return{schema_version:0,sources:0,source_revisions:0,chunks:0,wiki_pages:0,citations:0,indexes:0,runs:0,run_events:0,redaction_findings:0,audit_events:0,approval_gates:0,storage_objects:0,embeddings:0,vector_entries:0,reindex_queue:0,knowledge_machines:0,sync_snapshots:0,sync_changes:0,sync_conflicts:0,sync_table_clocks:0,sync_imports:0,promotion_candidates:0,durable_records:0}}function M9(_,$,D=!1){return{query:_,limit:$,offset:0,mode:{keyword:!0,catalog:!0,semantic:D},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:0,catalog_results:0,semantic_results:0,merged_results:0},warnings:["knowledge_db_missing"],results:[]}}function oH(_){return _.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function pH(_,$,D=!1){let I=M9(_,$,D);return{query:_,normalized_query:oH(_),created_at:new Date().toISOString(),mode:I.mode,warnings:I.warnings,search_counts:I.counts,results:[],citations:[],excerpts:[],graph:{citations:[],backlinks:[]},notes:{permissions:[],freshness:[]}}}function nW(_,$,D){let I=D??$.jsonStorePath;if(X_(I))return I;if(_==="global"){let U=CD();if(X_(U))return U}return I}function eH(_){let $=JSON.stringify(_);return Math.max(1,Math.ceil($.length/4))}function iW(_,$){let D=(_??"").normalize("NFKC").trim().replace(/\s+/g," ");if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-1)).trim()}...`}function X9(_,$,D){let I=u_(iW(_,D),$);return{text:I.text,redactions:I.findings.length}}function G9(_,$,D){let I=_.now??new Date,U=_.source??"search",E=_.purpose??(U==="loops"||U==="runs"?"proposal":"agent_context"),j=(_.query??_.topic??$.query).normalize("NFKC").trim().replace(/\s+/g," "),N=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),A=Math.max(500,Math.min(_.maxTokens??6000,1e5)),O=0,S=$.citations.slice(0,Math.max(N*2,N)).map((R,T)=>{let Y=X9(R.quote,D,T<3?220:140);O+=Y.redactions;let Q=R.source_ref??R.source_uri??R.artifact_path??R.artifact_uri??R.id;return{id:`cite_${G1("sha256").update(`${R.id}\x00${Q}`).digest("hex").slice(0,12)}`,kind:R.artifact_uri||R.artifact_path?"artifact":"source",ref:Q,source_ref:R.source_ref,source_uri:R.source_uri,artifact_uri:R.artifact_uri,artifact_path:R.artifact_path,run_id:null,run_event_id:null,revision:R.revision,hash:R.hash,chunk_id:R.chunk_id,offsets:{start:R.start_offset,end:R.end_offset},quote_preview:Y.text}}),L=new Map($.citations.map((R,T)=>[R.id,S[T]])),P=$.excerpts.slice(0,Math.max(N*2,N)).map((R)=>{let T=$.results.find((F)=>F.id===R.result_id),Y=R.citation_id?L.get(R.citation_id):void 0,Q=X9(R.text,D,520);return O+=Q.redactions,{id:`ev_${G1("sha256").update(`${R.kind}\x00${R.result_id}\x00${R.citation_id??""}`).digest("hex").slice(0,14)}`,kind:R.kind,title:iW(T?.title??Y?.ref??R.kind,100),text_preview:Q.text,score:Number(R.score.toFixed(6)),citation_ids:Y?[Y.id]:[],provenance:{source:U,record_ref:`${R.kind}:${R.result_id}`,created_at:$.created_at,updated_at:null,metadata_keys:[]}}}).sort((R,T)=>T.score-R.score||R.id.localeCompare(T.id)).slice(0,N),z=new Set(P.flatMap((R)=>R.citation_ids)),G=S.filter((R)=>z.has(R.id)),J=Array.from(new Set($.warnings)),W=`ctx_${G1("sha256").update([U,E,j,J.join(","),P.map((R)=>R.id).join(",")].join("\x00")).digest("hex").slice(0,20)}`,X={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:I.toISOString(),source:U,purpose:E,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:W,budgets:{max_tokens:A,estimated_tokens:0,max_items:N,items_included:P.length,items_available:$.excerpts.length,items_truncated:Math.max(0,$.excerpts.length-P.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:O,reminders:["This pack is read-only and performs no durable writes.","Legacy JSON note evidence is bounded and redacted before inclusion."]},citations:G,evidence:P,duplicate_candidates:[],outline:{title:j?`Knowledge context: ${iW(j,80)}`:"Knowledge context",bullets:P.length>0?P.slice(0,5).map((R)=>`${R.id}: ${R.title}`):["No matching bounded evidence was found."],evidence_ids:P.slice(0,8).map((R)=>R.id),duplicate_candidate_ids:[],next_actions:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]},warnings:J,message:`${P.length} bounded evidence item(s), estimated under ${A} token(s)`};return X.budgets.estimated_tokens=eH(X),X.budgets.token_budget_exceeded=X.budgets.estimated_tokens>A,X.message=`${X.evidence.length} bounded evidence item(s), estimated ${X.budgets.estimated_tokens}/${A} token(s)`,X}function aH(){return{schema_version:0,chunks:0,vector_entries:0,missing_embeddings:0,queued:{},stale_revisions:0}}function sH(){return{total_embeddings:0,total_vector_entries:0,indexes:[]}}function _k(_){return{ok:!0,scope:_.scope,workspace_home:_.workspaceHome,sqlite_schema_version:0,local_machine_id:_.localMachineId??null,machines:{total:0,rows:[]},snapshots:{total:0,latest:null},changes:{total:0,by_operation:[]},clocks:{total:0,rows:[]},imports:{total:0,latest:null},conflicts:{total:0,by_status:[],open:0},table_counts:{},message:"0 machine(s), 0 open sync conflict(s)"}}function R9(_){let $=_.now??new Date,D=_.source??"search",I=_.purpose??(D==="loops"||D==="runs"?"proposal":"agent_context"),U=(_.query??_.topic??"").normalize("NFKC").trim().replace(/\s+/g," "),E=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),j=Math.max(500,Math.min(_.maxTokens??6000,1e5)),N=`ctx_${G1("sha256").update(["empty",D,I,U,_.topic??"",_.since??""].join("\x00")).digest("hex").slice(0,20)}`;return{ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:D,purpose:I,query:U,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:N,budgets:{max_tokens:j,estimated_tokens:0,max_items:E,items_included:0,items_available:0,items_truncated:0,token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:0,reminders:["This pack is read-only and performs no durable writes.","No knowledge.db exists for this scope yet."]},citations:[],evidence:[],duplicate_candidates:[],outline:{title:U?`Context for ${U}`:"Knowledge context",bullets:[],evidence_ids:[],duplicate_candidate_ids:[],next_actions:[]},warnings:["knowledge_db_missing"],message:`0 bounded evidence item(s), estimated 0/${j} token(s)`}}function tW(_){let $=_.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g,"");return $?`${$}/`:null}function $k(_,$){let D=w(_);try{let I=D.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json + ORDER BY item_id ASC`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$.collection_id]),I=await Promise.all(D.map(async(S)=>{let L=await this.itemResolver(S.item_id);if(!L||L.id!==S.item_id)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","collection membership points at a missing Knowledge item; refusing a partial resource population.",{collection_id:$.collection_id,item_id:S.item_id});return L})),U=`r${Number($.revision)}`,E={project_id:$.project_id,source_project_id:$.source_project_id,collection_id:$.collection_id,revision:U},j=[],N={...E,kind:"project",id:$.project_id,title:$.project_name,locator:{kind:"canonical_uri",value:`knowledge:project:${$.project_id}`},metadata:{source_project_id:$.source_project_id,slug:$.project_slug,collection_count:1}};j.push({...N,key:`project:${$.project_id}`,digest:v_(N)});let A={...E,kind:"collection",id:$.collection_id,title:$.collection_name,locator:{kind:"external_uuid",value:$.collection_id},metadata:{slug:$.collection_slug,membership_rule:ND,member_count:I.length}};j.push({...A,key:`collection:${$.collection_id}`,digest:v_(A)});for(let S of I){let L={...E,kind:"item",id:S.id,revision:`v${S.version??1}`,title:S.title,locator:{kind:"canonical_uri",value:`knowledge:item:${encodeURIComponent(S.id)}`},metadata:{tags:[...S.tags??[]],archived:S.archived===!0,updated_at:S.updated_at}};j.push({...L,key:`item:${S.id}`,digest:v_(L)})}let O=new Map;for(let S of I)for(let L of S.tags??[]){let P=L.trim().toLowerCase();if(!P)continue;let z=O.get(P)??{label:L.trim(),itemIds:[]};z.itemIds.push(S.id),O.set(P,z)}for(let[S,L]of[...O.entries()].sort(([P],[z])=>P.localeCompare(z))){let P=NN(`${$.collection_id}\x00taxonomy\x00${S}`),z={...E,kind:"taxonomy",id:P,title:L.label,locator:{kind:"external_uuid",value:P},metadata:{tag:L.label,normalized_tag:S,item_count:L.itemIds.length,member_digest:v_([...L.itemIds].sort())}};j.push({...z,key:`taxonomy:${P}`,digest:v_(z)})}return j.sort((S,L)=>S.key.localeCompare(L.key)),{aggregate:$,resources:j}}async listProjectResources(_,$={}){let D=ZH($.limit),I=HH($.kinds),{aggregate:U,resources:E}=await this.buildResources(_),j=`r${Number(U.revision)}`,N=E.filter((G)=>I.includes(G.kind)),A=v_(N.map((G)=>({key:G.key,digest:G.digest}))),O="";if($.cursor){let G;try{G=JSON.parse(Buffer.from($.cursor,"base64url").toString("utf8"))}catch{throw new a("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","cursor is not a valid Knowledge project-resources cursor.")}if(G.version!==1||G.project_id!==U.project_id||G.collection_id!==U.collection_id||G.collection_revision!==j||G.population_digest!==A||gD(G.kinds)!==gD(I)||typeof G.after!=="string")throw new a("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed or the cursor belongs to a different project/kind selection; restart from the first page.");O=G.after}let S=O?N.filter((G)=>G.key>O):N,L=S.slice(0,D),P=S.length>L.length,z=P&&L.length>0?Buffer.from(JSON.stringify({version:1,project_id:U.project_id,collection_id:U.collection_id,collection_revision:j,population_digest:A,kinds:I,after:L.at(-1).key})).toString("base64url"):null;return{schema:"knowledge.project-resources.page.v1",authority:"knowledge",route:sR,...this.identity,project_id:U.project_id,source_project_id:U.source_project_id,collection_id:U.collection_id,collection_revision:j,population_digest:A,resource_kinds:I,resources:L,count:L.length,total:N.length,limit:D,cursor:$.cursor??null,next_cursor:z,has_more:P,complete:!P,truncated:!1}}async readProjectResource(_,$,D){let{resources:I}=await this.buildResources(_),U=I.find((E)=>E.kind===$&&E.id===D);if(!U)throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge project resource was not found by exact kind and id.");return U}async readAllProjectResources(_,$={}){let D=[],I=new Set,U=null,E=null;do{let j=await this.listProjectResources(_,{...$,cursor:U}),N={project_id:j.project_id,collection_id:j.collection_id,collection_revision:j.collection_revision,population_digest:j.population_digest,total:j.total,kinds:gD(j.resource_kinds)};if(E&&gD(E)!==gD(N))throw new a("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed while the complete population was being read.");E??=N;for(let A of j.resources){if(I.has(A.key))throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resource pagination returned a duplicate stable resource key.",{key:A.key});I.add(A.key),D.push(A)}if(j.has_more&&!j.next_cursor)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resource page claims more data without a continuation cursor.");U=j.next_cursor}while(U);if(!E||D.length!==E.total)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","complete project resource enumeration did not match the producer total.",{expected_total:E?.total??null,received:D.length});return D}}function ON(_){if(_.databasePath!==":memory:")u$(_.databasePath);let $=new BH(_.databasePath,{create:!0});return $.exec(bH()),new E9(new U9($),(D)=>_.itemStore.get(D),_.options)}class j9{options;fetchImpl;root;constructor(_){this.options=_;this.fetchImpl=_.fetch??P0,this.root=_.baseUrl.replace(/\/+$/,"")}async close(){}headers(_={}){let $=new Headers(this.options.headers);if($.set("accept","application/json"),this.options.apiKey)$.set("x-api-key",this.options.apiKey);for(let[D,I]of Object.entries(_))$.set(D,I);return $}async request(_,$={}){let D=await this.fetchImpl(`${this.root}${_}`,{...$,headers:this.headers($.body?{"content-type":"application/json"}:{})}),I=await D.json().catch(()=>({}));if(!D.ok)throw new a(typeof I.error==="string"?I.error:"KNOWLEDGE_PROJECT_LINKS_CONFLICT",typeof I.message==="string"?I.message:`Knowledge project-links HTTP ${D.status}`,I.details&&typeof I.details==="object"?I.details:{});return I}async capability(){return(await this.request("/v1/project-registration/capability")).capability}async registerCollection(_){return(await this.request("/v1/project-registration/create",{method:"POST",body:JSON.stringify(_)})).receipt}async readCollection(_){return(await this.request("/v1/project-registration/read-exact",{method:"POST",body:JSON.stringify({collection_id:_})})).record}async lookupReceipt(_){return(await this.request("/v1/project-registration/receipts/lookup",{method:"POST",body:JSON.stringify(_)})).receipt}async compensateRegistration(_){return(await this.request("/v1/project-registration/compensate",{method:"POST",body:JSON.stringify(_)})).receipt}async verifyRegistrationInverse(_){return(await this.request("/v1/project-registration/verify-inverse",{method:"POST",body:JSON.stringify(_)})).verification}async bindItem(_){return(await this.request("/v1/project-registration/items/bind",{method:"POST",body:JSON.stringify(_)})).receipt}async readItemBinding(_,$){return(await this.request("/v1/project-registration/items/read-exact",{method:"POST",body:JSON.stringify({collection_id:_,item_id:$})})).record}async compensateItemBinding(_){return(await this.request("/v1/project-registration/items/compensate",{method:"POST",body:JSON.stringify(_)})).receipt}async verifyItemBindingInverse(_){return(await this.request("/v1/project-registration/items/verify-inverse",{method:"POST",body:JSON.stringify(_)})).verification}async listProjectResources(_,$={}){let D=new URLSearchParams;if($.limit!==void 0)D.set("limit",String($.limit));if($.cursor)D.set("cursor",$.cursor);for(let U of $.kinds??[])D.append("kind",U);let I=D.size>0?`?${D.toString()}`:"";return this.request(`/v1/projects/${encodeURIComponent(_)}/resources${I}`)}async readProjectResource(_,$,D){return(await this.request(`/v1/projects/${encodeURIComponent(_)}/resources/${$}/${encodeURIComponent(D)}`)).resource}async readAllProjectResources(_,$={}){let D=[],I=new Set,U=null,E=null,j=null,N=null;do{let A=await this.listProjectResources(_,{...$,cursor:U});if(E??=A.total,j??=A.collection_revision,N??=A.population_digest,A.total!==E||A.collection_revision!==j||A.population_digest!==N)throw new a("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed while the complete HTTP population was being read.");for(let O of A.resources){if(I.has(O.key))throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resources HTTP pagination returned a duplicate stable key.");I.add(O.key),D.push(O)}if(A.has_more&&!A.next_cursor)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resources HTTP page claims more data without a cursor.");U=A.next_cursor}while(U);if(E===null||D.length!==E)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","complete HTTP resource enumeration did not match the producer total.");return D}}function N9(_){return new j9(_)}var E$={name:"@hasna/knowledge",version:"0.2.103",description:"Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions",type:"module",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./storage":{import:"./dist/storage.js",types:"./dist/storage.d.ts"},"./serve":{import:"./dist/serve.js",types:"./dist/serve.d.ts"}},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{knowledge:"bin/knowledge.js","knowledge-mcp":"bin/knowledge-mcp.js","knowledge-serve":"bin/knowledge-serve.js"},files:["bin","dist","scripts/apply-cloud-migrations.mjs","scripts/live-private-query.mjs","scripts/lib/remote-temp-dir.mjs","scripts/smoke-machine-sync-release.mjs","scripts/smoke-machines-adapter.mjs","scripts/smoke-open-files-installed-boundary.mjs","scripts/strip-generated-trailing-whitespace.mjs","scripts/verify-generated-artifacts.mjs","docs/architecture/ai-native-knowledge-base.md","docs/architecture/hosted-wrapper-responsibilities.md","docs/architecture/hybrid-semantic-search.md","docs/architecture/machine-sync-schema.md","docs/examples/app-project-wiki-standard.md","docs/examples/company-wiki-workflow.md","docs/migration/global-rules-provenance-import.md","docs/migration/json-to-sqlite.md","LICENSE","README.md"],scripts:{test:"bun test","test:cli":"bun test tests/cli.test.ts","test:package":"bun test tests/package-release.test.ts","release:pack:check":"node scripts/validate-public-package.mjs","smoke:machines-adapter":"bun scripts/smoke-machines-adapter.mjs","smoke:machine-sync-release":"bun scripts/smoke-machine-sync-release.mjs","smoke:open-files-installed-boundary":"bun scripts/smoke-open-files-installed-boundary.mjs","migrate:cloud":"bun scripts/apply-cloud-migrations.mjs","live:private-query":"bun scripts/live-private-query.mjs",serve:"bun src/serve-entry.ts","verify:generated":"bun scripts/verify-generated-artifacts.mjs","contracts:conformance":"contracts conformance fixtures",build:"rm -rf dist && bun build --target=bun --outfile=bin/knowledge.js --minify --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/cli.ts && bun build --target=bun --outfile=bin/knowledge-mcp.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @modelcontextprotocol/sdk --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/mcp.js && bun build --target=bun --outfile=bin/knowledge-serve.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/serve-entry.ts && bun build ./src/index.ts ./src/storage.ts ./src/serve.ts --outdir ./dist --target bun --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek && bun scripts/strip-generated-trailing-whitespace.mjs && bunx tsc -p tsconfig.build.json",prepublishOnly:"bun run contracts:conformance && contracts no-cloud-scan . && bun run build && node scripts/validate-public-package.mjs"},keywords:["knowledge","cli","agents","json","notes","local","store"],license:"Apache-2.0",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},repository:{type:"git",url:"git+https://github.com/hasna/knowledge.git"},bugs:{url:"https://github.com/hasna/knowledge/issues"},author:"Hasna Inc. ",engines:{bun:">=1.0",node:">=18"},dependencies:{"@ai-sdk/anthropic":"^3.0.81","@ai-sdk/deepseek":"^2.0.35","@ai-sdk/openai":"^3.0.68","@aws-sdk/client-s3":"^3.1063.0","@aws-sdk/credential-providers":"^3.1063.0","@hasna/events":"^0.1.3","@modelcontextprotocol/sdk":"^1.29.0","@types/json-schema":"^7.0.15",ai:"^6.0.197",commander:"^13.1.0",pg:"^8.16.3",zod:"^4.3.6"},devDependencies:{"@electric-sql/pglite":"^0.5.4","@hasna/contracts":"0.8.5","@types/bun":"^1.3.14","@types/pg":"^8.15.6"}};function wH(_){let $=K9(_);if(X_(g9($,"knowledge.db"))||X_(g9($,"config.json")))return g0($);return g0(j$(xN($)).home)}function hW(_){return`${vH()}:${G1("sha256").update(_.home).digest("hex").slice(0,12)}`}function dW(_){return`'${_.replace(/'/g,"'\\''")}'`}function rH(_){return["knowledge",..._].map(dW).join(" ")}function A9(_,$){return`cd ${dW(_)} && knowledge ${$.map(dW).join(" ")}`}function T9(_){return!_||_==="local"||_==="localhost"}function X1(_,$){return{source:_.source,adapter:_.adapter,project_root:$,project_root_source:_.project_root_source,workspace_root:_.workspace_root,workspace_root_source:_.workspace_root_source,open_files_root:_.open_files_root,open_files_root_source:_.open_files_root_source,trust_status:_.trust_status,auth_status:_.auth_status,current:_.current,primary:_.primary,diagnostics:_.diagnostics,repair_hints:_.repair_hints,evidence:_.evidence,cacheability:_.cacheability,warnings:_.warnings}}function cW(_){return{source:_.source,adapter:_.adapter,target:_.target,route:_.route,target_kind:_.targetKind,confidence:_.confidence,evidence:_.evidence,cacheability:_.cacheability}}function fH(_){try{let $=JSON.parse(_);return Array.isArray($)?$.filter((D)=>typeof D==="string"):[]}catch{return[]}}function R1(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function q_(_){return typeof _==="string"&&_.length>0?_:null}function xH(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function SN(_){return typeof _==="boolean"?_:null}function uH(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function F9(_,$,D){let I=R1(_),U=q_(I.observed_at)??q_($[`${D}_observed_at`]),E=q_(I.source_authority)??q_($[`${D}_source_authority`]);if(!U||!E)return null;return{observed_at:U,verified_at:q_(I.verified_at),expires_at:q_(I.expires_at)??q_($[`${D}_expires_at`]),ttl_ms:xH(I.ttl_ms),source_authority:E,confidence:q_(I.confidence)??(D==="route"?q_($.route_confidence):null),cacheable:SN(I.cacheable)??SN($[`${D}_cacheable`])??!1,stale:SN(I.stale)??SN($[`${D}_stale`])??!1,reasons:uH(I.reasons)}}function yH(_,$){return _.machine_id===$||_.hostname===$||_.ssh_target===$||_.tailscale_dns===$||fH(_.tailscale_ips_json).includes($)}function O9(_,$){return sg(_).find((D)=>yH(D,$))??null}function V9(_){return R1(i4(_.metadata_json).resolver_evidence)}function Y1(_){return R1(i4(_.capabilities_json).resolver)}function B9(_){let $=Y1(_),D=q_($.route_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;if(_.tailscale_dns&&_.ssh_target===_.tailscale_dns)return"tailscale";return _.ssh_target?"ssh":"unknown"}function hH(_){let $=Y1(_),D=q_($.route_target_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;return B9(_)}function cH(_){return q_(Y1(_).route_confidence)??"medium"}function S9(_,$,D){let I=V9(_),U=R1(I.route),E=Y1(_);return{target:_.ssh_target??_.tailscale_dns??_.hostname??_.machine_id,route:B9(_),targetKind:hH(_),confidence:cH(_),source:"registry",adapter:D.adapter,evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,route:U},cacheability:F9(U.cacheability,E,"route")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_route_fallback"])]}}function L9(_,$,D){if(!_.workspace_home)return null;let I=V9(_),U=R1(I.workspace),E=Y1(_);return{ok:!0,source:"registry",adapter:D.adapter,requested_machine_id:$,machine_id:_.machine_id,project_id:q_(U.project_id)??D.project_id,repo_name:q_(U.repo_name)??D.repo_name,project_root:_.workspace_home,project_root_source:q_(E.project_root_source)??"registry",workspace_root:q_(U.workspace_root),workspace_root_source:q_(E.workspace_root_source)??"registry",open_files_root:q_(U.open_files_root),open_files_root_source:q_(E.open_files_root_source)??"registry",trust_status:q_(E.trust_status)??"unknown",auth_status:q_(E.auth_status)??"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,workspace:U},cacheability:F9(U.cacheability,E,"workspace")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_workspace_fallback"])]}}function J9(_){if(!_)return null;let $=_.diagnostics.filter((I)=>I.severity!=="ok"),D=_.repair_hints[0];if(!$.length&&!_.warnings.length&&!D)return null;return[$.length?`workspace diagnostics: ${$.map((I)=>`${I.id}=${I.status}`).join(", ")}`:null,_.warnings.length?`warnings: ${_.warnings.join(", ")}`:null,D?`repair: ${D.shell_command}`:null].filter(Boolean).join("; ")}function LN(_){return{id:_.id,reason:_.reason,command:["knowledge",..._.args],shell_command:rH(_.args)}}function JN(_,$){let D=w(_);try{return Number(D.query($).get()?.count??0)}finally{D.close()}}function nH(_,$){let D=JN(_,"SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"),I=JN(_,"SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"),U=JN(_,"SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"),E=JN(_,["SELECT COUNT(*) AS count FROM sources","WHERE metadata_json LIKE '%raw_bytes%'","OR metadata_json LIKE '%raw_content%'","OR metadata_json LIKE '%content_base64%'","OR metadata_json LIKE '%source_bytes%'"].join(" ")),j=E===0;return{ok:j,source_of_truth:"open-files",configured_root:$?.open_files_root??null,configured_root_source:$?.open_files_root_source??null,source_refs:{open_files:D,metadata_mentions:I},extracted_text_artifacts:U,raw_source_bytes_owned_by:"open-files",raw_payload_sentinel_hits:E,message:j?`${D} open-files source ref(s); raw source bytes remain owned by open-files`:`${E} raw source payload metadata sentinel(s) found`}}var dH=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body","body_bytes"]);function mW(_,$=0){if($>8)return!1;if(!_||typeof _!=="object")return!1;if(Array.isArray(_))return _.some((D)=>mW(D,$+1));for(let[D,I]of Object.entries(_)){if(dH.has(D.toLowerCase()))return!0;if(mW(I,$+1))return!0}return!1}function i4(_){try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function W9(_,$=20,D=200){if(!Number.isFinite(_)||_<=0)return $;return Math.min(Math.floor(_),D)}function mH(_,$=220){let D=_??"";return D.length>$?`${D.slice(0,$)}...`:D}function G$(_,$=["metadata_json"]){return _.map((D)=>{let I={...D};for(let U of $){let E=I[U];if(typeof E==="string"){let j=U.endsWith("_json")?U.slice(0,-5):U;I[j]=i4(E),delete I[U]}}return I})}function PN(_){if(typeof _!=="string")return[];try{let $=JSON.parse(_);return Array.isArray($)?$:[]}catch{return[]}}function lW(_){if(typeof _!=="string")return{};return i4(_)}function lH(_){let $={..._};return $.source_refs=PN($.source_refs_json),$.evidence_refs=PN($.evidence_refs_json),$.requires_approval=$.requires_approval===1||$.requires_approval===!0,$.checks=lW($.checks_json),$.metadata=lW($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.checks_json,delete $.metadata_json,$}function iH(_){let $={..._};return $.source_refs=PN($.source_refs_json),$.evidence_refs=PN($.evidence_refs_json),$.metadata=lW($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.metadata_json,$}function e_(_,$,D=[]){return _.query($).all(...D)}function tH(_){if(!X_(_))return{exists:!1,read_error:null,items:[]};try{let $=JSON.parse(CH(_,"utf8"));if(!$||!Array.isArray($.items))return{exists:!0,read_error:"invalid_store_shape",items:[]};return{exists:!0,read_error:null,items:$.items}}catch($){return{exists:!0,read_error:$ instanceof Error?$.message:String($),items:[]}}}function P9(_){return{id:_.id,short_id:_.short_id??null,title:_.title,content_preview:mH(_.content),url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:_.archived===!0,created_at:_.created_at,updated_at:_.updated_at}}function z9(){return{schema_version:0,sources:0,source_revisions:0,chunks:0,wiki_pages:0,citations:0,indexes:0,runs:0,run_events:0,redaction_findings:0,audit_events:0,approval_gates:0,storage_objects:0,embeddings:0,vector_entries:0,reindex_queue:0,knowledge_machines:0,sync_snapshots:0,sync_changes:0,sync_conflicts:0,sync_table_clocks:0,sync_imports:0,promotion_candidates:0,durable_records:0}}function M9(_,$,D=!1){return{query:_,limit:$,offset:0,mode:{keyword:!0,catalog:!0,semantic:D},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:0,catalog_results:0,semantic_results:0,merged_results:0},warnings:["knowledge_db_missing"],results:[]}}function oH(_){return _.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function pH(_,$,D=!1){let I=M9(_,$,D);return{query:_,normalized_query:oH(_),created_at:new Date().toISOString(),mode:I.mode,warnings:I.warnings,search_counts:I.counts,results:[],citations:[],excerpts:[],graph:{citations:[],backlinks:[]},notes:{permissions:[],freshness:[]}}}function nW(_,$,D){let I=D??$.jsonStorePath;if(X_(I))return I;if(_==="global"){let U=CD();if(X_(U))return U}return I}function eH(_){let $=JSON.stringify(_);return Math.max(1,Math.ceil($.length/4))}function iW(_,$){let D=(_??"").normalize("NFKC").trim().replace(/\s+/g," ");if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-1)).trim()}...`}function X9(_,$,D){let I=u_(iW(_,D),$);return{text:I.text,redactions:I.findings.length}}function G9(_,$,D){let I=_.now??new Date,U=_.source??"search",E=_.purpose??(U==="loops"||U==="runs"?"proposal":"agent_context"),j=(_.query??_.topic??$.query).normalize("NFKC").trim().replace(/\s+/g," "),N=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),A=Math.max(500,Math.min(_.maxTokens??6000,1e5)),O=0,S=$.citations.slice(0,Math.max(N*2,N)).map((R,T)=>{let Y=X9(R.quote,D,T<3?220:140);O+=Y.redactions;let Q=R.source_ref??R.source_uri??R.artifact_path??R.artifact_uri??R.id;return{id:`cite_${G1("sha256").update(`${R.id}\x00${Q}`).digest("hex").slice(0,12)}`,kind:R.artifact_uri||R.artifact_path?"artifact":"source",ref:Q,source_ref:R.source_ref,source_uri:R.source_uri,artifact_uri:R.artifact_uri,artifact_path:R.artifact_path,run_id:null,run_event_id:null,revision:R.revision,hash:R.hash,chunk_id:R.chunk_id,offsets:{start:R.start_offset,end:R.end_offset},quote_preview:Y.text}}),L=new Map($.citations.map((R,T)=>[R.id,S[T]])),P=$.excerpts.slice(0,Math.max(N*2,N)).map((R)=>{let T=$.results.find((F)=>F.id===R.result_id),Y=R.citation_id?L.get(R.citation_id):void 0,Q=X9(R.text,D,520);return O+=Q.redactions,{id:`ev_${G1("sha256").update(`${R.kind}\x00${R.result_id}\x00${R.citation_id??""}`).digest("hex").slice(0,14)}`,kind:R.kind,title:iW(T?.title??Y?.ref??R.kind,100),text_preview:Q.text,score:Number(R.score.toFixed(6)),citation_ids:Y?[Y.id]:[],provenance:{source:U,record_ref:`${R.kind}:${R.result_id}`,created_at:$.created_at,updated_at:null,metadata_keys:[]}}}).sort((R,T)=>T.score-R.score||R.id.localeCompare(T.id)).slice(0,N),z=new Set(P.flatMap((R)=>R.citation_ids)),G=S.filter((R)=>z.has(R.id)),J=Array.from(new Set($.warnings)),W=`ctx_${G1("sha256").update([U,E,j,J.join(","),P.map((R)=>R.id).join(",")].join("\x00")).digest("hex").slice(0,20)}`,X={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:I.toISOString(),source:U,purpose:E,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:W,budgets:{max_tokens:A,estimated_tokens:0,max_items:N,items_included:P.length,items_available:$.excerpts.length,items_truncated:Math.max(0,$.excerpts.length-P.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:O,reminders:["This pack is read-only and performs no durable writes.","Legacy JSON note evidence is bounded and redacted before inclusion."]},citations:G,evidence:P,duplicate_candidates:[],outline:{title:j?`Knowledge context: ${iW(j,80)}`:"Knowledge context",bullets:P.length>0?P.slice(0,5).map((R)=>`${R.id}: ${R.title}`):["No matching bounded evidence was found."],evidence_ids:P.slice(0,8).map((R)=>R.id),duplicate_candidate_ids:[],next_actions:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]},warnings:J,message:`${P.length} bounded evidence item(s), estimated under ${A} token(s)`};return X.budgets.estimated_tokens=eH(X),X.budgets.token_budget_exceeded=X.budgets.estimated_tokens>A,X.message=`${X.evidence.length} bounded evidence item(s), estimated ${X.budgets.estimated_tokens}/${A} token(s)`,X}function aH(){return{schema_version:0,chunks:0,vector_entries:0,missing_embeddings:0,queued:{},stale_revisions:0}}function sH(){return{total_embeddings:0,total_vector_entries:0,indexes:[]}}function _k(_){return{ok:!0,scope:_.scope,workspace_home:_.workspaceHome,sqlite_schema_version:0,local_machine_id:_.localMachineId??null,machines:{total:0,rows:[]},snapshots:{total:0,latest:null},changes:{total:0,by_operation:[]},clocks:{total:0,rows:[]},imports:{total:0,latest:null},conflicts:{total:0,by_status:[],open:0},table_counts:{},message:"0 machine(s), 0 open sync conflict(s)"}}function R9(_){let $=_.now??new Date,D=_.source??"search",I=_.purpose??(D==="loops"||D==="runs"?"proposal":"agent_context"),U=(_.query??_.topic??"").normalize("NFKC").trim().replace(/\s+/g," "),E=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),j=Math.max(500,Math.min(_.maxTokens??6000,1e5)),N=`ctx_${G1("sha256").update(["empty",D,I,U,_.topic??"",_.since??""].join("\x00")).digest("hex").slice(0,20)}`;return{ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:D,purpose:I,query:U,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:N,budgets:{max_tokens:j,estimated_tokens:0,max_items:E,items_included:0,items_available:0,items_truncated:0,token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:0,reminders:["This pack is read-only and performs no durable writes.","No knowledge.db exists for this scope yet."]},citations:[],evidence:[],duplicate_candidates:[],outline:{title:U?`Context for ${U}`:"Knowledge context",bullets:[],evidence_ids:[],duplicate_candidate_ids:[],next_actions:[]},warnings:["knowledge_db_missing"],message:`0 bounded evidence item(s), estimated 0/${j} token(s)`}}function tW(_){let $=_.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g,"");return $?`${$}/`:null}function $k(_,$){let D=w(_);try{let I=D.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json FROM storage_objects ORDER BY artifact_uri ASC`).all(),U=new Map,E=0,j=0,N=0,A=0,O=0,S=0,L=0,P=0,z=0,G=0,J=0,W=0,X=new Map,R=[],T=[],Y=[],Q=[],F=$.artifact_store.uri_prefix,q=tW($);for(let E_ of I){if(U.set(E_.kind,(U.get(E_.kind)??0)+1),E_.hash?.startsWith("sha256:"))E+=1;if(typeof E_.size_bytes==="number"&&E_.size_bytes>=0)j+=1,N+=E_.size_bytes;if(E_.artifact_uri.startsWith(F))A+=1;else if(R.length<5)R.push(E_.artifact_uri);let C_=i4(E_.metadata_json);if(mW(C_))L+=1;let N0=typeof C_.key==="string"?C_.key:null;if(!N0)O+=1;else if(q&&N0.startsWith(q)){if(S+=1,T.length<5)T.push(N0)}let ZP=typeof C_.artifact_modified_at==="string"?C_.artifact_modified_at:null;if(ZP)if(Number.isNaN(Date.parse(ZP))){if(z+=1,Y.length<5)Y.push(E_.artifact_uri)}else P+=1;let qD=C_.provenance&&typeof C_.provenance==="object"&&!Array.isArray(C_.provenance)?C_.provenance:null;if(qD){G+=1;let vN=typeof qD.artifact_key==="string"?qD.artifact_key:null,HP=typeof qD.generated_from==="string"?qD.generated_from:"unknown";if(X.set(HP,(X.get(HP)??0)+1),vN){if(J+=1,N0&&vN!==N0){if(W+=1,Q.length<5)Q.push(`${E_.artifact_uri}:provenance.artifact_key=${vN}:key=${N0}`)}}else if(Q.length<5)Q.push(`${E_.artifact_uri}:missing_provenance_artifact_key`)}else if(Q.length<5)Q.push(`${E_.artifact_uri}:missing_provenance`)}let Z=I.length-E,f=I.length-j,l=I.length-P-z,U_=I.length-G,j_=G-J,_$=I.length-A,G_=[Z>0?`artifact_manifest_missing_hash:${Z}`:null,f>0?`artifact_manifest_missing_size:${f}`:null,O>0?`artifact_manifest_missing_key:${O}`:null,_$>0?`artifact_manifest_uri_prefix_mismatch:${_$}`:null,S>0?`artifact_manifest_s3_key_contains_storage_prefix:${S}`:null,z>0?`artifact_manifest_invalid_modified_at:${z}`:null,U_>0?`artifact_manifest_missing_provenance:${U_}`:null,j_>0?`artifact_manifest_missing_provenance_artifact_key:${j_}`:null,W>0?`artifact_manifest_provenance_key_mismatch:${W}`:null,L>0?`artifact_manifest_raw_payload_sentinels:${L}`:null].filter((E_)=>Boolean(E_)),K$=G_.length===0;return{ok:K$,read_only:!0,storage_type:$.storage_type,artifact_uri_prefix:F,s3:$.artifact_store.s3,artifacts:{total:I.length,by_kind:[...U.entries()].map(([E_,C_])=>({kind:E_,count:C_})).sort((E_,C_)=>E_.kind.localeCompare(C_.kind)),with_hash:E,missing_hash:Z,with_size:j,missing_size:f,total_size_bytes:N},modified_time:{with_modified_at:P,missing_modified_at:l,invalid_modified_at:z,examples:Y},provenance:{with_provenance:G,missing_provenance:U_,with_artifact_key:J,missing_artifact_key:j_,artifact_key_mismatches:W,generated_from:[...X.entries()].map(([E_,C_])=>({value:E_,count:C_})).sort((E_,C_)=>E_.value.localeCompare(C_.value)),examples:Q},uri_prefix:{matching:A,mismatched:_$,examples:R},keys:{with_key:I.length-O,missing_key:O,prefixed_with_storage_prefix:S,prefixed_examples:T},sync_manifest:{copied_by_sync:!0,generated_artifacts_only:!0,includes_raw_source_bytes:!1,hash_algorithm:"sha256",portable_keys:S===0&&O===0,tracks_modified_time:P>0&&z===0,preserves_provenance:U_===0&&j_===0&&W===0},raw_payload_sentinel_hits:L,warnings:G_,message:K$?`${I.length} generated artifact manifest row(s) ready for ${$.storage_type} sync`:`Generated artifact manifest needs attention: ${G_.join(", ")}`}}finally{D.close()}}function Dk(_,$){let D=tW($);if(!D)return[];let I=w(_);try{let U=I.query(`SELECT id, artifact_uri, kind, hash, size_bytes, metadata_json FROM storage_objects diff --git a/dist/index.js b/dist/index.js index dce37fa..fe723a6 100644 --- a/dist/index.js +++ b/dist/index.js @@ -37468,7 +37468,7 @@ function migrateLegacyKnowledgeWorkspace(options) { // package.json var package_default = { name: "@hasna/knowledge", - version: "0.2.102", + version: "0.2.103", description: "Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions", type: "module", exports: { diff --git a/package.json b/package.json index 819880f..153d263 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@hasna/knowledge", - "version": "0.2.102", + "version": "0.2.103", "description": "Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions", "type": "module", "exports": {