dotmem 0.1.7 → 0.1.8

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.
package/global.js CHANGED
@@ -21,18 +21,6 @@ var __export = (target, all) => {
21
21
  __defProp(target, name, { get: all[name], enumerable: true });
22
22
  };
23
23
 
24
- // core/suppress-idb-warning.ts
25
- var orig;
26
- var init_suppress_idb_warning = __esm({
27
- "core/suppress-idb-warning.ts"() {
28
- orig = console.warn.bind(console);
29
- console.warn = (...args) => {
30
- if (typeof args[0] === "string" && args[0].includes("IndexedDB is not available")) return;
31
- orig(...args);
32
- };
33
- }
34
- });
35
-
36
24
  // core/env.ts
37
25
  var DEV;
38
26
  var init_env = __esm({
@@ -108,6 +96,56 @@ var init_storage_paths = __esm({
108
96
  }
109
97
  });
110
98
 
99
+ // core/knowledge/text-encoding.ts
100
+ function detectBom(bytes) {
101
+ if (bytes.length >= 3 && bytes[0] === BOM_UTF8 && bytes[1] === 187 && bytes[2] === 191) {
102
+ return "utf-8";
103
+ }
104
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16LE_FIRST && bytes[1] === BOM_UTF16LE_SECOND) {
105
+ return "utf-16le";
106
+ }
107
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16BE_FIRST && bytes[1] === BOM_UTF16BE_SECOND) {
108
+ return "utf-16be";
109
+ }
110
+ return null;
111
+ }
112
+ function decodeText(bytes, options = {}) {
113
+ const bom = detectBom(bytes);
114
+ if (bom === "utf-16le" || bom === "utf-16be") {
115
+ throw new UnsupportedEncodingError(
116
+ `UTF-16 encoded content detected in ${options.source ?? "unknown"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`
117
+ );
118
+ }
119
+ let content = bytes;
120
+ if (bom === "utf-8") {
121
+ content = bytes.subarray(3);
122
+ }
123
+ return strictDecoder.decode(content);
124
+ }
125
+ var strictDecoder, UnsupportedEncodingError, BOM_UTF8, BOM_UTF16LE_FIRST, BOM_UTF16LE_SECOND, BOM_UTF16BE_FIRST, BOM_UTF16BE_SECOND;
126
+ var init_text_encoding = __esm({
127
+ "core/knowledge/text-encoding.ts"() {
128
+ new TextEncoder();
129
+ strictDecoder = new TextDecoder("utf-8", { fatal: true });
130
+ UnsupportedEncodingError = class extends Error {
131
+ static {
132
+ __name(this, "UnsupportedEncodingError");
133
+ }
134
+ constructor(message) {
135
+ super(message);
136
+ this.name = "UnsupportedEncodingError";
137
+ }
138
+ };
139
+ BOM_UTF8 = 239;
140
+ BOM_UTF16LE_FIRST = 255;
141
+ BOM_UTF16LE_SECOND = 254;
142
+ BOM_UTF16BE_FIRST = 254;
143
+ BOM_UTF16BE_SECOND = 255;
144
+ __name(detectBom, "detectBom");
145
+ __name(decodeText, "decodeText");
146
+ }
147
+ });
148
+
111
149
  // core/knowledge/storage-settings.ts
112
150
  var DOTMEM_STORAGE_SETTINGS_FILE_NAME, SETTINGS_MODES, projectRoot, findProjectSettingsFile, discoverProjectSettingsFilePath, resolveUserSettingsFilePath, invalidSettings, parseSettings, resolveSettingsEntry, readTextFile, readStorageSettings;
