@tangle-network/agent-knowledge 19.0.1 → 19.1.0

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.
@@ -166,6 +166,38 @@ async function listRegularFilesWithinRoot(root, relativeDirectory) {
166
166
  const normalized = normalizeRelativePath(relativeDirectory);
167
167
  return withSafeDirectory(root, normalized, false, (directory) => listRegularFilesFromOpenDirectory(directory, normalized));
168
168
  }
169
+ /** Metadata-only inventory, retaining the same directory anchoring and special-file refusal as reads. */
170
+ async function listRegularFileMetadataWithinRoot(root, relativeDirectory) {
171
+ const normalized = normalizeRelativePath(relativeDirectory);
172
+ const walk = async (directory, relative) => {
173
+ const out = [];
174
+ const entries = await readdir(directory, { withFileTypes: true });
175
+ for (const entry of entries.filter((entry) => entry.isDirectory())) out.push(...await withSafeDirectory(directory, entry.name, false, (child) => walk(child, `${relative}/${entry.name}`)));
176
+ const files = entries.filter((entry) => !entry.isDirectory());
177
+ for (let start = 0; start < files.length; start += 64) {
178
+ const batch = await Promise.all(files.slice(start, start + 64).map(async (entry) => {
179
+ const path = `${relative}/${entry.name}`;
180
+ if (!entry.isFile()) throw new Error(`knowledge tree contains an unsupported filesystem entry: ${path}`);
181
+ const stat = await lstat(resolve(directory, entry.name), { bigint: true });
182
+ if (!stat.isFile()) throw new Error(`knowledge path is not a regular file: ${path}`);
183
+ return [{
184
+ path,
185
+ bytes: Number(stat.size),
186
+ generation: [
187
+ stat.dev,
188
+ stat.ino,
189
+ stat.size,
190
+ stat.mtimeNs,
191
+ stat.ctimeNs
192
+ ].join(":")
193
+ }];
194
+ }));
195
+ out.push(...batch.flat());
196
+ }
197
+ return out.sort((left, right) => left.path.localeCompare(right.path));
198
+ };
199
+ return withSafeDirectory(root, normalized, false, (directory) => walk(directory, normalized));
200
+ }
169
201
  function isMissingFile(error) {
170
202
  return error?.code === "ENOENT";
171
203
  }
@@ -3862,6 +3894,18 @@ function originatedPages(pages, origin = "here") {
3862
3894
  }));
3863
3895
  }
3864
3896
  const RUN_LINEAGE_BASENAME = "lineage.json";
3897
+ const toolViewLoaders = /* @__PURE__ */ new WeakMap();
3898
+ const toolViews = /* @__PURE__ */ new WeakSet();
3899
+ /** Only factory-owned immutable views are safe to reuse by object identity. */
3900
+ function isKnowledgeToolChain(chain) {
3901
+ return toolViews.has(chain);
3902
+ }
3903
+ const MAX_CACHED_ROOTS = 8;
3904
+ const MAX_CACHED_SOURCE_BYTES = 67108864;
3905
+ /** Internal tool path. Custom stores retain their existing loadChain contract. */
3906
+ function loadKnowledgeToolChain(stores, runId) {
3907
+ return toolViewLoaders.get(stores)?.(runId) ?? stores.loadChain(runId);
3908
+ }
3865
3909
  function createRunScopedStores(options) {
3866
3910
  if (!options || typeof options !== "object") throw new TypeError("createRunScopedStores options are required");
3867
3911
  if (typeof options.root !== "string" || options.root.trim().length === 0) throw new TypeError("createRunScopedStores root must be a non-empty string");
@@ -3889,7 +3933,7 @@ function createRunScopedStores(options) {
3889
3933
  current = parent;
3890
3934
  }
3891
3935
  };
