@tangle-network/agent-knowledge 15.0.3 → 17.0.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.
@@ -400,6 +400,7 @@ const transactionSchema = z.object({
400
400
  recoveryOwner: z.string().min(1).max(256).optional(),
401
401
  pagesDirectory: pagesDirectorySchema.optional(),
402
402
  researchState: z.boolean().optional(),
403
+ retainHistory: z.boolean().optional(),
403
404
  createdAt: z.string().min(1),
404
405
  entries: z.array(transactionEntrySchema).min(1)
405
406
  }).strict();
@@ -457,6 +458,7 @@ async function prepareKnowledgeFileTransaction(input) {
457
458
  ...input.recoveryOwner ? { recoveryOwner: input.recoveryOwner } : {},
458
459
  ...pagesDirectory === void 0 ? {} : { pagesDirectory },
459
460
  ...input.researchState === void 0 ? {} : { researchState: input.researchState },
461
+ ...input.retainHistory === void 0 ? {} : { retainHistory: input.retainHistory },
460
462
  createdAt: (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
461
463
  entries: changed.map((item) => item.entry)
462
464
  });
@@ -492,6 +494,7 @@ async function commitKnowledgeFileMutations(input) {
492
494
  purpose: input.purpose,
493
495
  mutations: input.mutations,
494
496
  ...input.researchState === void 0 ? {} : { researchState: input.researchState },
497
+ ...input.retainHistory === void 0 ? {} : { retainHistory: input.retainHistory },
495
498
  ...input.pagesDirectory === void 0 ? {} : { pagesDirectory: input.pagesDirectory },
496
499
  now: input.now
497
500
  });