113
151
  var init_storage_settings = __esm({
@@ -239,15 +277,19 @@ function readDotMemStorageLocator() {
239
277
  const locatorFile = resolveLocatorFilePath(anchor);
240
278
  let raw;
241
279
  try {
242
- raw = fs2.readFileSync(locatorFile, "utf8");
280
+ raw = decodeText(fs2.readFileSync(locatorFile), { source: locatorFile });
243
281
  } catch (error) {
282
+ if (error instanceof UnsupportedEncodingError) {
283
+ throw new DotMemStorageLocationError(
284
+ `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} is UTF-16 encoded; dotmem persists UTF-8 only. Re-save the locator as UTF-8 without BOM.`
285
+ );
286
+ }
244
287
  const code = error?.code;
245
288
  if (code === "ENOENT") return null;
246
289
  throw new DotMemStorageLocationError(
247
290
  `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} cannot be read (${describeAccessFailure(error)}). No alternative location was selected automatically.`
248
291
  );
249
292
  }
250
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
251
293
  let parsed;
252
294
  try {
253
295
  parsed = JSON.parse(raw);
@@ -339,6 +381,7 @@ var DOTMEM_USER_ANCHOR_DIR_NAME, DOTMEM_STORAGE_LOCATOR_FILE_NAME, DOTMEM_STORAG
339
381
  var init_storage_location = __esm({
340
382
  "core/knowledge/storage-location.ts"() {
341
383
  init_storage_paths();
384
+ init_text_encoding();
342
385
  init_storage_settings();
343
386
  init_storage_paths();
344
387
  DOTMEM_USER_ANCHOR_DIR_NAME = ".dotmem";
@@ -1345,6 +1388,12 @@ var init_state = __esm({
1345
1388
  if (claim.sourceProject !== void 0 && !requiredText(claim.sourceProject)) {
1346
1389
  throw new Error(`Claim ${claim.id} has an invalid sourceProject`);
1347
1390
  }
1391
+ if (claim.check !== void 0) {
1392
+ const check = claim.check;
1393
+ if (!check || typeof check !== "object" || Array.isArray(check) || check.kind !== "regex" || !requiredText(check.pattern) || !["staged", "committed", "working-tree"].includes(check.on) || check.description !== void 0 && !requiredText(check.description)) {
1394
+ throw new Error(`Claim ${claim.id} has an invalid check`);
1395
+ }
1396
+ }
1348
1397
  return claim;
1349
1398
  }, "validateClaim");
1350
1399
  validateKnowledgeState = /* @__PURE__ */ __name((value) => {
@@ -1649,6 +1698,50 @@ var init_scope_eligibility = __esm({
1649
1698
  }
1650
1699
  });
1651
1700
 
1701
+ // core/knowledge/currentness.ts
1702
+ var asRecord, verifiedAtOf, findContestedIds, deriveCurrentness;
1703
+ var init_currentness = __esm({
1704
+ "core/knowledge/currentness.ts"() {
1705
+ asRecord = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0, "asRecord");
1706
+ verifiedAtOf = /* @__PURE__ */ __name((claim) => {
1707
+ const value = asRecord(claim.knowledge)?.verifiedAt;
1708
+ if (typeof value !== "string") return void 0;
1709
+ const parsed = Date.parse(value);
1710
+ return Number.isNaN(parsed) ? void 0 : parsed;
1711
+ }, "verifiedAtOf");
1712
+ findContestedIds = /* @__PURE__ */ __name((claims) => {
1713
+ const retracting = /* @__PURE__ */ new Map();
1714
+ for (const claim of claims) {
1715
+ if (claim.revision?.kind === "retracts" && claim.revision.claimIds.length > 0) {
1716
+ retracting.set(claim.id, new Set(claim.revision.claimIds));
1717
+ }
1718
+ }
1719
+ const contested = /* @__PURE__ */ new Set();
1720
+ for (const [id, targets] of retracting) {
1721
+ for (const target of targets) {
1722
+ if (retracting.get(target)?.has(id)) {
1723
+ contested.add(id);
1724
+ contested.add(target);
1725
+ }
1726
+ }
1727
+ }
1728
+ return contested;
1729
+ }, "findContestedIds");
1730
+ deriveCurrentness = /* @__PURE__ */ __name((claim, context2 = {}) => {
1731
+ const now2 = context2.now ?? Date.now();
1732
+ if (context2.contestedIds?.has(claim.id)) return "contested";
1733
+ if (claim.revision?.kind === "retracts") return "historical";
1734
+ if (context2.retractedIds?.has(claim.id)) return "historical";
1735
+ if (context2.supersededIds?.has(claim.id)) return "superseded";
1736
+ if (claim.expiresAt !== void 0 && now2 >= claim.expiresAt) return "expired";
1737
+ const verifiedAt = verifiedAtOf(claim);
1738
+ if (verifiedAt !== void 0) return "verified";
1739
+ if (claim.epistemicType === "verified") return "unverified";
1740
+ return "unknown-currentness";
1741
+ }, "deriveCurrentness");
1742
+ }
1743
+ });
1744
+
1652
1745
  // core/knowledge/discover.ts
1653
1746
  var diagnostic, DEFAULT_LIMITS, FIELD_ORDER, FIELD_WEIGHT, normalize, discoveryTerms, jsonText, fieldText, acquiredTime, isExpired, rankCandidate, discoverAcquiredExperience;
1654
1747
  var init_discover = __esm({
@@ -1656,6 +1749,7 @@ var init_discover = __esm({
1656
1749
  init_state();
1657
1750
  init_applicability();
1658
1751
  init_scope_eligibility();
1752
+ init_currentness();
1659
1753
  init_env();
1660
1754
  diagnostic = /* @__PURE__ */ __name((message) => {
1661
1755
  if (typeof process !== "undefined" && typeof process.stderr?.write === "function") {
@@ -1768,11 +1862,78 @@ var init_discover = __esm({
1768
1862
  throw new Error("Discovery maxCandidates must be a positive integer");
1769
1863
  }
1770
1864
  const queryTerms = discoveryTerms(situation);
1865
+ const offset = options.cursor?.offset ?? 0;
1866
+ if (!Number.isInteger(offset) || offset < 0) {
1867
+ throw new Error("Discovery cursor offset must be a non-negative integer");
1868
+ }
1869
+ if (options.cursor && options.cursor.knowledgeVersion !== validated.version) {
1870
+ return {
1871
+ knowledgeVersion: validated.version,
1872
+ depth,
1873
+ queryTerms,
1874
+ candidates: [],
1875
+ omissions: [],
1876
+ offset: 0,
1877
+ snapshotChanged: true
1878
+ };
1879
+ }
1771
1880
  const available = activeClaims(validated);
1881
+ const availableIds = new Set(available.map((claim) => claim.id));
1882
+ const retractedIds = /* @__PURE__ */ new Set();
1883
+ const supersededIds = /* @__PURE__ */ new Set();
1884
+ const contestedIds = findContestedIds(validated.claims);
1885
+ for (const claim of validated.claims) {
1886
+ if (claim.revision?.kind === "retracts") {
1887
+ for (const id of claim.revision.claimIds) retractedIds.add(id);
1888
+ }
1889
+ if (claim.revision?.kind === "supersedes") {
1890
+ for (const id of claim.revision.claimIds) supersededIds.add(id);
1891
+ }
1892
+ }
1893
+ const revisionOmissions = validated.claims.filter((claim) => !availableIds.has(claim.id)).map((claim) => {
1894
+ const retracted = retractedIds.has(claim.id);
1895
+ const superseded = supersededIds.has(claim.id);
1896
+ return {
1897
+ id: claim.id,
1898
+ reason: retracted ? "retracted" : superseded ? "superseded" : "retracted",
1899
+ gate: "revision-resolution",
1900
+ ...retracted || superseded ? {} : { detail: "the claim itself retracts prior knowledge and is kept as history" }
1901
+ };
1902
+ }).sort((left, right) => left.id.localeCompare(right.id));
1772
1903
  const scopeEligible = options.currentProjectId === void 0 ? available : available.filter((claim) => isScopeEligible(claim, options.currentProjectId, sources.get(claim.id)));
1773
1904
  const freshEligible = scopeEligible.filter((claim) => !isExpired(claim));
1905
+ const scopeEligibleIds = new Set(scopeEligible.map((claim) => claim.id));
1906
+ const scopeOmissions = available.filter((claim) => !scopeEligibleIds.has(claim.id)).map((claim) => {
1907
+ const owner = claimOwnerProject(claim, sources.get(claim.id));
1908
+ return {
1909
+ id: claim.id,
1910
+ reason: "scope",
1911
+ gate: "scope",
1912
+ detail: owner === void 0 ? "owner project could not be resolved" : `owned by project ${owner}`
1913
+ };
1914
+ }).sort((left, right) => left.id.localeCompare(right.id));
1915
+ const freshIds = new Set(freshEligible.map((claim) => claim.id));
1916
+ const freshnessOmissions = scopeEligible.filter((claim) => !freshIds.has(claim.id)).map((claim) => ({
1917
+ id: claim.id,
1918
+ reason: "expired",
1919
+ gate: "freshness",
1920
+ detail: `expired at ${new Date(claim.expiresAt).toISOString()}`
1921
+ })).sort((left, right) => left.id.localeCompare(right.id));
1774
1922
  const situationApplicability = deriveSituationApplicability(situation, options.facts);
1775
- const eligible = freshEligible.map((claim) => ({ claim, match: isEligibleByApplicability(claim, situationApplicability) })).filter((candidate) => candidate.match.eligible);
1923
+ const applicabilityMatches = new Map(
1924
+ freshEligible.map((claim) => [claim.id, isEligibleByApplicability(claim, situationApplicability)])
1925
+ );
1926
+ const eligible = freshEligible.map((claim) => ({ claim, match: applicabilityMatches.get(claim.id) })).filter((candidate) => candidate.match.eligible);
1927
+ const applicabilityOmissions = freshEligible.filter((claim) => !applicabilityMatches.get(claim.id).eligible).map((claim) => {
1928
+ const match = applicabilityMatches.get(claim.id);
1929
+ const mismatched = Object.entries(match.dimensions).filter(([, state4]) => state4 === "MISMATCH").map(([dimension]) => dimension);
1930
+ return {
1931
+ id: claim.id,
1932
+ reason: "applicability-mismatch",
1933
+ gate: "applicability",
1934
+ detail: `mismatching dimensions: ${mismatched.length > 0 ? mismatched.join(", ") : "none recorded"}`
1935
+ };
1936
+ }).sort((left, right) => left.id.localeCompare(right.id));
1776
1937
  if (DEV) {
1777
1938
  diagnostic(
1778
1939
  "[dotmem discovery] ACTIVE=" + JSON.stringify(
@@ -1784,12 +1945,15 @@ var init_discover = __esm({
1784
1945
  )
1785
1946
  );
1786
1947
  }
1948
+ const currentnessOf = /* @__PURE__ */ __name((claim) => deriveCurrentness(claim, { retractedIds, supersededIds, contestedIds }), "currentnessOf");
1787
1949
  if (queryTerms.length === 0) {
1788
- const baseline = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1950
+ const baselineAll = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1789
1951
  const leftTime = acquiredTime(left);
1790
1952
  const rightTime = acquiredTime(right);
1791
1953
  return rightTime - leftTime || Number(right.scope === "project") - Number(left.scope === "project") || left.id.localeCompare(right.id);
1792
- }).slice(0, maxCandidates);
1954
+ });
1955
+ const baseline = baselineAll.slice(offset, offset + maxCandidates);
1956
+ const limitOmissions = baselineAll.slice(offset + maxCandidates).map((claim) => ({ id: claim.id, reason: "limit", gate: "ranking" })).sort((left, right) => left.id.localeCompare(right.id));
1793
1957
  const baselineCandidates = baseline.map((claim) => {
1794
1958
  const explanation = {
1795
1959
  matchedTerms: [],
@@ -1802,7 +1966,8 @@ var init_discover = __esm({
1802
1966
  }
1803
1967
  return {
1804
1968
  claim,
1805
- explanation
1969
+ explanation,
1970
+ currentness: currentnessOf(claim)
1806
1971
  };
1807
1972
  });
1808
1973
  if (DEV) {
@@ -1815,10 +1980,18 @@ var init_discover = __esm({
1815
1980
  depth,
1816
1981
  queryTerms,
1817
1982
  situationApplicability,
1818
- candidates: baselineCandidates
1983
+ candidates: baselineCandidates,
1984
+ offset,
1985
+ omissions: [
1986
+ ...revisionOmissions,
1987
+ ...scopeOmissions,
1988
+ ...freshnessOmissions,
1989
+ ...applicabilityOmissions,
1990
+ ...limitOmissions
1991
+ ]
1819
1992
  };
1820
1993
  }
1821
- const candidates = eligible.map(
1994
+ const ranked = eligible.map(
1822
1995
  (candidate) => rankCandidate(
1823
1996
  candidate.claim,
1824
1997
  situation,
@@ -1830,16 +2003,40 @@ var init_discover = __esm({
1830
2003
  (candidate) => candidate !== null
1831
2004
  ).sort(
1832
2005
  (left, right) => Number(right.directPhrase) - Number(left.directPhrase) || right.matchedTermCount - left.matchedTermCount || right.fieldWeight - left.fieldWeight || Number(right.claim.scope === "project") - Number(left.claim.scope === "project") || right.acquiredTime - left.acquiredTime || left.claim.id.localeCompare(right.claim.id)
1833
- ).slice(0, maxCandidates).map(({ claim, explanation }) => ({
2006
+ );
2007
+ const rankedIds = new Set(ranked.map((candidate) => candidate.claim.id));
2008
+ const rankingOmissions = [
2009
+ ...eligible.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2010
+ id: candidate.claim.id,
2011
+ reason: "no-term-match",
2012
+ gate: "ranking",
2013
+ detail: "passed every gate but shares no query term"
2014
+ })),
2015
+ ...ranked.slice(offset + maxCandidates).map((candidate) => ({
2016
+ id: candidate.claim.id,
2017
+ reason: "limit",
2018
+ gate: "ranking"
2019
+ }))
2020
+ ].sort((left, right) => left.id.localeCompare(right.id));
2021
+ const candidates = ranked.slice(offset, offset + maxCandidates).map(({ claim, explanation }) => ({
1834
2022
  claim,
1835
- explanation
2023
+ explanation,
2024
+ currentness: currentnessOf(claim)
1836
2025
  }));
1837
2026
  return {
1838
2027
  knowledgeVersion: validated.version,
1839
2028
  depth,
1840
2029
  queryTerms,
1841
2030
  situationApplicability,
1842
- candidates
2031
+ candidates,
2032
+ offset,
2033
+ omissions: [
2034
+ ...revisionOmissions,
2035
+ ...scopeOmissions,
2036
+ ...freshnessOmissions,
2037
+ ...applicabilityOmissions,
2038
+ ...rankingOmissions
2039
+ ]
1843
2040
  };
1844
2041
  }, "discoverAcquiredExperience");
1845
2042
  }
@@ -2896,7 +3093,7 @@ var init_policy_store = __esm({
2896
3093
  });
2897
3094
 
2898
3095
  // core/knowledge/acquisition-limits.ts
2899
- var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder, serializedBytes, measureKnowledge, checkAcquireLimits;
3096
+ var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder2, serializedBytes, measureKnowledge, checkAcquireLimits;
2900
3097
  var init_acquisition_limits = __esm({
2901
3098
  "core/knowledge/acquisition-limits.ts"() {
2902
3099
  MEMORY_ACQUIRE_LIMITS = Object.freeze({
@@ -2955,10 +3152,10 @@ var init_acquisition_limits = __esm({
2955
3152
  this.name = "MemoryAcquireDuplicateClaimError";
2956
3153
  }
2957
3154
  };
2958
- encoder = new TextEncoder();
3155
+ encoder2 = new TextEncoder();
2959
3156
  serializedBytes = /* @__PURE__ */ __name((value) => {
2960
3157
  const json = JSON.stringify(value);
2961
- return json === void 0 ? 0 : encoder.encode(json).length;
3158
+ return json === void 0 ? 0 : encoder2.encode(json).length;
2962
3159
  }, "serializedBytes");
2963
3160
  measureKnowledge = /* @__PURE__ */ __name((knowledge) => {
2964
3161
  const claimBytes = serializedBytes(knowledge);
@@ -3052,7 +3249,7 @@ var init_context_constants = __esm({
3052
3249
  });
3053
3250
 
3054
3251
  // core/knowledge/project.ts
3055
- var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_MAX_CHARACTERS, projectCandidate, renderHeader, renderExperience, renderText, projectDiscoveredExperience;
3252
+ var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_MAX_CHARACTERS, projectCandidate, GIST_MAX_LENGTH, GIST_KEYS, MANIFEST_ID_LIMIT, deriveGist, renderHeader, renderExperience, renderText, byteLength, summarizeOmissions, renderManifestFitting, renderCompactExperience, projectDiscoveredExperience;
3056
3253
  var init_project = __esm({
3057
3254
  "core/knowledge/project.ts"() {
3058
3255
  init_state();
@@ -3077,9 +3274,29 @@ var init_project = __esm({
3077
3274
  ...claim.provenance ? { provenance: claim.provenance } : {},
3078
3275
  ...claim.acquiredAt ? { acquiredAt: claim.acquiredAt } : {},
3079
3276
  ...claim.revision ? { revision: claim.revision } : {},
3080
- ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {}
3277
+ ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {},
3278
+ ...candidate.currentness ? { currentness: candidate.currentness } : {}
3081
3279
  });
3082
3280
  }, "projectCandidate");
3281
+ GIST_MAX_LENGTH = 80;
3282
+ GIST_KEYS = ["gist", "summary", "statement", "title", "reason", "principle", "finding", "detail"];
3283
+ MANIFEST_ID_LIMIT = 40;
3284
+ deriveGist = /* @__PURE__ */ __name((knowledge) => {
3285
+ if (typeof knowledge === "string") {
3286
+ return knowledge.length > GIST_MAX_LENGTH ? `${knowledge.slice(0, GIST_MAX_LENGTH)}\u2026` : knowledge;
3287
+ }
3288
+ if (knowledge && typeof knowledge === "object" && !Array.isArray(knowledge)) {
3289
+ const obj = knowledge;
3290
+ for (const key of GIST_KEYS) {
3291
+ const value = obj[key];
3292
+ if (typeof value === "string" && value.length > 0) {
3293
+ return value.length > GIST_MAX_LENGTH ? `${value.slice(0, GIST_MAX_LENGTH)}\u2026` : value;
3294
+ }
3295
+ }
3296
+ }
3297
+ const str = JSON.stringify(knowledge);
3298
+ return str.length > GIST_MAX_LENGTH ? `${str.slice(0, GIST_MAX_LENGTH)}\u2026` : str;
3299
+ }, "deriveGist");
3083
3300
  renderHeader = /* @__PURE__ */ __name((knowledgeVersion, totalCandidates) => {
3084
3301
  const lines = [
3085
3302
  `DOTMEM STORAGE: ${resolveUserDotMemPath()}`,
@@ -3105,27 +3322,70 @@ var init_project = __esm({
3105
3322
  evidence.supports ?? null
3106
3323
  ]),
3107
3324
  ...experience.epistemicType ? { epistemic: experience.epistemicType } : {},
3325
+ ...experience.currentness ? { currentness: experience.currentness } : {},
3108
3326
  ...experience.provenance ? { provenance: [experience.provenance.source, experience.provenance.detail ?? null] } : {},
3109
3327
  ...experience.acquiredAt ? { acquiredAt: experience.acquiredAt } : {},
3110
3328
  ...experience.revision ? { revision: experience.revision } : {},
3111
3329
  ...experience.sourceId ? { source: experience.sourceId } : {}
3112
3330
  }), "renderExperience");
3113
- renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates) => `${header}${experiences.length ? `
3114
- ${experiences.map(renderExperience).join("\n")}` : ""}
3115
- OMITTED:${omittedCandidates}`, "renderText");
3331
+ renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, render = renderExperience, currentnessSummary) => {
3332
+ const lines = [header];
3333
+ if (experiences.length > 0) lines.push(...experiences.map(render));
3334
+ lines.push(`OMITTED:${omittedCandidates}`);
3335
+ if (manifest && manifest.byReason.length > 0) {
3336
+ lines.push(`OMITTED_BY_REASON:${manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`);
3337
+ }
3338
+ if (manifest && manifest.items.length > 0) {
3339
+ lines.push(`OMITTED_IDS:${manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`);
3340
+ if (manifest.items.length > MANIFEST_ID_LIMIT) {
3341
+ lines.push(`OMITTED_IDS_TRUNCATED:${manifest.items.length - MANIFEST_ID_LIMIT}`);
3342
+ }
3343
+ }
3344
+ if (currentnessSummary) {
3345
+ lines.push(`CURRENTNESS:${currentnessSummary}`);
3346
+ }
3347
+ return lines.join("\n");
3348
+ }, "renderText");
3349
+ byteLength = /* @__PURE__ */ __name((value) => new TextEncoder().encode(value).length, "byteLength");
3350
+ summarizeOmissions = /* @__PURE__ */ __name((items) => {
3351
+ const counts = /* @__PURE__ */ new Map();
3352
+ for (const item of items) counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
3353
+ return [...counts.entries()].map(([reason, count]) => ({ reason, count })).sort((left, right) => left.reason.localeCompare(right.reason));
3354
+ }, "summarizeOmissions");
3355
+ renderManifestFitting = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, maxCharacters, render, currentnessSummary) => {
3356
+ const full = renderText(header, experiences, omittedCandidates, manifest, render, currentnessSummary);
3357
+ if (byteLength(full) <= maxCharacters) return full;
3358
+ const withoutIds = { ...manifest, items: [] };
3359
+ return renderText(header, experiences, omittedCandidates, withoutIds, render, currentnessSummary);
3360
+ }, "renderManifestFitting");
3361
+ renderCompactExperience = /* @__PURE__ */ __name((experience) => JSON.stringify({
3362
+ id: experience.id,
3363
+ status: "candidate",
3364
+ gist: deriveGist(experience.experience),
3365
+ epistemic: experience.epistemicType ?? null,
3366
+ currentness: experience.currentness ?? null,
3367
+ ...experience.revision ? { revision: experience.revision.kind } : {}
3368
+ }), "renderCompactExperience");
3116
3369
  projectDiscoveredExperience = /* @__PURE__ */ __name((discovery, options = {}) => {
3117
3370
  if (!discovery || !Number.isInteger(discovery.knowledgeVersion) || discovery.knowledgeVersion < 0 || !Array.isArray(discovery.candidates)) {
3118
3371
  throw new Error("Valid DiscoveryResult is required for context projection");
3119
3372
  }
3120
3373
  const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES;
3121
3374
  const maxCharacters = options.maxCharacters ?? DEFAULT_MAX_CHARACTERS;
3375
+ const format = options.format ?? "compact";
3376
+ if (format !== "compact" && format !== "standard" && format !== "full") {
3377
+ throw new Error("Projection format must be compact, standard or full");
3378
+ }
3122
3379
  if (!Number.isInteger(maxCandidates) || maxCandidates < 1) throw new Error("Projection maxCandidates must be a positive integer");
3123
3380
  if (!Number.isInteger(maxCharacters) || maxCharacters < MIN_MAX_CHARACTERS) {
3124
3381
  throw new Error(`Projection maxCharacters must be an integer of at least ${MIN_MAX_CHARACTERS}`);
3125
3382
  }
3126
- const totalCandidates = discovery.candidates.length;
3383
+ const render = /* @__PURE__ */ __name((experience) => format === "compact" ? renderCompactExperience(experience) : renderExperience(experience), "render");
3384
+ const gateOmissions = discovery.omissions ?? [];
3385
+ const totalCandidates = discovery.candidates.length + gateOmissions.length;
3127
3386
  const header = renderHeader(discovery.knowledgeVersion, totalCandidates);
3128
- if (renderText(header, [], totalCandidates).length > maxCharacters) {
3387
+ const emptyManifest = { considered: totalCandidates, included: 0, items: [], byReason: [] };
3388
+ if (byteLength(renderText(header, [], totalCandidates, emptyManifest)) > maxCharacters) {
3129
3389
  throw new Error("Projection maxCharacters is too small for the projection envelope");
3130
3390
  }
3131
3391
  const experiences = [];
@@ -3134,12 +3394,49 @@ OMITTED:${omittedCandidates}`, "renderText");
3134
3394
  const projected = projectCandidate(candidate);
3135
3395
  const possibleExperiences = [...experiences, projected];
3136
3396
  const possibleOmitted = totalCandidates - possibleExperiences.length;
3137
- if (renderText(header, possibleExperiences, possibleOmitted).length <= maxCharacters) {
3397
+ const candidateManifest = {
3398
+ considered: totalCandidates,
3399
+ included: possibleExperiences.length,
3400
+ items: gateOmissions,
3401
+ byReason: summarizeOmissions(gateOmissions)
3402
+ };
3403
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, candidateManifest, render)) <= maxCharacters) {
3404
+ experiences.push(projected);
3405
+ continue;
3406
+ }
3407
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, void 0, render)) <= maxCharacters) {
3138
3408
  experiences.push(projected);
3139
3409
  }
3140
3410
  }
3411
+ const projectedIds = new Set(experiences.map((experience) => experience.id));
3412
+ const budgetOmissions = discovery.candidates.filter((candidate) => !projectedIds.has(candidate.claim.id)).map((candidate) => ({ id: candidate.claim.id, reason: "budget", gate: "projection" }));
3413
+ const items = [...gateOmissions, ...budgetOmissions];
3141
3414
  const omittedCandidates = totalCandidates - experiences.length;
3142
- const text = renderText(header, experiences, omittedCandidates);
3415
+ const manifest = {
3416
+ considered: totalCandidates,
3417
+ included: experiences.length,
3418
+ items,
3419
+ byReason: summarizeOmissions(items)
3420
+ };
3421
+ const currentnessCounts = /* @__PURE__ */ new Map();
3422
+ for (const experience of experiences) {
3423
+ if (experience.currentness) {
3424
+ currentnessCounts.set(
3425
+ experience.currentness,
3426
+ (currentnessCounts.get(experience.currentness) ?? 0) + 1
3427
+ );
3428
+ }
3429
+ }
3430
+ const currentnessSummary = currentnessCounts.size > 0 ? [...currentnessCounts.entries()].map(([state3, count]) => `${state3}=${count}`).join(",") : void 0;
3431
+ const text = renderManifestFitting(
3432
+ header,
3433
+ experiences,
3434
+ omittedCandidates,
3435
+ manifest,
3436
+ maxCharacters,
3437
+ render,
3438
+ currentnessSummary
3439
+ );
3143
3440
  return {
3144
3441
  format: FORMAT,
3145
3442
  status: STATUS,
@@ -3148,6 +3445,7 @@ OMITTED:${omittedCandidates}`, "renderText");
3148
3445
  totalCandidates,
3149
3446
  omittedCandidates,
3150
3447
  experiences,
3448
+ manifest,
3151
3449
  text
3152
3450
  };
3153
3451
  }, "projectDiscoveredExperience");
@@ -3185,7 +3483,7 @@ var init_language_detect = __esm({
3185
3483
  var CANONICAL_KINDS, validateKind, buildClaimRecord;
3186
3484
  var init_claim_record = __esm({
3187
3485
  "core/knowledge/claim-record.ts"() {
3188
- CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note"];
3486
+ CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note", "rule"];
3189
3487
  validateKind = /* @__PURE__ */ __name((kind) => {
3190
3488
  if (!CANONICAL_KINDS.includes(kind)) {
3191
3489
  throw new Error(
@@ -4416,8 +4714,8 @@ var init_browser = __esm({
4416
4714
  this.p = null;
4417
4715
  }
4418
4716
  };
4419
- Unzip2.prototype.register = function(decoder2) {
4420
- this.o[decoder2.compression] = decoder2;
4717
+ Unzip2.prototype.register = function(decoder) {
4718
+ this.o[decoder.compression] = decoder;
4421
4719
  };
4422
4720
  return Unzip2;
4423
4721
  })();
@@ -4437,6 +4735,15 @@ function encodeMemFile(stateValue, preserved) {
4437
4735
  if (!map.claim.includes("kind")) {
4438
4736
  map.claim.push("kind");
4439
4737
  }
4738
+ if (!map.claim.includes("expires-at")) {
4739
+ map.claim.push("expires-at");
4740
+ }
4741
+ if (!map.claim.includes("bootstrap-priority")) {
4742
+ map.claim.push("bootstrap-priority");
4743
+ }
4744
+ if (!map.claim.includes("check")) {
4745
+ map.claim.push("check");
4746
+ }
4440
4747
  const indexes = Object.fromEntries(Object.keys(expectedFields).map((name) => [name, fieldIndexes(map, name)]));
4441
4748
  validateVocabulary(map.epistemicType, epistemicTypes, "epistemicType");
4442
4749
  validateVocabulary(map.revisionKind, revisionKinds, "revisionKind");
@@ -4486,6 +4793,15 @@ function encodeMemFile(stateValue, preserved) {
4486
4793
  if (indexes.claim.has("kind")) {
4487
4794
  putOptional(record, indexes.claim, "kind", claim.kind ?? void 0, original !== void 0);
4488
4795
  }
4796
+ if (indexes.claim.has("expires-at")) {
4797
+ putOptional(record, indexes.claim, "expires-at", claim.expiresAt, original !== void 0);
4798
+ }
4799
+ if (indexes.claim.has("bootstrap-priority")) {
4800
+ putOptional(record, indexes.claim, "bootstrap-priority", claim.bootstrapPriority, original !== void 0);
4801
+ }
4802
+ if (indexes.claim.has("check")) {
4803
+ putOptional(record, indexes.claim, "check", claim.check, original !== void 0);
4804
+ }
4489
4805
  return original ? record : trimRecord(record);
4490
4806
  }, "encodeClaim");
4491
4807
  const stateRecord = structuredClone(preserved?.data ?? []);
@@ -4554,8 +4870,37 @@ function decodeMemDocument(value) {
4554
4870
  const scope = optionalGet(record, indexes.claim, "scope");
4555
4871
  const sourceProject = optionalGet(record, indexes.claim, "source-project");
4556
4872
  const kindValue = optionalGet(record, indexes.claim, "kind");
4873
+ const expiresAtValue = indexes.claim.has("expires-at") ? optionalGet(record, indexes.claim, "expires-at") : void 0;
4874
+ const bootstrapPriorityValue = indexes.claim.has("bootstrap-priority") ? optionalGet(record, indexes.claim, "bootstrap-priority") : void 0;
4875
+ const checkValue = indexes.claim.has("check") ? optionalGet(record, indexes.claim, "check") : void 0;
4557
4876
  if (epistemicIndex !== void 0 && (!Number.isInteger(epistemicIndex) || epistemicIndex < 0 || epistemicIndex >= epistemic.length)) throw new Error("Invalid .mem epistemic value");
4558
4877
  if (kindIndex !== void 0 && (!Number.isInteger(kindIndex) || kindIndex < 0 || kindIndex >= revisions.length)) throw new Error("Invalid .mem revision value");
4878
+ if (expiresAtValue !== void 0 && (!Number.isInteger(expiresAtValue) || expiresAtValue < 0)) {
4879
+ throw new Error("Invalid .mem expiresAt value");
4880
+ }
4881
+ if (bootstrapPriorityValue !== void 0 && !bootstrapPriorities.includes(bootstrapPriorityValue)) {
4882
+ throw new Error("Invalid .mem bootstrapPriority value");
4883
+ }
4884
+ let check;
4885
+ if (checkValue !== void 0) {
4886
+ if (!checkValue || typeof checkValue !== "object" || Array.isArray(checkValue)) {
4887
+ throw new Error("Invalid .mem check record");
4888
+ }
4889
+ const checkRecord = checkValue;
4890
+ const description = checkRecord.description;
4891
+ if (typeof description !== "undefined" && typeof description !== "string") {
4892
+ throw new Error("Invalid .mem check record");
4893
+ }
4894
+ if (checkRecord.kind !== "regex" || typeof checkRecord.pattern !== "string" || checkRecord.pattern.length === 0 || !checkTargets.includes(checkRecord.on)) {
4895
+ throw new Error("Invalid .mem check record");
4896
+ }
4897
+ check = {
4898
+ kind: "regex",
4899
+ pattern: checkRecord.pattern,
4900
+ on: checkRecord.on,
4901
+ ...typeof description === "string" ? { description } : {}
4902
+ };
4903
+ }
4559
4904
  const understoodEpistemic = typeof epistemicIndex === "number" && epistemicTypes.includes(epistemic[epistemicIndex]) ? epistemic[epistemicIndex] : void 0;
4560
4905
  const understoodRevision = typeof kindIndex === "number" && revisionKinds.includes(revisions[kindIndex]);
4561
4906
  const claim = {
@@ -4580,6 +4925,9 @@ function decodeMemDocument(value) {
4580
4925
  } : {},
4581
4926
  ...scope === void 0 ? {} : { scope },
4582
4927
  ...sourceProject === void 0 ? {} : { sourceProject },
4928
+ ...expiresAtValue === void 0 ? {} : { expiresAt: expiresAtValue },
4929
+ ...bootstrapPriorityValue === void 0 ? {} : { bootstrapPriority: bootstrapPriorityValue },
4930
+ ...check === void 0 ? {} : { check },
4583
4931
  ...claimKinds.includes(kindValue) ? { kind: kindValue } : {}
4584
4932
  };
4585
4933
  return validateClaim(claim);
@@ -4589,7 +4937,7 @@ function decodeMemDocument(value) {
4589
4937
  preserved: { map: structuredClone(map), data: structuredClone(stateRecord) }
4590
4938
  };
4591
4939
  }
4592
- var MEM_FORMAT, MEM_FORMAT_LEGACY, MEM_FORMAT_VERSION, MEM_FORMAT_VERSION_V1, expectedFields, epistemicTypes, revisionKinds, claimKinds, isJsonValue2, createMemInterpretationMap, validateSourceState, trimRecord, fieldIndexes, validateVocabulary, put, get, optionalGet, requireRecord, putOptional;
4940
+ var MEM_FORMAT, MEM_FORMAT_LEGACY, MEM_FORMAT_VERSION, MEM_FORMAT_VERSION_V1, expectedFields, epistemicTypes, revisionKinds, claimKinds, bootstrapPriorities, checkTargets, isJsonValue2, createMemInterpretationMap, validateSourceState, trimRecord, fieldIndexes, validateVocabulary, put, get, optionalGet, requireRecord, putOptional;
4593
4941
  var init_mem_codec = __esm({
4594
4942
  "core/knowledge/mem-codec.ts"() {
4595
4943
  init_state();
@@ -4606,7 +4954,9 @@ var init_mem_codec = __esm({
4606
4954
  };
4607
4955
  epistemicTypes = ["observed", "inferred", "human-stated", "verified"];
4608
4956
  revisionKinds = ["refines", "supersedes", "retracts"];
4609
- claimKinds = ["experience", "agent", "relationship", "logic", "note"];
4957
+ claimKinds = ["experience", "agent", "relationship", "logic", "note", "rule"];
4958
+ bootstrapPriorities = ["P1", "P2", "P3", "P4", "P5", "unclassified"];
4959
+ checkTargets = ["staged", "committed", "working-tree"];
4610
4960
  isJsonValue2 = /* @__PURE__ */ __name((value) => {
4611
4961
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
4612
4962
  if (typeof value === "number") return Number.isFinite(value);
@@ -4680,14 +5030,14 @@ async function encodeMemPackage(state3, semantic, preservedPackage) {
4680
5030
  return encodePackage(state3, semantic, preservedPackage);
4681
5031
  }
4682
5032
  async function decodeMemArtifact(input) {
4683
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
5033
+ const bytes = typeof input === "string" ? encoder3.encode(input) : input;
4684
5034
  if (isZip(bytes)) {
4685
5035
  const { parts: _parts, integrity: _integrity, ...artifact } = await decodePackage(bytes);
4686
5036
  return artifact;
4687
5037
  }
4688
5038
  let value;
4689
5039
  try {
4690
- value = JSON.parse(decoder.decode(bytes).replace(/^\uFEFF/, ""));
5040
+ value = JSON.parse(decodeText(bytes));
4691
5041
  } catch (error) {
4692
5042
  throw new MemArtifactError("corrupt", `Unsupported or corrupt MEM artifact: ${error.message}`);
4693
5043
  }
@@ -4700,11 +5050,12 @@ async function decodeMemArtifact(input) {
4700
5050
  throw new MemArtifactError(message.startsWith("Unsupported") ? "unsupported" : "invalid", message);
4701
5051
  }
4702
5052
  }
4703
- var MEM_PACKAGE_FORMAT, MEM_PACKAGE_FORMAT_LEGACY, MEM_PACKAGE_VERSION, MEM_PACKAGE_LIMITS, MEM_PACKAGE_WRITE_MARGIN_BYTES, MEM_PACKAGE_WRITE_LIMITS, MANIFEST_PATH, MAP_PATH, DATA_PATH, INTEGRITY_PATH, requiredParts, encoder2, decoder, MemArtifactError, stableValue, jsonBytes, sha256, parseJson, validEntryPath, concatenate, readZipParts, createManifest, digestTableIdentity, encodePackage, isZip, decodePackage;
5053
+ var MEM_PACKAGE_FORMAT, MEM_PACKAGE_FORMAT_LEGACY, MEM_PACKAGE_VERSION, MEM_PACKAGE_LIMITS, MEM_PACKAGE_WRITE_MARGIN_BYTES, MEM_PACKAGE_WRITE_LIMITS, MANIFEST_PATH, MAP_PATH, DATA_PATH, INTEGRITY_PATH, requiredParts, encoder3, MemArtifactError, stableValue, jsonBytes, sha256, parseJson, validEntryPath, concatenate, readZipParts, createManifest, digestTableIdentity, encodePackage, isZip, decodePackage;
4704
5054
  var init_mem_package = __esm({
4705
5055
  "core/knowledge/mem-package.ts"() {
4706
5056
  init_browser();
4707
5057
  init_mem_codec();
5058
+ init_text_encoding();
4708
5059
  MEM_PACKAGE_FORMAT = "dotmem.package";
4709
5060
  MEM_PACKAGE_FORMAT_LEGACY = "memorio.package";
4710
5061
  MEM_PACKAGE_VERSION = 1;
@@ -4728,8 +5079,7 @@ var init_mem_package = __esm({
4728
5079
  DATA_PATH = "memory/data.json";
4729
5080
  INTEGRITY_PATH = "security/integrity.json";
4730
5081
  requiredParts = [MANIFEST_PATH, MAP_PATH, DATA_PATH];
4731
- encoder2 = new TextEncoder();
4732
- decoder = new TextDecoder("utf-8", { fatal: true });
5082
+ encoder3 = new TextEncoder();
4733
5083
  MemArtifactError = class extends Error {
4734
5084
  constructor(code, message) {
4735
5085
  super(message);
@@ -4748,7 +5098,7 @@ var init_mem_package = __esm({
4748
5098
  }
4749
5099
  return value;
4750
5100
  }, "stableValue");
4751
- jsonBytes = /* @__PURE__ */ __name((value) => encoder2.encode(`${JSON.stringify(stableValue(value), null, 2)}
5101
+ jsonBytes = /* @__PURE__ */ __name((value) => encoder3.encode(`${JSON.stringify(stableValue(value), null, 2)}
4752
5102
  `), "jsonBytes");
4753
5103
  sha256 = /* @__PURE__ */ __name(async (data) => {
4754
5104
  if (!globalThis.crypto?.subtle) throw new MemArtifactError("unsupported", "SHA-256 is unavailable in this runtime");
@@ -4757,7 +5107,7 @@ var init_mem_package = __esm({
4757
5107
  }, "sha256");
4758
5108
  parseJson = /* @__PURE__ */ __name((bytes, path2) => {
4759
5109
  try {
4760
- return JSON.parse(decoder.decode(bytes));
5110
+ return JSON.parse(decodeText(bytes));
4761
5111
  } catch (error) {
4762
5112
  throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path2}: ${error.message}`);
4763
5113
  }
@@ -4927,10 +5277,12 @@ var init_mem_package = __esm({
4927
5277
  });
4928
5278
 
4929
5279
  // core/storage-coordinator/index.ts
4930
- var nodeFs4, withStorageLock, readStorageGeneration, writeStorageGeneration;
5280
+ var nodeFs4, heldLocks, withStorageLock, readStorageGeneration, writeStorageGeneration;
4931
5281
  var init_storage_coordinator = __esm({
4932
5282
  "core/storage-coordinator/index.ts"() {
5283
+ init_text_encoding();
4933
5284
  nodeFs4 = /* @__PURE__ */ __name(async () => import('fs/promises'), "nodeFs");
5285
+ heldLocks = /* @__PURE__ */ new Map();
4934
5286
  withStorageLock = /* @__PURE__ */ __name(async (directoryPath, operationOrOptions, operation, _options = {}) => {
4935
5287
  const opts = typeof operationOrOptions === "function" ? operation ?? {} : operationOrOptions ?? {};
4936
5288
  const op = typeof operationOrOptions === "function" ? operationOrOptions : operation;
@@ -4940,6 +5292,15 @@ var init_storage_coordinator = __esm({
4940
5292
  const lockPath = `${directoryPath}/${lockName}`;
4941
5293
  const fs2 = await nodeFs4();
4942
5294
  const started = Date.now();
5295
+ const heldDepth = heldLocks.get(lockPath) ?? 0;
5296
+ if (heldDepth > 0) {
5297
+ heldLocks.set(lockPath, heldDepth + 1);
5298
+ try {
5299
+ return await op();
5300
+ } finally {
5301
+ heldLocks.set(lockPath, heldDepth);
5302
+ }
5303
+ }
4943
5304
  await fs2.mkdir(directoryPath, { recursive: true });
4944
5305
  while (true) {
4945
5306
  try {
@@ -4953,8 +5314,8 @@ var init_storage_coordinator = __esm({
4953
5314
  let stale = false;
4954
5315
  let processDead = false;
4955
5316
  try {
4956
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
4957
- const parsed = JSON.parse(raw);
5317
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5318
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
4958
5319
  const ageStale = typeof parsed.createdAt === "number" && Date.now() - parsed.createdAt > staleMs;
4959
5320
  if (typeof parsed.pid === "number") {
4960
5321
  try {
@@ -4991,17 +5352,19 @@ var init_storage_coordinator = __esm({
4991
5352
  }
4992
5353
  let token = "";
4993
5354
  try {
4994
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
4995
- token = JSON.parse(raw).token ?? "";
5355
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5356
+ token = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` })).token ?? "";
4996
5357
  } catch {
4997
5358
  token = "";
4998
5359
  }
4999
5360
  try {
5361
+ heldLocks.set(lockPath, 1);
5000
5362
  return await op();
5001
5363
  } finally {
5364
+ heldLocks.delete(lockPath);
5002
5365
  try {
5003
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5004
- const parsed = JSON.parse(raw);
5366
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5367
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
5005
5368
  if (parsed.token === token && token) {
5006
5369
  await fs2.rm(lockPath, { recursive: true, force: true });
5007
5370
  }
@@ -5012,8 +5375,8 @@ var init_storage_coordinator = __esm({
5012
5375
  readStorageGeneration = /* @__PURE__ */ __name(async (directoryPath) => {
5013
5376
  const fs2 = await nodeFs4();
5014
5377
  try {
5015
- const raw = await fs2.readFile(`${directoryPath}/.storage.generation`, "utf8");
5016
- const value = Number(raw.trim());
5378
+ const raw = await fs2.readFile(`${directoryPath}/.storage.generation`);
5379
+ const value = Number(decodeText(raw, { source: `${directoryPath}/.storage.generation` }).trim());
5017
5380
  return Number.isFinite(value) && value >= 0 ? value : 0;
5018
5381
  } catch {
5019
5382
  return 0;
@@ -5501,12 +5864,11 @@ function readJsonFile(path2) {
5501
5864
  if (!fs2) return null;
5502
5865
  let raw;
5503
5866
  try {
5504
- raw = fs2.readFileSync(path2, "utf8");
5867
+ raw = decodeText(fs2.readFileSync(path2), { source: path2 });
5505
5868
  } catch {
5506
5869
  return null;
5507
5870
  }
5508
5871
  if (typeof raw !== "string") return null;
5509
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
5510
5872
  try {
5511
5873
  return JSON.parse(raw);
5512
5874
  } catch {
@@ -5630,6 +5992,7 @@ var init_user_language = __esm({
5630
5992
  "core/knowledge/user-language.ts"() {
5631
5993
  init_user_paths();
5632
5994
  init_storage_paths();
5995
+ init_text_encoding();
5633
5996
  USER_LANGUAGE_FILE_NAME = "language.json";
5634
5997
  USER_LANGUAGE_PREFERENCE_FILE_NAME = "user-language.json";
5635
5998
  LANGUAGE_PREFERENCE_FILE_NAME = "language-preference.json";
@@ -9353,10 +9716,13 @@ var init_staging = __esm({
9353
9716
  epistemicType: sanitizedClaim.epistemicType,
9354
9717
  provenance: sanitizedClaim.provenance,
9355
9718
  acquiredAt: sanitizedClaim.acquiredAt,
9719
+ ...sanitizedClaim.expiresAt === void 0 ? {} : { expiresAt: sanitizedClaim.expiresAt },
9720
+ ...sanitizedClaim.bootstrapPriority === void 0 ? {} : { bootstrapPriority: sanitizedClaim.bootstrapPriority },
9356
9721
  revision,
9357
9722
  scope,
9358
9723
  sourceProject,
9359
- kind
9724
+ kind,
9725
+ ...sanitizedClaim.check === void 0 ? {} : { check: sanitizedClaim.check }
9360
9726
  });
9361
9727
  await withStoreQueue(acquisitionStoreKey(kind, scope, sourceProject), async () => {
9362
9728
  const state3 = await target.runtime.select([]);
@@ -9604,19 +9970,19 @@ var init_incidents = __esm({
9604
9970
  }
9605
9971
  });
9606
9972
 
9607
- // core/knowledge/rules-loader.ts
9608
- var init_rules_loader = __esm({
9609
- "core/knowledge/rules-loader.ts"() {
9610
- init_state();
9611
- }
9612
- });
9613
-
9614
9973
  // core/knowledge/violations.ts
9615
9974
  var init_violations = __esm({
9616
9975
  "core/knowledge/violations.ts"() {
9617
9976
  init_user_paths();
9618
9977
  }
9619
9978
  });
9979
+ var init_rules_loader = __esm({
9980
+ "core/knowledge/rules-loader.ts"() {
9981
+ init_state();
9982
+ init_user_paths();
9983
+ init_violations();
9984
+ }
9985
+ });
9620
9986
 
9621
9987
  // core/knowledge/session.ts
9622
9988
  var init_session = __esm({
@@ -10077,8 +10443,8 @@ function loadBuiltInContext() {
10077
10443
  for (const candidate of candidates) {
10078
10444
  if (!fs.existsSync(candidate)) continue;
10079
10445
  try {
10080
- const raw = fs.readFileSync(candidate, "utf8");
10081
- const parsed = JSON.parse(raw);
10446
+ const raw = fs.readFileSync(candidate);
10447
+ const parsed = JSON.parse(decodeText(raw, { source: candidate }));
10082
10448
  const artifact = validateArtifact(parsed);
10083
10449
  cached = artifact;
10084
10450
  cachedStatus = {
@@ -10135,6 +10501,7 @@ function assertBuiltInContextAvailable() {
10135
10501
  var BUILT_IN_CONTEXT_FORMAT, BUILT_IN_CONTEXT_FORMAT_VERSION, cached, cachedStatus, _artifactPathOverride;
10136
10502
  var init_built_in_context = __esm({
10137
10503
  "core/knowledge/built-in-context.ts"() {
10504
+ init_text_encoding();
10138
10505
  BUILT_IN_CONTEXT_FORMAT = "dotmem.built-in-context";
10139
10506
  BUILT_IN_CONTEXT_FORMAT_VERSION = 1;
10140
10507
  cached = null;
@@ -10194,6 +10561,7 @@ var init_knowledge = __esm({
10194
10561
  init_state();
10195
10562
  init_select();
10196
10563
  init_discover();
10564
+ init_currentness();
10197
10565
  init_project();
10198
10566
  init_applicability();
10199
10567
  init_policy();
@@ -10301,7 +10669,6 @@ function _inferConfidence(claim) {
10301
10669
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, LogicEngine, logic, logic_default;
10302
10670
  var init_logic = __esm({
10303
10671
  "core/logic/index.ts"() {
10304
- init_suppress_idb_warning();
10305
10672
  init_knowledge();
10306
10673
  init_mem_repository();
10307
10674
  init_acquisition_boundary();
@@ -10569,18 +10936,6 @@ Do not store secrets unless dotmem explicitly supports secure secret storage.
10569
10936
  }
10570
10937
  });
10571
10938
 
10572
- // global.ts
10573
- init_suppress_idb_warning();
10574
-
10575
- // core/idb.ts
10576
- var idb = {
10577
- db: {},
10578
- table: {},
10579
- data: {},
10580
- _disabled: true,
10581
- _warning: "IndexedDB is not available in this environment. Use dotmem store or session for persistence."
10582
- };
10583
-
10584
10939
  // core/encryption/index.ts
10585
10940
  var PBKDF2_ITERATIONS = 6e5;
10586
10941
  var AES_GCM_TAG_LENGTH = 128;
@@ -10841,11 +11196,7 @@ var security = {
10841
11196
  createSanitizer
10842
11197
  };
10843
11198
 
10844
- // core/memory/index.ts
10845
- init_suppress_idb_warning();
10846
-
10847
11199
  // core/memory/journal.ts
10848
- init_suppress_idb_warning();
10849
11200
  init_env();
10850
11201
  var g = globalThis;
10851
11202
  function namespace() {
@@ -11052,7 +11403,6 @@ var journal_default = journal;
11052
11403
  init_brain();
11053
11404
 
11054
11405
  // core/memory/knowledge-runtime.ts
11055
- init_suppress_idb_warning();
11056
11406
  init_knowledge();
11057
11407
  init_project_identity();
11058
11408
  init_user_paths();
@@ -11394,12 +11744,12 @@ var policy = {
11394
11744
  };
11395
11745
 
11396
11746
  // core/memory/entries.ts
11397
- init_suppress_idb_warning();
11398
11747
  init_env();
11399
11748
 
11400
11749
  // core/memory/durable-store.ts
11401
11750
  init_storage_coordinator();
11402
11751
  init_store_queue();
11752
+ init_text_encoding();
11403
11753
  var DurableStorageUnavailableError = class extends Error {
11404
11754
  static {
11405
11755
  __name(this, "DurableStorageUnavailableError");
@@ -11454,11 +11804,11 @@ var DurableMemoryStore = class {
11454
11804
  }
11455
11805
  let parsed;
11456
11806
  try {
11457
- parsed = JSON.parse(new TextDecoder().decode(raw));
11807
+ parsed = JSON.parse(decodeText(raw, { source: this.filePath }));
11458
11808
  } catch {
11459
11809
  try {
11460
11810
  const bakRaw = await fs2.readFile(`${this.filePath}.bak`);
11461
- parsed = JSON.parse(new TextDecoder().decode(bakRaw));
11811
+ parsed = JSON.parse(decodeText(bakRaw, { source: `${this.filePath}.bak` }));
11462
11812
  } catch {
11463
11813
  throw new DurableStorageUnavailableError(
11464
11814
  "Durable memory store is corrupt and no backup is available."
@@ -12266,7 +12616,6 @@ var context = {
12266
12616
  };
12267
12617
 
12268
12618
  // core/memory/acquire.ts
12269
- init_suppress_idb_warning();
12270
12619
  init_env();
12271
12620
  init_built_in_context();
12272
12621
  init_project_identity();
@@ -12440,16 +12789,16 @@ var profile = {
12440
12789
 
12441
12790
  // core/knowledge/note-types.ts
12442
12791
  async function sha256HexOfText(text) {
12443
- const encoder3 = new TextEncoder();
12444
- const bytes = encoder3.encode(text);
12792
+ const encoder4 = new TextEncoder();
12793
+ const bytes = encoder4.encode(text);
12445
12794
  const hashArray = await crypto.subtle.digest("SHA-256", bytes);
12446
12795
  return Array.from(new Uint8Array(hashArray)).map((b) => b.toString(16).padStart(2, "0")).join("");
12447
12796
  }
12448
12797
  __name(sha256HexOfText, "sha256HexOfText");
12449
12798
  async function buildNoteKnowledge(title, content, origin, tag) {
12450
12799
  const sha2563 = await sha256HexOfText(content);
12451
- const encoder3 = new TextEncoder();
12452
- const size = encoder3.encode(content).byteLength;
12800
+ const encoder4 = new TextEncoder();
12801
+ const size = encoder4.encode(content).byteLength;
12453
12802
  return {
12454
12803
  title,
12455
12804
  content,
@@ -13608,7 +13957,7 @@ var memory = {
13608
13957
  resetPolicyStoreCache();
13609
13958
  },
13610
13959
  // ----- namespaced surfaces -----
13611
- /** Local operation journal (namespaced). No-op substrate when sqlite/idb unavailable. */
13960
+ /** Local operation journal (namespaced). Persisted on `store`. */
13612
13961
  journal: journal_default,
13613
13962
  /** Configure the optional cloud-sync layer (namespace + provider). Chainable. */
13614
13963
  configure(opts) {
@@ -13982,7 +14331,6 @@ var global_default = {
13982
14331
  state: state,
13983
14332
  store: store$1,
13984
14333
  session: session,
13985
- idb,
13986
14334
  dispatch: dispatch,
13987
14335
  hlc: hlc,
13988
14336
  encryption,
@@ -13991,4 +14339,4 @@ var global_default = {
13991
14339
  continuity
13992
14340
  };
13993
14341
 
13994
- export { continuity, global_default as default, encryption, idb, memory, security };
14342
+ export { continuity, global_default as default, encryption, memory, security };