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.cjs CHANGED
@@ -31,18 +31,6 @@ var __export = (target, all) => {
31
31
  __defProp(target, name, { get: all[name], enumerable: true });
32
32
  };
33
33
 
34
- // core/suppress-idb-warning.ts
35
- var orig;
36
- var init_suppress_idb_warning = __esm({
37
- "core/suppress-idb-warning.ts"() {
38
- orig = console.warn.bind(console);
39
- console.warn = (...args) => {
40
- if (typeof args[0] === "string" && args[0].includes("IndexedDB is not available")) return;
41
- orig(...args);
42
- };
43
- }
44
- });
45
-
46
34
  // core/env.ts
47
35
  var DEV;
48
36
  var init_env = __esm({
@@ -118,6 +106,56 @@ var init_storage_paths = __esm({
118
106
  }
119
107
  });
120
108
 
109
+ // core/knowledge/text-encoding.ts
110
+ function detectBom(bytes) {
111
+ if (bytes.length >= 3 && bytes[0] === BOM_UTF8 && bytes[1] === 187 && bytes[2] === 191) {
112
+ return "utf-8";
113
+ }
114
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16LE_FIRST && bytes[1] === BOM_UTF16LE_SECOND) {
115
+ return "utf-16le";
116
+ }
117
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16BE_FIRST && bytes[1] === BOM_UTF16BE_SECOND) {
118
+ return "utf-16be";
119
+ }
120
+ return null;
121
+ }
122
+ function decodeText(bytes, options = {}) {
123
+ const bom = detectBom(bytes);
124
+ if (bom === "utf-16le" || bom === "utf-16be") {
125
+ throw new UnsupportedEncodingError(
126
+ `UTF-16 encoded content detected in ${options.source ?? "unknown"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`
127
+ );
128
+ }
129
+ let content = bytes;
130
+ if (bom === "utf-8") {
131
+ content = bytes.subarray(3);
132
+ }
133
+ return strictDecoder.decode(content);
134
+ }
135
+ var strictDecoder, UnsupportedEncodingError, BOM_UTF8, BOM_UTF16LE_FIRST, BOM_UTF16LE_SECOND, BOM_UTF16BE_FIRST, BOM_UTF16BE_SECOND;
136
+ var init_text_encoding = __esm({
137
+ "core/knowledge/text-encoding.ts"() {
138
+ new TextEncoder();
139
+ strictDecoder = new TextDecoder("utf-8", { fatal: true });
140
+ UnsupportedEncodingError = class extends Error {
141
+ static {
142
+ __name(this, "UnsupportedEncodingError");
143
+ }
144
+ constructor(message) {
145
+ super(message);
146
+ this.name = "UnsupportedEncodingError";
147
+ }
148
+ };
149
+ BOM_UTF8 = 239;
150
+ BOM_UTF16LE_FIRST = 255;
151
+ BOM_UTF16LE_SECOND = 254;
152
+ BOM_UTF16BE_FIRST = 254;
153
+ BOM_UTF16BE_SECOND = 255;
154
+ __name(detectBom, "detectBom");
155
+ __name(decodeText, "decodeText");
156
+ }
157
+ });
158
+
121
159
  // core/knowledge/storage-settings.ts
122
160
  var DOTMEM_STORAGE_SETTINGS_FILE_NAME, SETTINGS_MODES, projectRoot, findProjectSettingsFile, discoverProjectSettingsFilePath, resolveUserSettingsFilePath, invalidSettings, parseSettings, resolveSettingsEntry, readTextFile, readStorageSettings;