@@ -580,6 +583,10 @@ async function finishKnowledgeFileTransaction(input) {
580
583
  assertTransactionEntries(transaction);
581
584
  await withTransactionRoot(input.root, input.transactionRoot, false, async (transactionRoot) => {
582
585
  const activeName = activeTransactionDirectoryName(transaction.transactionId);
586
+ if (transaction.retainHistory === true && !(await activeTransactionDirectoryNames(transactionRoot)).includes(activeName) && await hasRetainedTransaction(input.root, transaction)) {
587
+ await syncDirectory(transactionRoot);
588
+ return;
589
+ }
583
590
  await withTransactionDirectory(input.root, input.transactionRoot, transaction, async (transactionDir) => {
584
591
  await assertActiveTransaction(transactionDir, transaction);
585
592
  input.assertOwned?.();
@@ -592,13 +599,34 @@ async function finishKnowledgeFileTransaction(input) {
592
599
  await assertKnowledgeFileTransactionTerminal(input.root, transaction, currentDirection);
593
600
  });
594
601
  });
595
- await rm(join(transactionRoot, activeName), {
602
+ if (transaction.retainHistory === true) await withSafeDirectory(input.root, ".agent-knowledge/history", true, async (historyRoot) => {
603
+ await renameDurable(join(transactionRoot, activeName), join(historyRoot, transaction.transactionId));
604
+ });
605
+ else await rm(join(transactionRoot, activeName), {
596
606
  recursive: true,
597
607
  force: false
598
608
  });
599
609
  await syncDirectory(transactionRoot);
600
610
  });
601
611
  }
612
+ async function hasRetainedTransaction(root, transaction) {
613
+ try {
614
+ return await withSafeDirectory(root, `.agent-knowledge/history/${transaction.transactionId}`, false, async (historyDir) => {
615
+ await assertActiveTransaction(historyDir, transaction);
616
+ await readTransactionDirection(historyDir, transaction);
617
+ for (const entry of transaction.entries) for (const side of ["before", "after"]) {
618
+ const expected = side === "before" ? entry.beforeHash : entry.afterHash;
619
+ if (expected === null) continue;
620
+ if (hashBytes((await readRegularFileNoFollow(snapshotPath(historyDir, side, entry.index))).bytes) !== expected) throw new Error(`retained knowledge snapshot changed: ${entry.path}`);
621
+ }
622
+ await syncDirectory(historyDir);
623
+ return true;
624
+ });
625
+ } catch (error) {
626
+ if (isMissingFile(error)) return false;
627
+ throw error;
628
+ }
629
+ }
602
630
  async function rollbackKnowledgeFileTransaction(input) {
603
631
  await withTransactionDirectory(input.root, input.transactionRoot, input.transaction, async (transactionDir) => {
604
632
  const transaction = transactionSchema.parse(input.transaction);
@@ -3594,12 +3622,12 @@ function originatedPages(pages, origin = "here") {
3594
3622
  }));
3595
3623
  }
3596
3624
  const RUN_LINEAGE_BASENAME = "lineage.json";
3597
- /** Ancestry beyond this bound is invalid durable state. */
3598
- const MAX_LINEAGE_HOPS = 64;
3599
3625
  function createRunScopedStores(options) {
3600
3626
  if (!options || typeof options !== "object") throw new TypeError("createRunScopedStores options are required");
3601
3627
  if (typeof options.root !== "string" || options.root.trim().length === 0) throw new TypeError("createRunScopedStores root must be a non-empty string");
3602
3628
  if (options.runStorePath !== void 0 && typeof options.runStorePath !== "function") throw new TypeError("createRunScopedStores runStorePath must be a function when present");
3629
+ const maxAncestors = options.maxAncestors;
3630
+ if (maxAncestors !== void 0 && (!Number.isSafeInteger(maxAncestors) || maxAncestors < 0)) throw new TypeError("createRunScopedStores maxAncestors must be a non-negative safe integer");
3603
3631
  if (options.lineageAuthority !== void 0) validateLineageAuthority(options.lineageAuthority);
3604
3632
  const pagesDirectory = normalizePagesDirectory(options.pagesDirectory);
3605
3633
  const storePath = options.runStorePath ?? ((runId) => join(options.root, runId, "knowledge-base"));
@@ -3610,16 +3638,16 @@ function createRunScopedStores(options) {
3610
3638
  const chain = [];
3611
3639
  const seen = /* @__PURE__ */ new Set([runId]);
3612
3640
  let current = runId;
3613
- for (let hop = 0; hop <= MAX_LINEAGE_HOPS; hop += 1) {
3641
+ for (;;) {
3614
3642
  const parent = await authority.parentOf(current);
3615
3643
  if (parent === null) return chain;
3616
3644
  assertRunId(parent, `parent of '${current}'`);
3617
3645
  if (seen.has(parent)) throw new Error(`run lineage cycle: ${parent} is its own ancestor (via ${runId})`);
3646
+ if (maxAncestors !== void 0 && chain.length >= maxAncestors) throw new Error(`run lineage for '${runId}' exceeds caller maxAncestors=${maxAncestors}`);
3618
3647
  seen.add(parent);
3619
3648
  chain.push(parent);
3620
3649
  current = parent;
3621
3650
  }
3622
- throw new Error(`run lineage for '${runId}' exceeds ${MAX_LINEAGE_HOPS} ancestors`);
3623
3651
  };
3624
3652
  return {
3625
3653
  storePath(runId) {
@@ -3930,6 +3958,7 @@ async function applyKnowledgeWriteBlocks(root, proposalText, options = {}) {
3930
3958
  purpose,
3931
3959
  mutations,
3932
3960
  pagesDirectory,
3961
+ retainHistory: options.retainHistory,
3933
3962
  assertOwned: lock.assertOwned
3934
3963
  });
3935
3964
  }
@@ -4022,4 +4051,4 @@ function explainKnowledgeTarget(index, target) {
4022
4051
  //#endregion
4023
4052
  export { formatKnowledgeCitationReference as $, inspectPendingKnowledgeMutation as $t, addSourceText as A, writeJsonDurableWithinRoot as An, ResearchSourceVersionSchema as At, KB_STORE_DIR as B, claimId as Bt, gradeClaims as C, renameDurable as Cn, KnowledgePageSchema as Ct, buildKnowledgeIndex as D, writeFileDurable as Dn, ResearchClaimEvidenceSchema as Dt, verifyGradeableEvidence as E, withSafeDirectory as En, KnowledgeRelationSchema as Et, ClaimLedgerMigrationRequiredError as F, assertDeepQuestionIntegrity as Ft, KnowledgeCitationAuditError as G, materializeRegisteredClaimEvidence as Gt, assertClaimLedgerId as H, deepQuestionId as Ht, FileSystemKbStore as I, assertResearchClaimEvidenceIntegrity as It, assertKnowledgeCitationAudit as J, normalizeClaimText as Jt, KnowledgeCitationResolutionError as K, mergeClaimLedgers as Kt, KB_CLAIM_LEDGER_DIR as L, assertResearchClaimLedgerIntegrity as Lt, snapshotSourceTextInput as M, textSourceAdapter as Mn, SourceRecordSchema as Mt, sourceRegistryPath as N, KNOWLEDGE_EVENT_TYPES as Nt, writeKnowledgeIndex as O, writeFileDurableWithinRoot as On, ResearchClaimLedgerSchema as Ot, writeSourceRegistry as P, ClaimLedgerGoalConflictError as Pt, auditKnowledgeCitations as Q, acquireDurableFileLock as Qt, KB_EVENTS_PATH as R, assertTrackedClaimIntegrity as Rt, claimCheckKey as S, removeDurable as Sn, KnowledgePageInvalidationSchema as St, verdictFor as T, withSafeDescendant as Tn, KnowledgeRelationNodeSchema as Tt, buildKnowledgeGraph as U, emptyClaimLedger as Ut, MemoryKbStore as V, claimSourceHost as Vt, knowledgePageRelations as W, linkClaimContradictions as Wt, assertRunScopedCitationsResolved as X, formatFrontmatter as Xt, assertKnowledgeCitationsResolved as Y, researchSourceVersionKey as Yt, auditCurrentRunCitations as Z, parseFrontmatter as Zt, lintKnowledgeIndex as _, isMissingFile as _n, KnowledgeBaseCandidateSchema as _t, applyKnowledgeWriteBlocksFile as a, applyKnowledgeFileTransaction as an, SCAFFOLD_PAGE_BASENAMES as at, UncheckableClaimError as b, readRegularFileWithinRoot as bn, KnowledgeGraphNodeSchema as bt, KnowledgeDuplicateIntakeError as c, finishKnowledgeFileTransaction as cn, isScaffoldPath as ct, createFileRunLineageAuthority as d, rollbackKnowledgeFileTransaction as dn, loadKnowledgePages as dt, isKnowledgeMutationHeld as en, parseKnowledgeCitationReference as et, createRunScopedStores as f, DEFAULT_PAGES_DIRECTORY as fn, writeJson as ft, validateKnowledgeIndex as g, isKernelAnchoredPath as gn, DeepQuestionSchema as gt, normalizePageText as h, canonicalRelativeWithinRoot as hn, normalizeLinkTarget as ht, applyKnowledgeWriteBlocks as i, withKnowledgeRead as in, resolveRunScopedCitations as it, loadSourceRegistry as j, mediaTypeFor$1 as jn, SourceAnchorSchema as jt, addSourcePath as k, writeJsonDurable as kn, ResearchClaimRecordSchema as kt, assertKnowledgeWriteIntake as l, knowledgeFileTransactionPlanHash as ln, knowledgePageFromMarkdown as lt, detectNearDuplicatePages as m, canonicalPathsEqual as mn, extractWikilinks as mt, inspectKnowledgeIndex as n, runInKnowledgeMutationScope as nn, resolveKnowledgeCitations as nt, isSafeKnowledgePath as o, assertKnowledgeMutationPath as on, initKnowledgeBase as ot, originatedPages as p, normalizePagesDirectory as pn, WIKILINK_REGEX as pt, assertCurrentRunCitationsResolved as q, mergeTrackedClaims as qt, stringMetadata as r, withKnowledgeMutation as rn, resolveRunScopedCitation as rt, parseKnowledgeWriteBlocks as s, commitKnowledgeFileMutations as sn, isKnowledgePagePath as st, explainKnowledgeTarget as t, recoverPendingKnowledgeMutation as tn, resolveKnowledgeCitation as tt, RUN_LINEAGE_BASENAME as u, prepareKnowledgeFileTransaction as un, layoutFor as ut, CHECKABLE_RUNG_THRESHOLD as v, listRegularFilesWithinRoot as vn, KnowledgeEventSchema as vt, gradeFor as w, syncDirectory as wn, KnowledgeRelationGraphSchema as wt, assertGradeableEvidence as x, relativeWithinRoot as xn, KnowledgeIndexSchema as xt, DEADLINE_EXIT_CODE as y, readRegularFileNoFollow as yn, KnowledgeGraphEdgeSchema as yt, KB_INDEX_PATH as z, claimEvidenceId as zt };
4024
4053
 
4025
- //# sourceMappingURL=inspect-DMZXOQYl.js.map
4054
+ //# sourceMappingURL=inspect-Dn7xCZLn.js.map