3892
- return {
3936
+ const stores = {
3893
3937
  storePath(runId) {
3894
3938
  assertRunId(runId);
3895
3939
  return storePath(runId);
@@ -3933,6 +3977,85 @@ function createRunScopedStores(options) {
3933
3977
  return out;
3934
3978
  }
3935
3979
  };
3980
+ const roots = /* @__PURE__ */ new Map();
3981
+ let cachedBytes = 0;
3982
+ let current;
3983
+ const readRoot = async (root) => {
3984
+ const loaded = await withKnowledgeRead(root, async () => {
3985
+ let files;
3986
+ try {
3987
+ files = await listRegularFileMetadataWithinRoot(root, pagesDirectory);
3988
+ } catch (error) {
3989
+ if (!isMissingFile(error)) throw error;
3990
+ files = [];
3991
+ }
3992
+ const generation = JSON.stringify(files.map((file) => [file.path, file.generation]));
3993
+ const previous = roots.get(root);
3994
+ if (previous?.generation === generation) return previous;
3995
+ const pages = await loadKnowledgePages(root, { pagesDirectory });
3996
+ return {
3997
+ generation,
3998
+ bytes: files.reduce((sum, file) => sum + file.bytes, 0),
3999
+ pages: freezeView(pages)
4000
+ };
4001
+ });
4002
+ const existing = roots.get(root);
4003
+ if (existing?.generation === loaded.generation) return existing;
4004
+ if (existing) {
4005
+ roots.delete(root);
4006
+ cachedBytes -= existing.bytes;
4007
+ }
4008
+ if (loaded.bytes <= MAX_CACHED_SOURCE_BYTES) {
4009
+ while (roots.size >= MAX_CACHED_ROOTS || cachedBytes + loaded.bytes > MAX_CACHED_SOURCE_BYTES) {
4010
+ const oldest = roots.keys().next().value;
4011
+ if (oldest === void 0) break;
4012
+ cachedBytes -= roots.get(oldest).bytes;
4013
+ roots.delete(oldest);
4014
+ current = void 0;
4015
+ }
4016
+ roots.set(root, loaded);
4017
+ cachedBytes += loaded.bytes;
4018
+ }
4019
+ return loaded;
4020
+ };
4021
+ toolViewLoaders.set(stores, async (runId) => {
4022
+ assertRunId(runId);
4023
+ const scopes = [{
4024
+ root: storePath(runId),
4025
+ origin: "here"
4026
+ }];
4027
+ for (const ancestor of await resolveLineage(runId)) scopes.push({
4028
+ root: storePath(ancestor),
4029
+ origin: `inherited:${ancestor}`
4030
+ });
4031
+ if (options.sharedRoot) scopes.push({
4032
+ root: options.sharedRoot,
4033
+ origin: "shared"
4034
+ });
4035
+ const identities = scopes.map(({ root, origin }) => JSON.stringify([root, origin]));
4036
+ const parts = [];
4037
+ for (const scope of scopes) parts.push(await readRoot(scope.root));
4038
+ if (current && identities.length === current.identities.length && identities.every((id, i) => id === current.identities[i] && parts[i] === current.parts[i])) return current.chain;
4039
+ const chain = Object.freeze(parts.flatMap((part, i) => part.pages.map((page) => Object.freeze({
4040
+ page,
4041
+ origin: scopes[i].origin
4042
+ }))));
4043
+ toolViews.add(chain);
4044
+ current = parts.length <= MAX_CACHED_ROOTS && parts.reduce((sum, part) => sum + part.bytes, 0) <= MAX_CACHED_SOURCE_BYTES ? {
4045
+ identities,
4046
+ parts,
4047
+ chain
4048
+ } : void 0;
4049
+ return chain;
4050
+ });
4051
+ return stores;
4052
+ }
4053
+ function freezeView(value) {
4054
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
4055
+ for (const child of Object.values(value)) freezeView(child);
4056
+ Object.freeze(value);
4057
+ }
4058
+ return value;
3936
4059
  }
3937
4060
  /** File-backed authority used when the product has no separate run manifest. */
3938
4061
  function createFileRunLineageAuthority(runStorePath) {
@@ -4316,6 +4439,6 @@ function explainKnowledgeTarget(index, target) {
4316
4439
  };
4317
4440
  }
4318
4441
  //#endregion