123
161
  var init_storage_settings = __esm({
@@ -249,15 +287,19 @@ function readDotMemStorageLocator() {
249
287
  const locatorFile = resolveLocatorFilePath(anchor);
250
288
  let raw;
251
289
  try {
252
- raw = fs2.readFileSync(locatorFile, "utf8");
290
+ raw = decodeText(fs2.readFileSync(locatorFile), { source: locatorFile });
253
291
  } catch (error) {
292
+ if (error instanceof UnsupportedEncodingError) {
293
+ throw new DotMemStorageLocationError(
294
+ `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.`
295
+ );
296
+ }
254
297
  const code = error?.code;
255
298
  if (code === "ENOENT") return null;
256
299
  throw new DotMemStorageLocationError(
257
300
  `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} cannot be read (${describeAccessFailure(error)}). No alternative location was selected automatically.`
258
301
  );
259
302
  }
260
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
261
303
  let parsed;
262
304
  try {
263
305
  parsed = JSON.parse(raw);
@@ -349,6 +391,7 @@ var DOTMEM_USER_ANCHOR_DIR_NAME, DOTMEM_STORAGE_LOCATOR_FILE_NAME, DOTMEM_STORAG
349
391
  var init_storage_location = __esm({
350
392
  "core/knowledge/storage-location.ts"() {
351
393
  init_storage_paths();
394
+ init_text_encoding();
352
395
  init_storage_settings();
353
396
  init_storage_paths();
354
397
  DOTMEM_USER_ANCHOR_DIR_NAME = ".dotmem";
@@ -1355,6 +1398,12 @@ var init_state = __esm({
1355
1398
  if (claim.sourceProject !== void 0 && !requiredText(claim.sourceProject)) {
1356
1399
  throw new Error(`Claim ${claim.id} has an invalid sourceProject`);
1357
1400
  }
1401
+ if (claim.check !== void 0) {
1402
+ const check = claim.check;
1403
+ 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)) {
1404
+ throw new Error(`Claim ${claim.id} has an invalid check`);
1405
+ }
1406
+ }
1358
1407
  return claim;
1359
1408
  }, "validateClaim");
1360
1409
  validateKnowledgeState = /* @__PURE__ */ __name((value) => {
@@ -1659,6 +1708,50 @@ var init_scope_eligibility = __esm({
1659
1708
  }
1660
1709
  });
1661
1710
 
1711
+ // core/knowledge/currentness.ts
1712
+ var asRecord, verifiedAtOf, findContestedIds, deriveCurrentness;
1713
+ var init_currentness = __esm({
1714
+ "core/knowledge/currentness.ts"() {
1715
+ asRecord = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0, "asRecord");
1716
+ verifiedAtOf = /* @__PURE__ */ __name((claim) => {
1717
+ const value = asRecord(claim.knowledge)?.verifiedAt;
1718
+ if (typeof value !== "string") return void 0;
1719
+ const parsed = Date.parse(value);
1720
+ return Number.isNaN(parsed) ? void 0 : parsed;
1721
+ }, "verifiedAtOf");
1722
+ findContestedIds = /* @__PURE__ */ __name((claims) => {
1723
+ const retracting = /* @__PURE__ */ new Map();
1724
+ for (const claim of claims) {
1725
+ if (claim.revision?.kind === "retracts" && claim.revision.claimIds.length > 0) {
1726
+ retracting.set(claim.id, new Set(claim.revision.claimIds));
1727
+ }
1728
+ }
1729
+ const contested = /* @__PURE__ */ new Set();
1730
+ for (const [id, targets] of retracting) {
1731
+ for (const target of targets) {
1732
+ if (retracting.get(target)?.has(id)) {
1733
+ contested.add(id);
1734
+ contested.add(target);
1735
+ }
1736
+ }
1737
+ }
1738
+ return contested;
1739
+ }, "findContestedIds");
1740
+ deriveCurrentness = /* @__PURE__ */ __name((claim, context2 = {}) => {
1741
+ const now2 = context2.now ?? Date.now();
1742
+ if (context2.contestedIds?.has(claim.id)) return "contested";
1743
+ if (claim.revision?.kind === "retracts") return "historical";
1744
+ if (context2.retractedIds?.has(claim.id)) return "historical";
1745
+ if (context2.supersededIds?.has(claim.id)) return "superseded";
1746
+ if (claim.expiresAt !== void 0 && now2 >= claim.expiresAt) return "expired";
1747
+ const verifiedAt = verifiedAtOf(claim);
1748
+ if (verifiedAt !== void 0) return "verified";
1749
+ if (claim.epistemicType === "verified") return "unverified";
1750
+ return "unknown-currentness";
1751
+ }, "deriveCurrentness");
1752
+ }
1753
+ });
1754
+
1662
1755
  // core/knowledge/discover.ts
1663
1756
  var diagnostic, DEFAULT_LIMITS, FIELD_ORDER, FIELD_WEIGHT, normalize, discoveryTerms, jsonText, fieldText, acquiredTime, isExpired, rankCandidate, discoverAcquiredExperience;
1664
1757
  var init_discover = __esm({
@@ -1666,6 +1759,7 @@ var init_discover = __esm({
1666
1759
  init_state();
1667
1760
  init_applicability();
1668
1761
  init_scope_eligibility();
1762
+ init_currentness();
1669
1763
  init_env();
1670
1764
  diagnostic = /* @__PURE__ */ __name((message) => {
1671
1765
  if (typeof process !== "undefined" && typeof process.stderr?.write === "function") {
@@ -1778,11 +1872,78 @@ var init_discover = __esm({
1778
1872
  throw new Error("Discovery maxCandidates must be a positive integer");
1779
1873
  }
1780
1874
  const queryTerms = discoveryTerms(situation);
1875
+ const offset = options.cursor?.offset ?? 0;
1876
+ if (!Number.isInteger(offset) || offset < 0) {
1877
+ throw new Error("Discovery cursor offset must be a non-negative integer");
1878
+ }
1879
+ if (options.cursor && options.cursor.knowledgeVersion !== validated.version) {
1880
+ return {
1881
+ knowledgeVersion: validated.version,
1882
+ depth,
1883
+ queryTerms,
1884
+ candidates: [],
1885
+ omissions: [],
1886
+ offset: 0,
1887
+ snapshotChanged: true
1888
+ };
1889
+ }
1781
1890
  const available = activeClaims(validated);
1891
+ const availableIds = new Set(available.map((claim) => claim.id));
1892
+ const retractedIds = /* @__PURE__ */ new Set();
1893
+ const supersededIds = /* @__PURE__ */ new Set();
1894
+ const contestedIds = findContestedIds(validated.claims);
1895
+ for (const claim of validated.claims) {
1896
+ if (claim.revision?.kind === "retracts") {
1897
+ for (const id of claim.revision.claimIds) retractedIds.add(id);
1898
+ }
1899
+ if (claim.revision?.kind === "supersedes") {
1900
+ for (const id of claim.revision.claimIds) supersededIds.add(id);
1901
+ }
1902
+ }
1903
+ const revisionOmissions = validated.claims.filter((claim) => !availableIds.has(claim.id)).map((claim) => {
1904
+ const retracted = retractedIds.has(claim.id);
1905
+ const superseded = supersededIds.has(claim.id);
1906
+ return {
1907
+ id: claim.id,
1908
+ reason: retracted ? "retracted" : superseded ? "superseded" : "retracted",
1909
+ gate: "revision-resolution",
1910
+ ...retracted || superseded ? {} : { detail: "the claim itself retracts prior knowledge and is kept as history" }
1911
+ };
1912
+ }).sort((left, right) => left.id.localeCompare(right.id));
1782
1913
  const scopeEligible = options.currentProjectId === void 0 ? available : available.filter((claim) => isScopeEligible(claim, options.currentProjectId, sources.get(claim.id)));
1783
1914
  const freshEligible = scopeEligible.filter((claim) => !isExpired(claim));
1915
+ const scopeEligibleIds = new Set(scopeEligible.map((claim) => claim.id));
1916
+ const scopeOmissions = available.filter((claim) => !scopeEligibleIds.has(claim.id)).map((claim) => {
1917
+ const owner = claimOwnerProject(claim, sources.get(claim.id));
1918
+ return {
1919
+ id: claim.id,
1920
+ reason: "scope",
1921
+ gate: "scope",
1922
+ detail: owner === void 0 ? "owner project could not be resolved" : `owned by project ${owner}`
1923
+ };
1924
+ }).sort((left, right) => left.id.localeCompare(right.id));
1925
+ const freshIds = new Set(freshEligible.map((claim) => claim.id));
1926
+ const freshnessOmissions = scopeEligible.filter((claim) => !freshIds.has(claim.id)).map((claim) => ({
1927
+ id: claim.id,
1928
+ reason: "expired",
1929
+ gate: "freshness",
1930
+ detail: `expired at ${new Date(claim.expiresAt).toISOString()}`
1931
+ })).sort((left, right) => left.id.localeCompare(right.id));
1784
1932
  const situationApplicability = deriveSituationApplicability(situation, options.facts);
1785
- const eligible = freshEligible.map((claim) => ({ claim, match: isEligibleByApplicability(claim, situationApplicability) })).filter((candidate) => candidate.match.eligible);
1933
+ const applicabilityMatches = new Map(
1934
+ freshEligible.map((claim) => [claim.id, isEligibleByApplicability(claim, situationApplicability)])
1935
+ );
1936
+ const eligible = freshEligible.map((claim) => ({ claim, match: applicabilityMatches.get(claim.id) })).filter((candidate) => candidate.match.eligible);
1937
+ const applicabilityOmissions = freshEligible.filter((claim) => !applicabilityMatches.get(claim.id).eligible).map((claim) => {
1938
+ const match = applicabilityMatches.get(claim.id);
1939
+ const mismatched = Object.entries(match.dimensions).filter(([, state4]) => state4 === "MISMATCH").map(([dimension]) => dimension);
1940
+ return {
1941
+ id: claim.id,
1942
+ reason: "applicability-mismatch",
1943
+ gate: "applicability",
1944
+ detail: `mismatching dimensions: ${mismatched.length > 0 ? mismatched.join(", ") : "none recorded"}`
1945
+ };
1946
+ }).sort((left, right) => left.id.localeCompare(right.id));
1786
1947
  if (DEV) {
1787
1948
  diagnostic(
1788
1949
  "[dotmem discovery] ACTIVE=" + JSON.stringify(
@@ -1794,12 +1955,15 @@ var init_discover = __esm({
1794
1955
  )
1795
1956
  );
1796
1957
  }
1958
+ const currentnessOf = /* @__PURE__ */ __name((claim) => deriveCurrentness(claim, { retractedIds, supersededIds, contestedIds }), "currentnessOf");
1797
1959
  if (queryTerms.length === 0) {
1798
- const baseline = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1960
+ const baselineAll = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1799
1961
  const leftTime = acquiredTime(left);
1800
1962
  const rightTime = acquiredTime(right);
1801
1963
  return rightTime - leftTime || Number(right.scope === "project") - Number(left.scope === "project") || left.id.localeCompare(right.id);
1802
- }).slice(0, maxCandidates);
1964
+ });
1965
+ const baseline = baselineAll.slice(offset, offset + maxCandidates);
1966
+ const limitOmissions = baselineAll.slice(offset + maxCandidates).map((claim) => ({ id: claim.id, reason: "limit", gate: "ranking" })).sort((left, right) => left.id.localeCompare(right.id));
1803
1967
  const baselineCandidates = baseline.map((claim) => {
1804
1968
  const explanation = {
1805
1969
  matchedTerms: [],
@@ -1812,7 +1976,8 @@ var init_discover = __esm({
1812
1976
  }
1813
1977
  return {
1814
1978
  claim,
1815
- explanation
1979
+ explanation,
1980
+ currentness: currentnessOf(claim)
1816
1981
  };
1817
1982
  });
1818
1983
  if (DEV) {
@@ -1825,10 +1990,18 @@ var init_discover = __esm({
1825
1990
  depth,
1826
1991
  queryTerms,
1827
1992
  situationApplicability,
1828
- candidates: baselineCandidates
1993
+ candidates: baselineCandidates,
1994
+ offset,
1995
+ omissions: [
1996
+ ...revisionOmissions,
1997
+ ...scopeOmissions,
1998
+ ...freshnessOmissions,
1999
+ ...applicabilityOmissions,
2000
+ ...limitOmissions
2001
+ ]
1829
2002
  };
1830
2003
  }
1831
- const candidates = eligible.map(
2004
+ const ranked = eligible.map(
1832
2005
  (candidate) => rankCandidate(
1833
2006
  candidate.claim,
1834
2007
  situation,
@@ -1840,16 +2013,40 @@ var init_discover = __esm({
1840
2013
  (candidate) => candidate !== null
1841
2014
  ).sort(
1842
2015
  (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)
1843
- ).slice(0, maxCandidates).map(({ claim, explanation }) => ({
2016
+ );
2017
+ const rankedIds = new Set(ranked.map((candidate) => candidate.claim.id));
2018
+ const rankingOmissions = [
2019
+ ...eligible.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2020
+ id: candidate.claim.id,
2021
+ reason: "no-term-match",
2022
+ gate: "ranking",
2023
+ detail: "passed every gate but shares no query term"
2024
+ })),
2025
+ ...ranked.slice(offset + maxCandidates).map((candidate) => ({
2026
+ id: candidate.claim.id,
2027
+ reason: "limit",
2028
+ gate: "ranking"
2029
+ }))
2030
+ ].sort((left, right) => left.id.localeCompare(right.id));
2031
+ const candidates = ranked.slice(offset, offset + maxCandidates).map(({ claim, explanation }) => ({
1844
2032
  claim,
1845
- explanation
2033
+ explanation,
2034
+ currentness: currentnessOf(claim)
1846
2035
  }));
1847
2036
  return {
1848
2037
  knowledgeVersion: validated.version,
1849
2038
  depth,
1850
2039
  queryTerms,
1851
2040
  situationApplicability,
1852
- candidates
2041
+ candidates,
2042
+ offset,
2043
+ omissions: [
2044
+ ...revisionOmissions,
2045
+ ...scopeOmissions,
2046
+ ...freshnessOmissions,
2047
+ ...applicabilityOmissions,
2048
+ ...rankingOmissions
2049
+ ]
1853
2050
  };
1854
2051
  }, "discoverAcquiredExperience");
1855
2052
  }
@@ -2906,7 +3103,7 @@ var init_policy_store = __esm({
2906
3103
  });
2907
3104
 
2908
3105
  // core/knowledge/acquisition-limits.ts
2909
- var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder, serializedBytes, measureKnowledge, checkAcquireLimits;
3106
+ var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder2, serializedBytes, measureKnowledge, checkAcquireLimits;
2910
3107
  var init_acquisition_limits = __esm({
2911
3108
  "core/knowledge/acquisition-limits.ts"() {
2912
3109
  MEMORY_ACQUIRE_LIMITS = Object.freeze({
@@ -2965,10 +3162,10 @@ var init_acquisition_limits = __esm({
2965
3162
  this.name = "MemoryAcquireDuplicateClaimError";
2966
3163
  }
2967
3164
  };
2968
- encoder = new TextEncoder();
3165
+ encoder2 = new TextEncoder();
2969
3166
  serializedBytes = /* @__PURE__ */ __name((value) => {
2970
3167
  const json = JSON.stringify(value);
2971
- return json === void 0 ? 0 : encoder.encode(json).length;
3168
+ return json === void 0 ? 0 : encoder2.encode(json).length;
2972
3169
  }, "serializedBytes");
2973
3170
  measureKnowledge = /* @__PURE__ */ __name((knowledge) => {
2974
3171
  const claimBytes = serializedBytes(knowledge);
@@ -3062,7 +3259,7 @@ var init_context_constants = __esm({
3062
3259
  });
3063
3260
 
3064
3261
  // core/knowledge/project.ts
3065
- var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_MAX_CHARACTERS, projectCandidate, renderHeader, renderExperience, renderText, projectDiscoveredExperience;
3262
+ 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;
3066
3263
  var init_project = __esm({
3067
3264
  "core/knowledge/project.ts"() {
3068
3265
  init_state();
@@ -3087,9 +3284,29 @@ var init_project = __esm({
3087
3284
  ...claim.provenance ? { provenance: claim.provenance } : {},
3088
3285
  ...claim.acquiredAt ? { acquiredAt: claim.acquiredAt } : {},
3089
3286
  ...claim.revision ? { revision: claim.revision } : {},
3090
- ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {}
3287
+ ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {},
3288
+ ...candidate.currentness ? { currentness: candidate.currentness } : {}
3091
3289
  });
3092
3290
  }, "projectCandidate");
3291
+ GIST_MAX_LENGTH = 80;
3292
+ GIST_KEYS = ["gist", "summary", "statement", "title", "reason", "principle", "finding", "detail"];
3293
+ MANIFEST_ID_LIMIT = 40;
3294
+ deriveGist = /* @__PURE__ */ __name((knowledge) => {
3295
+ if (typeof knowledge === "string") {
3296
+ return knowledge.length > GIST_MAX_LENGTH ? `${knowledge.slice(0, GIST_MAX_LENGTH)}\u2026` : knowledge;
3297
+ }
3298
+ if (knowledge && typeof knowledge === "object" && !Array.isArray(knowledge)) {
3299
+ const obj = knowledge;
3300
+ for (const key of GIST_KEYS) {
3301
+ const value = obj[key];
3302
+ if (typeof value === "string" && value.length > 0) {
3303
+ return value.length > GIST_MAX_LENGTH ? `${value.slice(0, GIST_MAX_LENGTH)}\u2026` : value;
3304
+ }
3305
+ }
3306
+ }
3307
+ const str = JSON.stringify(knowledge);
3308
+ return str.length > GIST_MAX_LENGTH ? `${str.slice(0, GIST_MAX_LENGTH)}\u2026` : str;
3309
+ }, "deriveGist");
3093
3310
  renderHeader = /* @__PURE__ */ __name((knowledgeVersion, totalCandidates) => {
3094
3311
  const lines = [
3095
3312
  `DOTMEM STORAGE: ${resolveUserDotMemPath()}`,
@@ -3115,27 +3332,70 @@ var init_project = __esm({
3115
3332
  evidence.supports ?? null
3116
3333
  ]),
3117
3334
  ...experience.epistemicType ? { epistemic: experience.epistemicType } : {},
3335
+ ...experience.currentness ? { currentness: experience.currentness } : {},
3118
3336
  ...experience.provenance ? { provenance: [experience.provenance.source, experience.provenance.detail ?? null] } : {},
3119
3337
  ...experience.acquiredAt ? { acquiredAt: experience.acquiredAt } : {},
3120
3338
  ...experience.revision ? { revision: experience.revision } : {},
3121
3339
  ...experience.sourceId ? { source: experience.sourceId } : {}
3122
3340
  }), "renderExperience");
3123
- renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates) => `${header}${experiences.length ? `
3124
- ${experiences.map(renderExperience).join("\n")}` : ""}
3125
- OMITTED:${omittedCandidates}`, "renderText");
3341
+ renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, render = renderExperience, currentnessSummary) => {
3342
+ const lines = [header];
3343
+ if (experiences.length > 0) lines.push(...experiences.map(render));
3344
+ lines.push(`OMITTED:${omittedCandidates}`);
3345
+ if (manifest && manifest.byReason.length > 0) {
3346
+ lines.push(`OMITTED_BY_REASON:${manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`);
3347
+ }
3348
+ if (manifest && manifest.items.length > 0) {
3349
+ lines.push(`OMITTED_IDS:${manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`);
3350
+ if (manifest.items.length > MANIFEST_ID_LIMIT) {
3351
+ lines.push(`OMITTED_IDS_TRUNCATED:${manifest.items.length - MANIFEST_ID_LIMIT}`);
3352
+ }
3353
+ }
3354
+ if (currentnessSummary) {
3355
+ lines.push(`CURRENTNESS:${currentnessSummary}`);
3356
+ }
3357
+ return lines.join("\n");
3358
+ }, "renderText");
3359
+ byteLength = /* @__PURE__ */ __name((value) => new TextEncoder().encode(value).length, "byteLength");
3360
+ summarizeOmissions = /* @__PURE__ */ __name((items) => {
3361
+ const counts = /* @__PURE__ */ new Map();
3362
+ for (const item of items) counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
3363
+ return [...counts.entries()].map(([reason, count]) => ({ reason, count })).sort((left, right) => left.reason.localeCompare(right.reason));
3364
+ }, "summarizeOmissions");
3365
+ renderManifestFitting = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, maxCharacters, render, currentnessSummary) => {
3366
+ const full = renderText(header, experiences, omittedCandidates, manifest, render, currentnessSummary);
3367
+ if (byteLength(full) <= maxCharacters) return full;
3368
+ const withoutIds = { ...manifest, items: [] };
3369
+ return renderText(header, experiences, omittedCandidates, withoutIds, render, currentnessSummary);
3370
+ }, "renderManifestFitting");
3371
+ renderCompactExperience = /* @__PURE__ */ __name((experience) => JSON.stringify({
3372
+ id: experience.id,
3373
+ status: "candidate",
3374
+ gist: deriveGist(experience.experience),
3375
+ epistemic: experience.epistemicType ?? null,
3376
+ currentness: experience.currentness ?? null,
3377
+ ...experience.revision ? { revision: experience.revision.kind } : {}
3378
+ }), "renderCompactExperience");
3126
3379
  projectDiscoveredExperience = /* @__PURE__ */ __name((discovery, options = {}) => {
3127
3380
  if (!discovery || !Number.isInteger(discovery.knowledgeVersion) || discovery.knowledgeVersion < 0 || !Array.isArray(discovery.candidates)) {
3128
3381
  throw new Error("Valid DiscoveryResult is required for context projection");
3129
3382
  }
3130
3383
  const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES;
3131
3384
  const maxCharacters = options.maxCharacters ?? DEFAULT_MAX_CHARACTERS;
3385
+ const format = options.format ?? "compact";
3386
+ if (format !== "compact" && format !== "standard" && format !== "full") {
3387
+ throw new Error("Projection format must be compact, standard or full");
3388
+ }
3132
3389
  if (!Number.isInteger(maxCandidates) || maxCandidates < 1) throw new Error("Projection maxCandidates must be a positive integer");
3133
3390
  if (!Number.isInteger(maxCharacters) || maxCharacters < MIN_MAX_CHARACTERS) {
3134
3391
  throw new Error(`Projection maxCharacters must be an integer of at least ${MIN_MAX_CHARACTERS}`);
3135
3392
  }
3136
- const totalCandidates = discovery.candidates.length;
3393
+ const render = /* @__PURE__ */ __name((experience) => format === "compact" ? renderCompactExperience(experience) : renderExperience(experience), "render");
3394
+ const gateOmissions = discovery.omissions ?? [];
3395
+ const totalCandidates = discovery.candidates.length + gateOmissions.length;
3137
3396
  const header = renderHeader(discovery.knowledgeVersion, totalCandidates);
3138
- if (renderText(header, [], totalCandidates).length > maxCharacters) {
3397
+ const emptyManifest = { considered: totalCandidates, included: 0, items: [], byReason: [] };
3398
+ if (byteLength(renderText(header, [], totalCandidates, emptyManifest)) > maxCharacters) {
3139
3399
  throw new Error("Projection maxCharacters is too small for the projection envelope");
3140
3400
  }
3141
3401
  const experiences = [];
@@ -3144,12 +3404,49 @@ OMITTED:${omittedCandidates}`, "renderText");
3144
3404
  const projected = projectCandidate(candidate);
3145
3405
  const possibleExperiences = [...experiences, projected];
3146
3406
  const possibleOmitted = totalCandidates - possibleExperiences.length;
3147
- if (renderText(header, possibleExperiences, possibleOmitted).length <= maxCharacters) {
3407
+ const candidateManifest = {
3408
+ considered: totalCandidates,
3409
+ included: possibleExperiences.length,
3410
+ items: gateOmissions,
3411
+ byReason: summarizeOmissions(gateOmissions)
3412
+ };
3413
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, candidateManifest, render)) <= maxCharacters) {
3414
+ experiences.push(projected);
3415
+ continue;
3416
+ }
3417
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, void 0, render)) <= maxCharacters) {
3148
3418
  experiences.push(projected);
3149
3419
  }
3150
3420
  }
3421
+ const projectedIds = new Set(experiences.map((experience) => experience.id));
3422
+ const budgetOmissions = discovery.candidates.filter((candidate) => !projectedIds.has(candidate.claim.id)).map((candidate) => ({ id: candidate.claim.id, reason: "budget", gate: "projection" }));
3423
+ const items = [...gateOmissions, ...budgetOmissions];
3151
3424
  const omittedCandidates = totalCandidates - experiences.length;
3152
- const text = renderText(header, experiences, omittedCandidates);
3425
+ const manifest = {
3426
+ considered: totalCandidates,
3427
+ included: experiences.length,
3428
+ items,
3429
+ byReason: summarizeOmissions(items)
3430
+ };
3431
+ const currentnessCounts = /* @__PURE__ */ new Map();
3432
+ for (const experience of experiences) {
3433
+ if (experience.currentness) {
3434
+ currentnessCounts.set(
3435
+ experience.currentness,
3436
+ (currentnessCounts.get(experience.currentness) ?? 0) + 1
3437
+ );
3438
+ }
3439
+ }
3440
+ const currentnessSummary = currentnessCounts.size > 0 ? [...currentnessCounts.entries()].map(([state3, count]) => `${state3}=${count}`).join(",") : void 0;
3441
+ const text = renderManifestFitting(
3442
+ header,
3443
+ experiences,
3444
+ omittedCandidates,
3445
+ manifest,
3446
+ maxCharacters,
3447
+ render,
3448
+ currentnessSummary
3449
+ );
3153
3450
  return {
3154
3451
  format: FORMAT,
3155
3452
  status: STATUS,
@@ -3158,6 +3455,7 @@ OMITTED:${omittedCandidates}`, "renderText");
3158
3455
  totalCandidates,
3159
3456
  omittedCandidates,
3160
3457
  experiences,
3458
+ manifest,
3161
3459
  text
3162
3460
  };
3163
3461
  }, "projectDiscoveredExperience");
@@ -3195,7 +3493,7 @@ var init_language_detect = __esm({
3195
3493
  var CANONICAL_KINDS, validateKind, buildClaimRecord;
3196
3494
  var init_claim_record = __esm({
3197
3495
  "core/knowledge/claim-record.ts"() {
3198
- CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note"];
3496
+ CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note", "rule"];
3199
3497
  validateKind = /* @__PURE__ */ __name((kind) => {
3200
3498
  if (!CANONICAL_KINDS.includes(kind)) {
3201
3499
  throw new Error(
@@ -4426,8 +4724,8 @@ var init_browser = __esm({
4426
4724
  this.p = null;
4427
4725
  }
4428
4726
  };
4429
- Unzip2.prototype.register = function(decoder2) {
4430
- this.o[decoder2.compression] = decoder2;
4727
+ Unzip2.prototype.register = function(decoder) {
4728
+ this.o[decoder.compression] = decoder;
4431
4729
  };
4432
4730
  return Unzip2;
4433
4731
  })();
@@ -4447,6 +4745,15 @@ function encodeMemFile(stateValue, preserved) {
4447
4745
  if (!map.claim.includes("kind")) {
4448
4746
  map.claim.push("kind");
4449
4747
  }
4748
+ if (!map.claim.includes("expires-at")) {
4749
+ map.claim.push("expires-at");
4750
+ }
4751
+ if (!map.claim.includes("bootstrap-priority")) {
4752
+ map.claim.push("bootstrap-priority");
4753
+ }
4754
+ if (!map.claim.includes("check")) {
4755
+ map.claim.push("check");
4756
+ }
4450
4757
  const indexes = Object.fromEntries(Object.keys(expectedFields).map((name) => [name, fieldIndexes(map, name)]));
4451
4758
  validateVocabulary(map.epistemicType, epistemicTypes, "epistemicType");
4452
4759
  validateVocabulary(map.revisionKind, revisionKinds, "revisionKind");
@@ -4496,6 +4803,15 @@ function encodeMemFile(stateValue, preserved) {
4496
4803
  if (indexes.claim.has("kind")) {
4497
4804
  putOptional(record, indexes.claim, "kind", claim.kind ?? void 0, original !== void 0);
4498
4805
  }
4806
+ if (indexes.claim.has("expires-at")) {
4807
+ putOptional(record, indexes.claim, "expires-at", claim.expiresAt, original !== void 0);
4808
+ }
4809
+ if (indexes.claim.has("bootstrap-priority")) {
4810
+ putOptional(record, indexes.claim, "bootstrap-priority", claim.bootstrapPriority, original !== void 0);
4811
+ }
4812
+ if (indexes.claim.has("check")) {
4813
+ putOptional(record, indexes.claim, "check", claim.check, original !== void 0);
4814
+ }
4499
4815
  return original ? record : trimRecord(record);
4500
4816
  }, "encodeClaim");
4501
4817
  const stateRecord = structuredClone(preserved?.data ?? []);
@@ -4564,8 +4880,37 @@ function decodeMemDocument(value) {
4564
4880
  const scope = optionalGet(record, indexes.claim, "scope");
4565
4881
  const sourceProject = optionalGet(record, indexes.claim, "source-project");
4566
4882
  const kindValue = optionalGet(record, indexes.claim, "kind");
4883
+ const expiresAtValue = indexes.claim.has("expires-at") ? optionalGet(record, indexes.claim, "expires-at") : void 0;
4884
+ const bootstrapPriorityValue = indexes.claim.has("bootstrap-priority") ? optionalGet(record, indexes.claim, "bootstrap-priority") : void 0;
4885
+ const checkValue = indexes.claim.has("check") ? optionalGet(record, indexes.claim, "check") : void 0;
4567
4886
  if (epistemicIndex !== void 0 && (!Number.isInteger(epistemicIndex) || epistemicIndex < 0 || epistemicIndex >= epistemic.length)) throw new Error("Invalid .mem epistemic value");
4568
4887
  if (kindIndex !== void 0 && (!Number.isInteger(kindIndex) || kindIndex < 0 || kindIndex >= revisions.length)) throw new Error("Invalid .mem revision value");
4888
+ if (expiresAtValue !== void 0 && (!Number.isInteger(expiresAtValue) || expiresAtValue < 0)) {
4889
+ throw new Error("Invalid .mem expiresAt value");
4890
+ }
4891
+ if (bootstrapPriorityValue !== void 0 && !bootstrapPriorities.includes(bootstrapPriorityValue)) {
4892
+ throw new Error("Invalid .mem bootstrapPriority value");
4893
+ }
4894
+ let check;
4895
+ if (checkValue !== void 0) {
4896
+ if (!checkValue || typeof checkValue !== "object" || Array.isArray(checkValue)) {
4897
+ throw new Error("Invalid .mem check record");
4898
+ }
4899
+ const checkRecord = checkValue;
4900
+ const description = checkRecord.description;
4901
+ if (typeof description !== "undefined" && typeof description !== "string") {
4902
+ throw new Error("Invalid .mem check record");
4903
+ }
4904
+ if (checkRecord.kind !== "regex" || typeof checkRecord.pattern !== "string" || checkRecord.pattern.length === 0 || !checkTargets.includes(checkRecord.on)) {
4905
+ throw new Error("Invalid .mem check record");
4906
+ }
4907
+ check = {
4908
+ kind: "regex",
4909
+ pattern: checkRecord.pattern,
4910
+ on: checkRecord.on,
4911
+ ...typeof description === "string" ? { description } : {}
4912
+ };
4913
+ }
4569
4914
  const understoodEpistemic = typeof epistemicIndex === "number" && epistemicTypes.includes(epistemic[epistemicIndex]) ? epistemic[epistemicIndex] : void 0;
4570
4915
  const understoodRevision = typeof kindIndex === "number" && revisionKinds.includes(revisions[kindIndex]);
4571
4916
  const claim = {
@@ -4590,6 +4935,9 @@ function decodeMemDocument(value) {
4590
4935
  } : {},
4591
4936
  ...scope === void 0 ? {} : { scope },
4592
4937
  ...sourceProject === void 0 ? {} : { sourceProject },
4938
+ ...expiresAtValue === void 0 ? {} : { expiresAt: expiresAtValue },
4939
+ ...bootstrapPriorityValue === void 0 ? {} : { bootstrapPriority: bootstrapPriorityValue },
4940
+ ...check === void 0 ? {} : { check },
4593
4941
  ...claimKinds.includes(kindValue) ? { kind: kindValue } : {}
4594
4942
  };
4595
4943
  return validateClaim(claim);
@@ -4599,7 +4947,7 @@ function decodeMemDocument(value) {
4599
4947
  preserved: { map: structuredClone(map), data: structuredClone(stateRecord) }
4600
4948
  };
4601
4949
  }
4602
- 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;
4950
+ 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;
4603
4951
  var init_mem_codec = __esm({
4604
4952
  "core/knowledge/mem-codec.ts"() {
4605
4953
  init_state();
@@ -4616,7 +4964,9 @@ var init_mem_codec = __esm({
4616
4964
  };
4617
4965
  epistemicTypes = ["observed", "inferred", "human-stated", "verified"];
4618
4966
  revisionKinds = ["refines", "supersedes", "retracts"];
4619
- claimKinds = ["experience", "agent", "relationship", "logic", "note"];
4967
+ claimKinds = ["experience", "agent", "relationship", "logic", "note", "rule"];
4968
+ bootstrapPriorities = ["P1", "P2", "P3", "P4", "P5", "unclassified"];
4969
+ checkTargets = ["staged", "committed", "working-tree"];
4620
4970
  isJsonValue2 = /* @__PURE__ */ __name((value) => {
4621
4971
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
4622
4972
  if (typeof value === "number") return Number.isFinite(value);
@@ -4690,14 +5040,14 @@ async function encodeMemPackage(state3, semantic, preservedPackage) {
4690
5040
  return encodePackage(state3, semantic, preservedPackage);
4691
5041
  }
4692
5042
  async function decodeMemArtifact(input) {
4693
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
5043
+ const bytes = typeof input === "string" ? encoder3.encode(input) : input;
4694
5044
  if (isZip(bytes)) {
4695
5045
  const { parts: _parts, integrity: _integrity, ...artifact } = await decodePackage(bytes);
4696
5046
  return artifact;
4697
5047
  }
4698
5048
  let value;
4699
5049
  try {
4700
- value = JSON.parse(decoder.decode(bytes).replace(/^\uFEFF/, ""));
5050
+ value = JSON.parse(decodeText(bytes));
4701
5051
  } catch (error) {
4702
5052
  throw new MemArtifactError("corrupt", `Unsupported or corrupt MEM artifact: ${error.message}`);
4703
5053
  }
@@ -4710,11 +5060,12 @@ async function decodeMemArtifact(input) {
4710
5060
  throw new MemArtifactError(message.startsWith("Unsupported") ? "unsupported" : "invalid", message);
4711
5061
  }
4712
5062
  }
4713
- 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;
5063
+ 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;
4714
5064
  var init_mem_package = __esm({
4715
5065
  "core/knowledge/mem-package.ts"() {
4716
5066
  init_browser();
4717
5067
  init_mem_codec();
5068
+ init_text_encoding();
4718
5069
  MEM_PACKAGE_FORMAT = "dotmem.package";
4719
5070
  MEM_PACKAGE_FORMAT_LEGACY = "memorio.package";
4720
5071
  MEM_PACKAGE_VERSION = 1;
@@ -4738,8 +5089,7 @@ var init_mem_package = __esm({
4738
5089
  DATA_PATH = "memory/data.json";
4739
5090
  INTEGRITY_PATH = "security/integrity.json";
4740
5091
  requiredParts = [MANIFEST_PATH, MAP_PATH, DATA_PATH];
4741
- encoder2 = new TextEncoder();
4742
- decoder = new TextDecoder("utf-8", { fatal: true });
5092
+ encoder3 = new TextEncoder();
4743
5093
  MemArtifactError = class extends Error {
4744
5094
  constructor(code, message) {
4745
5095
  super(message);
@@ -4758,7 +5108,7 @@ var init_mem_package = __esm({
4758
5108
  }
4759
5109
  return value;
4760
5110
  }, "stableValue");
4761
- jsonBytes = /* @__PURE__ */ __name((value) => encoder2.encode(`${JSON.stringify(stableValue(value), null, 2)}
5111
+ jsonBytes = /* @__PURE__ */ __name((value) => encoder3.encode(`${JSON.stringify(stableValue(value), null, 2)}
4762
5112
  `), "jsonBytes");
4763
5113
  sha256 = /* @__PURE__ */ __name(async (data) => {
4764
5114
  if (!globalThis.crypto?.subtle) throw new MemArtifactError("unsupported", "SHA-256 is unavailable in this runtime");
@@ -4767,7 +5117,7 @@ var init_mem_package = __esm({
4767
5117
  }, "sha256");
4768
5118
  parseJson = /* @__PURE__ */ __name((bytes, path2) => {
4769
5119
  try {
4770
- return JSON.parse(decoder.decode(bytes));
5120
+ return JSON.parse(decodeText(bytes));
4771
5121
  } catch (error) {
4772
5122
  throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path2}: ${error.message}`);
4773
5123
  }
@@ -4937,10 +5287,12 @@ var init_mem_package = __esm({
4937
5287
  });
4938
5288
 
4939
5289
  // core/storage-coordinator/index.ts
4940
- var nodeFs4, withStorageLock, readStorageGeneration, writeStorageGeneration;
5290
+ var nodeFs4, heldLocks, withStorageLock, readStorageGeneration, writeStorageGeneration;
4941
5291
  var init_storage_coordinator = __esm({
4942
5292
  "core/storage-coordinator/index.ts"() {
5293
+ init_text_encoding();
4943
5294
  nodeFs4 = /* @__PURE__ */ __name(async () => import('fs/promises'), "nodeFs");
5295
+ heldLocks = /* @__PURE__ */ new Map();
4944
5296
  withStorageLock = /* @__PURE__ */ __name(async (directoryPath, operationOrOptions, operation, _options = {}) => {
4945
5297
  const opts = typeof operationOrOptions === "function" ? operation ?? {} : operationOrOptions ?? {};
4946
5298
  const op = typeof operationOrOptions === "function" ? operationOrOptions : operation;
@@ -4950,6 +5302,15 @@ var init_storage_coordinator = __esm({
4950
5302
  const lockPath = `${directoryPath}/${lockName}`;
4951
5303
  const fs2 = await nodeFs4();
4952
5304
  const started = Date.now();
5305
+ const heldDepth = heldLocks.get(lockPath) ?? 0;
5306
+ if (heldDepth > 0) {
5307
+ heldLocks.set(lockPath, heldDepth + 1);
5308
+ try {
5309
+ return await op();
5310
+ } finally {
5311
+ heldLocks.set(lockPath, heldDepth);
5312
+ }
5313
+ }
4953
5314
  await fs2.mkdir(directoryPath, { recursive: true });
4954
5315
  while (true) {
4955
5316
  try {
@@ -4963,8 +5324,8 @@ var init_storage_coordinator = __esm({
4963
5324
  let stale = false;
4964
5325
  let processDead = false;
4965
5326
  try {
4966
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
4967
- const parsed = JSON.parse(raw);
5327
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5328
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
4968
5329
  const ageStale = typeof parsed.createdAt === "number" && Date.now() - parsed.createdAt > staleMs;
4969
5330
  if (typeof parsed.pid === "number") {
4970
5331
  try {
@@ -5001,17 +5362,19 @@ var init_storage_coordinator = __esm({
5001
5362
  }
5002
5363
  let token = "";
5003
5364
  try {
5004
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5005
- token = JSON.parse(raw).token ?? "";
5365
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5366
+ token = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` })).token ?? "";
5006
5367
  } catch {
5007
5368
  token = "";
5008
5369
  }
5009
5370
  try {
5371
+ heldLocks.set(lockPath, 1);
5010
5372
  return await op();
5011
5373
  } finally {
5374
+ heldLocks.delete(lockPath);
5012
5375
  try {
5013
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5014
- const parsed = JSON.parse(raw);
5376
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5377
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
5015
5378
  if (parsed.token === token && token) {
5016
5379
  await fs2.rm(lockPath, { recursive: true, force: true });
5017
5380
  }
@@ -5022,8 +5385,8 @@ var init_storage_coordinator = __esm({
5022
5385
  readStorageGeneration = /* @__PURE__ */ __name(async (directoryPath) => {
5023
5386
  const fs2 = await nodeFs4();
5024
5387
  try {
5025
- const raw = await fs2.readFile(`${directoryPath}/.storage.generation`, "utf8");
5026
- const value = Number(raw.trim());
5388
+ const raw = await fs2.readFile(`${directoryPath}/.storage.generation`);
5389
+ const value = Number(decodeText(raw, { source: `${directoryPath}/.storage.generation` }).trim());
5027
5390
  return Number.isFinite(value) && value >= 0 ? value : 0;
5028
5391
  } catch {
5029
5392
  return 0;
@@ -5511,12 +5874,11 @@ function readJsonFile(path2) {
5511
5874
  if (!fs2) return null;
5512
5875
  let raw;
5513
5876
  try {
5514
- raw = fs2.readFileSync(path2, "utf8");
5877
+ raw = decodeText(fs2.readFileSync(path2), { source: path2 });
5515
5878
  } catch {
5516
5879
  return null;
5517
5880
  }
5518
5881
  if (typeof raw !== "string") return null;
5519
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
5520
5882
  try {
5521
5883
  return JSON.parse(raw);
5522
5884
  } catch {
@@ -5640,6 +6002,7 @@ var init_user_language = __esm({
5640
6002
  "core/knowledge/user-language.ts"() {
5641
6003
  init_user_paths();
5642
6004
  init_storage_paths();
6005
+ init_text_encoding();
5643
6006
  USER_LANGUAGE_FILE_NAME = "language.json";
5644
6007
  USER_LANGUAGE_PREFERENCE_FILE_NAME = "user-language.json";
5645
6008
  LANGUAGE_PREFERENCE_FILE_NAME = "language-preference.json";
@@ -9363,10 +9726,13 @@ var init_staging = __esm({
9363
9726
  epistemicType: sanitizedClaim.epistemicType,
9364
9727
  provenance: sanitizedClaim.provenance,
9365
9728
  acquiredAt: sanitizedClaim.acquiredAt,
9729
+ ...sanitizedClaim.expiresAt === void 0 ? {} : { expiresAt: sanitizedClaim.expiresAt },
9730
+ ...sanitizedClaim.bootstrapPriority === void 0 ? {} : { bootstrapPriority: sanitizedClaim.bootstrapPriority },
9366
9731
  revision,
9367
9732
  scope,
9368
9733
  sourceProject,
9369
- kind
9734
+ kind,
9735
+ ...sanitizedClaim.check === void 0 ? {} : { check: sanitizedClaim.check }
9370
9736
  });
9371
9737
  await withStoreQueue(acquisitionStoreKey(kind, scope, sourceProject), async () => {
9372
9738
  const state3 = await target.runtime.select([]);
@@ -9614,19 +9980,19 @@ var init_incidents = __esm({
9614
9980
  }
9615
9981
  });
9616
9982
 
9617
- // core/knowledge/rules-loader.ts
9618
- var init_rules_loader = __esm({
9619
- "core/knowledge/rules-loader.ts"() {
9620
- init_state();
9621
- }
9622
- });
9623
-
9624
9983
  // core/knowledge/violations.ts
9625
9984
  var init_violations = __esm({
9626
9985
  "core/knowledge/violations.ts"() {
9627
9986
  init_user_paths();
9628
9987
  }
9629
9988
  });
9989
+ var init_rules_loader = __esm({
9990
+ "core/knowledge/rules-loader.ts"() {
9991
+ init_state();
9992
+ init_user_paths();
9993
+ init_violations();
9994
+ }
9995
+ });
9630
9996
 
9631
9997
  // core/knowledge/session.ts
9632
9998
  var init_session = __esm({
@@ -10087,8 +10453,8 @@ function loadBuiltInContext() {
10087
10453
  for (const candidate of candidates) {
10088
10454
  if (!fs__default.default.existsSync(candidate)) continue;
10089
10455
  try {
10090
- const raw = fs__default.default.readFileSync(candidate, "utf8");
10091
- const parsed = JSON.parse(raw);
10456
+ const raw = fs__default.default.readFileSync(candidate);
10457
+ const parsed = JSON.parse(decodeText(raw, { source: candidate }));
10092
10458
  const artifact = validateArtifact(parsed);
10093
10459
  cached = artifact;
10094
10460
  cachedStatus = {
@@ -10145,6 +10511,7 @@ function assertBuiltInContextAvailable() {
10145
10511
  var BUILT_IN_CONTEXT_FORMAT, BUILT_IN_CONTEXT_FORMAT_VERSION, cached, cachedStatus, _artifactPathOverride;
10146
10512
  var init_built_in_context = __esm({
10147
10513
  "core/knowledge/built-in-context.ts"() {
10514
+ init_text_encoding();
10148
10515
  BUILT_IN_CONTEXT_FORMAT = "dotmem.built-in-context";
10149
10516
  BUILT_IN_CONTEXT_FORMAT_VERSION = 1;
10150
10517
  cached = null;
@@ -10204,6 +10571,7 @@ var init_knowledge = __esm({
10204
10571
  init_state();
10205
10572
  init_select();
10206
10573
  init_discover();
10574
+ init_currentness();
10207
10575
  init_project();
10208
10576
  init_applicability();
10209
10577
  init_policy();
@@ -10311,7 +10679,6 @@ function _inferConfidence(claim) {
10311
10679
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, LogicEngine, logic, logic_default;
10312
10680
  var init_logic = __esm({
10313
10681
  "core/logic/index.ts"() {
10314
- init_suppress_idb_warning();
10315
10682
  init_knowledge();
10316
10683
  init_mem_repository();
10317
10684
  init_acquisition_boundary();
@@ -10579,18 +10946,6 @@ Do not store secrets unless dotmem explicitly supports secure secret storage.
10579
10946
  }
10580
10947
  });
10581
10948
 
10582
- // global.ts
10583
- init_suppress_idb_warning();
10584
-
10585
- // core/idb.ts
10586
- var idb = {
10587
- db: {},
10588
- table: {},
10589
- data: {},
10590
- _disabled: true,
10591
- _warning: "IndexedDB is not available in this environment. Use dotmem store or session for persistence."
10592
- };
10593
-
10594
10949
  // core/encryption/index.ts
10595
10950
  var PBKDF2_ITERATIONS = 6e5;
10596
10951
  var AES_GCM_TAG_LENGTH = 128;
@@ -10851,11 +11206,7 @@ var security = {
10851
11206
  createSanitizer
10852
11207
  };
10853
11208
 
10854
- // core/memory/index.ts
10855
- init_suppress_idb_warning();
10856
-
10857
11209
  // core/memory/journal.ts
10858
- init_suppress_idb_warning();
10859
11210
  init_env();
10860
11211
  var g = globalThis;
10861
11212
  function namespace() {
@@ -11062,7 +11413,6 @@ var journal_default = journal;
11062
11413
  init_brain();
11063
11414
 
11064
11415
  // core/memory/knowledge-runtime.ts
11065
- init_suppress_idb_warning();
11066
11416
  init_knowledge();
11067
11417
  init_project_identity();
11068
11418
  init_user_paths();
@@ -11404,12 +11754,12 @@ var policy = {
11404
11754
  };
11405
11755
 
11406
11756
  // core/memory/entries.ts
11407
- init_suppress_idb_warning();
11408
11757
  init_env();
11409
11758
 
11410
11759
  // core/memory/durable-store.ts
11411
11760
  init_storage_coordinator();
11412
11761
  init_store_queue();
11762
+ init_text_encoding();
11413
11763
  var DurableStorageUnavailableError = class extends Error {
11414
11764
  static {
11415
11765
  __name(this, "DurableStorageUnavailableError");
@@ -11464,11 +11814,11 @@ var DurableMemoryStore = class {
11464
11814
  }
11465
11815
  let parsed;
11466
11816
  try {
11467
- parsed = JSON.parse(new TextDecoder().decode(raw));
11817
+ parsed = JSON.parse(decodeText(raw, { source: this.filePath }));
11468
11818
  } catch {
11469
11819
  try {
11470
11820
  const bakRaw = await fs2.readFile(`${this.filePath}.bak`);
11471
- parsed = JSON.parse(new TextDecoder().decode(bakRaw));
11821
+ parsed = JSON.parse(decodeText(bakRaw, { source: `${this.filePath}.bak` }));
11472
11822
  } catch {
11473
11823
  throw new DurableStorageUnavailableError(
11474
11824
  "Durable memory store is corrupt and no backup is available."
@@ -12276,7 +12626,6 @@ var context = {
12276
12626
  };
12277
12627
 
12278
12628
  // core/memory/acquire.ts
12279
- init_suppress_idb_warning();
12280
12629
  init_env();
12281
12630
  init_built_in_context();
12282
12631
  init_project_identity();
@@ -12450,16 +12799,16 @@ var profile = {
12450
12799
 
12451
12800
  // core/knowledge/note-types.ts
12452
12801
  async function sha256HexOfText(text) {
12453
- const encoder3 = new TextEncoder();
12454
- const bytes = encoder3.encode(text);
12802
+ const encoder4 = new TextEncoder();
12803
+ const bytes = encoder4.encode(text);
12455
12804
  const hashArray = await crypto.subtle.digest("SHA-256", bytes);
12456
12805
  return Array.from(new Uint8Array(hashArray)).map((b) => b.toString(16).padStart(2, "0")).join("");
12457
12806
  }
12458
12807
  __name(sha256HexOfText, "sha256HexOfText");
12459
12808
  async function buildNoteKnowledge(title, content, origin, tag) {
12460
12809
  const sha2563 = await sha256HexOfText(content);
12461
- const encoder3 = new TextEncoder();
12462
- const size = encoder3.encode(content).byteLength;
12810
+ const encoder4 = new TextEncoder();
12811
+ const size = encoder4.encode(content).byteLength;
12463
12812
  return {
12464
12813
  title,
12465
12814
  content,
@@ -13618,7 +13967,7 @@ var memory = {
13618
13967
  resetPolicyStoreCache();
13619
13968
  },
13620
13969
  // ----- namespaced surfaces -----
13621
- /** Local operation journal (namespaced). No-op substrate when sqlite/idb unavailable. */
13970
+ /** Local operation journal (namespaced). Persisted on `store`. */
13622
13971
  journal: journal_default,
13623
13972
  /** Configure the optional cloud-sync layer (namespace + provider). Chainable. */
13624
13973
  configure(opts) {
@@ -13992,7 +14341,6 @@ var global_default = {
13992
14341
  state: memorio.state,
13993
14342
  store: memorio.store,
13994
14343
  session: memorio.session,
13995
- idb,
13996
14344
  dispatch: memorio.dispatch,
13997
14345
  hlc: memorio.hlc,
13998
14346
  encryption,
@@ -14024,6 +14372,5 @@ Object.defineProperty(exports, "store", {
14024
14372
  exports.continuity = continuity;
14025
14373
  exports.default = global_default;
14026
14374
  exports.encryption = encryption;
14027
- exports.idb = idb;
14028
14375
  exports.memory = memory;
14029
14376
  exports.security = security;