4319
- export { FileSystemKbStore as $, assertResearchClaimEvidenceIntegrity as $t, visibilityIndexOf as A, normalizePagesDirectory as An, WIKILINK_REGEX as At, gradeClaims as B, renameDurable as Bn, KnowledgePageSchema as Bt, nonEmpty as C, assertKnowledgeMutationPath as Cn, initKnowledgeBase as Ct, validateOrigin as D, prepareKnowledgeFileTransaction as Dn, layoutFor as Dt, validateKnowledgePage as E, knowledgeFileTransactionPlanHash as En, knowledgePageFromMarkdown as Et, CHECKABLE_RUNG_THRESHOLD as F, listRegularFilesWithinRoot as Fn, KnowledgeEventSchema as Ft, writeKnowledgeIndex as G, writeFileDurableWithinRoot as Gn, ResearchClaimLedgerSchema as Gt, verdictFor as H, withSafeDescendant as Hn, KnowledgeRelationNodeSchema as Ht, DEADLINE_EXIT_CODE as I, readRegularFileNoFollow as In, KnowledgeGraphEdgeSchema as It, loadSourceRegistry as J, mediaTypeFor$1 as Jn, SourceAnchorSchema as Jt, addSourcePath as K, writeJsonDurable as Kn, ResearchClaimRecordSchema as Kt, UncheckableClaimError as L, readRegularFileWithinRoot as Ln, KnowledgeGraphNodeSchema as Lt, normalizePageText as M, canonicalRelativeWithinRoot as Mn, normalizeLinkTarget as Mt, validateKnowledgeIndex as N, isKernelAnchoredPath as Nn, DeepQuestionSchema as Nt, verifyKnowledgeVisibilitySnapshot as O, rollbackKnowledgeFileTransaction as On, loadKnowledgePages as Ot, lintKnowledgeIndex as P, isMissingFile as Pn, KnowledgeBaseCandidateSchema as Pt, ClaimLedgerMigrationRequiredError as Q, assertDeepQuestionIntegrity as Qt, assertGradeableEvidence as R, relativeWithinRoot as Rn, KnowledgeIndexSchema as Rt, knowledgeVisibilityArtifactRef as S, applyKnowledgeFileTransaction as Sn, SCAFFOLD_PAGE_BASENAMES as St, normalizeVisibilityRef as T, finishKnowledgeFileTransaction as Tn, isScaffoldPath as Tt, verifyGradeableEvidence as U, withSafeDirectory as Un, KnowledgeRelationSchema as Ut, gradeFor as V, syncDirectory as Vn, KnowledgeRelationGraphSchema as Vt, buildKnowledgeIndex as W, writeFileDurable as Wn, ResearchClaimEvidenceSchema as Wt, sourceRegistryPath as X, KNOWLEDGE_EVENT_TYPES as Xt, snapshotSourceTextInput as Y, textSourceAdapter as Yn, SourceRecordSchema as Yt, writeSourceRegistry as Z, ClaimLedgerGoalConflictError as Zt, createKnowledgeVisibilitySnapshot as _, isKnowledgeMutationHeld as _n, parseKnowledgeCitationReference as _t, applyKnowledgeWriteBlocksFile as a, deepQuestionId as an, assertClaimLedgerId as at, encodeKnowledgeVisibilitySnapshot as b, withKnowledgeMutation as bn, resolveRunScopedCitation as bt, KnowledgeDuplicateIntakeError as c, materializeRegisteredClaimEvidence as cn, KnowledgeCitationAuditError as ct, createFileRunLineageAuthority as d, normalizeClaimText as dn, assertKnowledgeCitationAudit as dt, assertResearchClaimLedgerIntegrity as en, KB_CLAIM_LEDGER_DIR as et, createRunScopedStores as f, researchSourceVersionKey as fn, assertKnowledgeCitationsResolved as ft, assertSchemaVersion as g, inspectPendingKnowledgeMutation as gn, formatKnowledgeCitationReference as gt, KNOWLEDGE_USE_RECEIPT_SCHEMA_VERSION as h, acquireDurableFileLock as hn, auditKnowledgeCitations as ht, applyKnowledgeWriteBlocks as i, claimSourceHost as in, MemoryKbStore as it, detectNearDuplicatePages as j, canonicalPathsEqual as jn, extractWikilinks as jt, visibilityIdentity as k, DEFAULT_PAGES_DIRECTORY as kn, writeJson as kt, assertKnowledgeWriteIntake as l, mergeClaimLedgers as ln, KnowledgeCitationResolutionError as lt, KNOWLEDGE_RECEIPT_DIGEST_ALGORITHM as m, parseFrontmatter as mn, auditCurrentRunCitations as mt, inspectKnowledgeIndex as n, claimEvidenceId as nn, KB_INDEX_PATH as nt, isSafeKnowledgePath as o, emptyClaimLedger as on, buildKnowledgeGraph as ot, originatedPages as p, formatFrontmatter as pn, assertRunScopedCitationsResolved as pt, addSourceText as q, writeJsonDurableWithinRoot as qn, ResearchSourceVersionSchema as qt, stringMetadata as r, claimId as rn, KB_STORE_DIR as rt, parseKnowledgeWriteBlocks as s, linkClaimContradictions as sn, knowledgePageRelations as st, explainKnowledgeTarget as t, assertTrackedClaimIntegrity as tn, KB_EVENTS_PATH as tt, RUN_LINEAGE_BASENAME as u, mergeTrackedClaims as un, assertCurrentRunCitationsResolved as ut, decodeKnowledgeVisibilitySnapshot as v, recoverPendingKnowledgeMutation as vn, resolveKnowledgeCitation as vt, normalizeVisibilityArtifact as w, commitKnowledgeFileMutations as wn, isKnowledgePagePath as wt, knowledgePageDigest as x, withKnowledgeRead as xn, resolveRunScopedCitations as xt, digest as y, runInKnowledgeMutationScope as yn, resolveKnowledgeCitations as yt, claimCheckKey as z, removeDurable as zn, KnowledgePageInvalidationSchema as zt };
4442
+ export { writeSourceRegistry as $, ClaimLedgerGoalConflictError as $t, verifyKnowledgeVisibilitySnapshot as A, rollbackKnowledgeFileTransaction as An, loadKnowledgePages as At, assertGradeableEvidence as B, relativeWithinRoot as Bn, KnowledgeIndexSchema as Bt, knowledgePageDigest as C, withKnowledgeRead as Cn, resolveRunScopedCitations as Ct, normalizeVisibilityRef as D, finishKnowledgeFileTransaction as Dn, isScaffoldPath as Dt, normalizeVisibilityArtifact as E, commitKnowledgeFileMutations as En, isKnowledgePagePath as Et, validateKnowledgeIndex as F, isKernelAnchoredPath as Fn, DeepQuestionSchema as Ft, verifyGradeableEvidence as G, withSafeDirectory as Gn, KnowledgeRelationSchema as Gt, gradeClaims as H, renameDurable as Hn, KnowledgePageSchema as Ht, lintKnowledgeIndex as I, isMissingFile as In, KnowledgeBaseCandidateSchema as It, addSourcePath as J, writeJsonDurable as Jn, ResearchClaimRecordSchema as Jt, buildKnowledgeIndex as K, writeFileDurable as Kn, ResearchClaimEvidenceSchema as Kt, CHECKABLE_RUNG_THRESHOLD as L, listRegularFilesWithinRoot as Ln, KnowledgeEventSchema as Lt, visibilityIndexOf as M, normalizePagesDirectory as Mn, WIKILINK_REGEX as Mt, detectNearDuplicatePages as N, canonicalPathsEqual as Nn, extractWikilinks as Nt, validateKnowledgePage as O, knowledgeFileTransactionPlanHash as On, knowledgePageFromMarkdown as Ot, normalizePageText as P, canonicalRelativeWithinRoot as Pn, normalizeLinkTarget as Pt, sourceRegistryPath as Q, KNOWLEDGE_EVENT_TYPES as Qt, DEADLINE_EXIT_CODE as R, readRegularFileNoFollow as Rn, KnowledgeGraphEdgeSchema as Rt, encodeKnowledgeVisibilitySnapshot as S, withKnowledgeMutation as Sn, resolveRunScopedCitation as St, nonEmpty as T, assertKnowledgeMutationPath as Tn, initKnowledgeBase as Tt, gradeFor as U, syncDirectory as Un, KnowledgeRelationGraphSchema as Ut, claimCheckKey as V, removeDurable as Vn, KnowledgePageInvalidationSchema as Vt, verdictFor as W, withSafeDescendant as Wn, KnowledgeRelationNodeSchema as Wt, loadSourceRegistry as X, mediaTypeFor$1 as Xn, SourceAnchorSchema as Xt, addSourceText as Y, writeJsonDurableWithinRoot as Yn, ResearchSourceVersionSchema as Yt, snapshotSourceTextInput as Z, textSourceAdapter as Zn, SourceRecordSchema as Zt, KNOWLEDGE_USE_RECEIPT_SCHEMA_VERSION as _, acquireDurableFileLock as _n, auditKnowledgeCitations as _t, applyKnowledgeWriteBlocksFile as a, claimId as an, KB_STORE_DIR as at, decodeKnowledgeVisibilitySnapshot as b, recoverPendingKnowledgeMutation as bn, resolveKnowledgeCitation as bt, KnowledgeDuplicateIntakeError as c, emptyClaimLedger as cn, buildKnowledgeGraph as ct, createFileRunLineageAuthority as d, mergeClaimLedgers as dn, KnowledgeCitationResolutionError as dt, assertDeepQuestionIntegrity as en, ClaimLedgerMigrationRequiredError as et, createRunScopedStores as f, mergeTrackedClaims as fn, assertCurrentRunCitationsResolved as ft, KNOWLEDGE_RECEIPT_DIGEST_ALGORITHM as g, parseFrontmatter as gn, auditCurrentRunCitations as gt, originatedPages as h, formatFrontmatter as hn, assertRunScopedCitationsResolved as ht, applyKnowledgeWriteBlocks as i, claimEvidenceId as in, KB_INDEX_PATH as it, visibilityIdentity as j, DEFAULT_PAGES_DIRECTORY as jn, writeJson as jt, validateOrigin as k, prepareKnowledgeFileTransaction as kn, layoutFor as kt, assertKnowledgeWriteIntake as l, linkClaimContradictions as ln, knowledgePageRelations as lt, loadKnowledgeToolChain as m, researchSourceVersionKey as mn, assertKnowledgeCitationsResolved as mt, inspectKnowledgeIndex as n, assertResearchClaimLedgerIntegrity as nn, KB_CLAIM_LEDGER_DIR as nt, isSafeKnowledgePath as o, claimSourceHost as on, MemoryKbStore as ot, isKnowledgeToolChain as p, normalizeClaimText as pn, assertKnowledgeCitationAudit as pt, writeKnowledgeIndex as q, writeFileDurableWithinRoot as qn, ResearchClaimLedgerSchema as qt, stringMetadata as r, assertTrackedClaimIntegrity as rn, KB_EVENTS_PATH as rt, parseKnowledgeWriteBlocks as s, deepQuestionId as sn, assertClaimLedgerId as st, explainKnowledgeTarget as t, assertResearchClaimEvidenceIntegrity as tn, FileSystemKbStore as tt, RUN_LINEAGE_BASENAME as u, materializeRegisteredClaimEvidence as un, KnowledgeCitationAuditError as ut, assertSchemaVersion as v, inspectPendingKnowledgeMutation as vn, formatKnowledgeCitationReference as vt, knowledgeVisibilityArtifactRef as w, applyKnowledgeFileTransaction as wn, SCAFFOLD_PAGE_BASENAMES as wt, digest as x, runInKnowledgeMutationScope as xn, resolveKnowledgeCitations as xt, createKnowledgeVisibilitySnapshot as y, isKnowledgeMutationHeld as yn, parseKnowledgeCitationReference as yt, UncheckableClaimError as z, readRegularFileWithinRoot as zn, KnowledgeGraphNodeSchema as zt };
4320
4443
 
4321
- //# sourceMappingURL=inspect-C6YK7af7.js.map
4444
+ //# sourceMappingURL=inspect-CwIvMcno.js.map