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/index.js CHANGED
@@ -22,18 +22,6 @@ var __export = (target, all) => {
22
22
  __defProp(target, name, { get: all[name], enumerable: true });
23
23
  };
24
24
 
25
- // core/suppress-idb-warning.ts
26
- var orig;
27
- var init_suppress_idb_warning = __esm({
28
- "core/suppress-idb-warning.ts"() {
29
- orig = console.warn.bind(console);
30
- console.warn = (...args) => {
31
- if (typeof args[0] === "string" && args[0].includes("IndexedDB is not available")) return;
32
- orig(...args);
33
- };
34
- }
35
- });
36
-
37
25
  // core/env.ts
38
26
  var DEV;
39
27
  var init_env = __esm({
@@ -109,6 +97,60 @@ var init_storage_paths = __esm({
109
97
  }
110
98
  });
111
99
 
100
+ // core/knowledge/text-encoding.ts
101
+ function detectBom(bytes) {
102
+ if (bytes.length >= 3 && bytes[0] === BOM_UTF8 && bytes[1] === 187 && bytes[2] === 191) {
103
+ return "utf-8";
104
+ }
105
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16LE_FIRST && bytes[1] === BOM_UTF16LE_SECOND) {
106
+ return "utf-16le";
107
+ }
108
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16BE_FIRST && bytes[1] === BOM_UTF16BE_SECOND) {
109
+ return "utf-16be";
110
+ }
111
+ return null;
112
+ }
113
+ function encodeText(value) {
114
+ return encoder.encode(value);
115
+ }
116
+ function decodeText(bytes, options = {}) {
117
+ const bom = detectBom(bytes);
118
+ if (bom === "utf-16le" || bom === "utf-16be") {
119
+ throw new UnsupportedEncodingError(
120
+ `UTF-16 encoded content detected in ${options.source ?? "unknown"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`
121
+ );
122
+ }
123
+ let content = bytes;
124
+ if (bom === "utf-8") {
125
+ content = bytes.subarray(3);
126
+ }
127
+ return strictDecoder.decode(content);
128
+ }
129
+ var encoder, strictDecoder, UnsupportedEncodingError, BOM_UTF8, BOM_UTF16LE_FIRST, BOM_UTF16LE_SECOND, BOM_UTF16BE_FIRST, BOM_UTF16BE_SECOND;
130
+ var init_text_encoding = __esm({
131
+ "core/knowledge/text-encoding.ts"() {
132
+ encoder = new TextEncoder();
133
+ strictDecoder = new TextDecoder("utf-8", { fatal: true });
134
+ UnsupportedEncodingError = class extends Error {
135
+ static {
136
+ __name(this, "UnsupportedEncodingError");
137
+ }
138
+ constructor(message) {
139
+ super(message);
140
+ this.name = "UnsupportedEncodingError";
141
+ }
142
+ };
143
+ BOM_UTF8 = 239;
144
+ BOM_UTF16LE_FIRST = 255;
145
+ BOM_UTF16LE_SECOND = 254;
146
+ BOM_UTF16BE_FIRST = 254;
147
+ BOM_UTF16BE_SECOND = 255;
148
+ __name(detectBom, "detectBom");
149
+ __name(encodeText, "encodeText");
150
+ __name(decodeText, "decodeText");
151
+ }
152
+ });
153
+
112
154
  // core/knowledge/storage-settings.ts
113
155
  var DOTMEM_STORAGE_SETTINGS_FILE_NAME, SETTINGS_MODES, projectRoot, findProjectSettingsFile, discoverProjectSettingsFilePath, resolveUserSettingsFilePath, invalidSettings, parseSettings, resolveSettingsEntry, readTextFile, readStorageSettings;
114
156
  var init_storage_settings = __esm({
@@ -240,15 +282,19 @@ function readDotMemStorageLocator() {
240
282
  const locatorFile = resolveLocatorFilePath(anchor);
241
283
  let raw;
242
284
  try {
243
- raw = fs2.readFileSync(locatorFile, "utf8");
285
+ raw = decodeText(fs2.readFileSync(locatorFile), { source: locatorFile });
244
286
  } catch (error) {
287
+ if (error instanceof UnsupportedEncodingError) {
288
+ throw new DotMemStorageLocationError(
289
+ `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.`
290
+ );
291
+ }
245
292
  const code = error?.code;
246
293
  if (code === "ENOENT") return null;
247
294
  throw new DotMemStorageLocationError(
248
295
  `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} cannot be read (${describeAccessFailure(error)}). No alternative location was selected automatically.`
249
296
  );
250
297
  }
251
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
252
298
  let parsed;
253
299
  try {
254
300
  parsed = JSON.parse(raw);
@@ -340,6 +386,7 @@ var DOTMEM_USER_ANCHOR_DIR_NAME, DOTMEM_STORAGE_LOCATOR_FILE_NAME, DOTMEM_STORAG
340
386
  var init_storage_location = __esm({
341
387
  "core/knowledge/storage-location.ts"() {
342
388
  init_storage_paths();
389
+ init_text_encoding();
343
390
  init_storage_settings();
344
391
  init_storage_paths();
345
392
  DOTMEM_USER_ANCHOR_DIR_NAME = ".dotmem";
@@ -1354,6 +1401,12 @@ var init_state = __esm({
1354
1401
  if (claim.sourceProject !== void 0 && !requiredText(claim.sourceProject)) {
1355
1402
  throw new Error(`Claim ${claim.id} has an invalid sourceProject`);
1356
1403
  }
1404
+ if (claim.check !== void 0) {
1405
+ const check = claim.check;
1406
+ 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)) {
1407
+ throw new Error(`Claim ${claim.id} has an invalid check`);
1408
+ }
1409
+ }
1357
1410
  return claim;
1358
1411
  }, "validateClaim");
1359
1412
  validateKnowledgeState = /* @__PURE__ */ __name((value) => {
@@ -1658,6 +1711,50 @@ var init_scope_eligibility = __esm({
1658
1711
  }
1659
1712
  });
1660
1713
 
1714
+ // core/knowledge/currentness.ts
1715
+ var asRecord, verifiedAtOf, findContestedIds, deriveCurrentness;
1716
+ var init_currentness = __esm({
1717
+ "core/knowledge/currentness.ts"() {
1718
+ asRecord = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0, "asRecord");
1719
+ verifiedAtOf = /* @__PURE__ */ __name((claim) => {
1720
+ const value = asRecord(claim.knowledge)?.verifiedAt;
1721
+ if (typeof value !== "string") return void 0;
1722
+ const parsed = Date.parse(value);
1723
+ return Number.isNaN(parsed) ? void 0 : parsed;
1724
+ }, "verifiedAtOf");
1725
+ findContestedIds = /* @__PURE__ */ __name((claims) => {
1726
+ const retracting = /* @__PURE__ */ new Map();
1727
+ for (const claim of claims) {
1728
+ if (claim.revision?.kind === "retracts" && claim.revision.claimIds.length > 0) {
1729
+ retracting.set(claim.id, new Set(claim.revision.claimIds));
1730
+ }
1731
+ }
1732
+ const contested = /* @__PURE__ */ new Set();
1733
+ for (const [id, targets] of retracting) {
1734
+ for (const target of targets) {
1735
+ if (retracting.get(target)?.has(id)) {
1736
+ contested.add(id);
1737
+ contested.add(target);
1738
+ }
1739
+ }
1740
+ }
1741
+ return contested;
1742
+ }, "findContestedIds");
1743
+ deriveCurrentness = /* @__PURE__ */ __name((claim, context2 = {}) => {
1744
+ const now3 = context2.now ?? Date.now();
1745
+ if (context2.contestedIds?.has(claim.id)) return "contested";
1746
+ if (claim.revision?.kind === "retracts") return "historical";
1747
+ if (context2.retractedIds?.has(claim.id)) return "historical";
1748
+ if (context2.supersededIds?.has(claim.id)) return "superseded";
1749
+ if (claim.expiresAt !== void 0 && now3 >= claim.expiresAt) return "expired";
1750
+ const verifiedAt = verifiedAtOf(claim);
1751
+ if (verifiedAt !== void 0) return "verified";
1752
+ if (claim.epistemicType === "verified") return "unverified";
1753
+ return "unknown-currentness";
1754
+ }, "deriveCurrentness");
1755
+ }
1756
+ });
1757
+
1661
1758
  // core/knowledge/discover.ts
1662
1759
  var diagnostic, DEFAULT_LIMITS, FIELD_ORDER, FIELD_WEIGHT, normalize, discoveryTerms, jsonText, fieldText, acquiredTime, isExpired, rankCandidate, discoverAcquiredExperience;
1663
1760
  var init_discover = __esm({
@@ -1665,6 +1762,7 @@ var init_discover = __esm({
1665
1762
  init_state();
1666
1763
  init_applicability();
1667
1764
  init_scope_eligibility();
1765
+ init_currentness();
1668
1766
  init_env();
1669
1767
  diagnostic = /* @__PURE__ */ __name((message) => {
1670
1768
  if (typeof process !== "undefined" && typeof process.stderr?.write === "function") {
@@ -1777,11 +1875,78 @@ var init_discover = __esm({
1777
1875
  throw new Error("Discovery maxCandidates must be a positive integer");
1778
1876
  }
1779
1877
  const queryTerms = discoveryTerms(situation);
1878
+ const offset = options.cursor?.offset ?? 0;
1879
+ if (!Number.isInteger(offset) || offset < 0) {
1880
+ throw new Error("Discovery cursor offset must be a non-negative integer");
1881
+ }
1882
+ if (options.cursor && options.cursor.knowledgeVersion !== validated.version) {
1883
+ return {
1884
+ knowledgeVersion: validated.version,
1885
+ depth,
1886
+ queryTerms,
1887
+ candidates: [],
1888
+ omissions: [],
1889
+ offset: 0,
1890
+ snapshotChanged: true
1891
+ };
1892
+ }
1780
1893
  const available = activeClaims(validated);
1894
+ const availableIds = new Set(available.map((claim) => claim.id));
1895
+ const retractedIds = /* @__PURE__ */ new Set();
1896
+ const supersededIds = /* @__PURE__ */ new Set();
1897
+ const contestedIds = findContestedIds(validated.claims);
1898
+ for (const claim of validated.claims) {
1899
+ if (claim.revision?.kind === "retracts") {
1900
+ for (const id of claim.revision.claimIds) retractedIds.add(id);
1901
+ }
1902
+ if (claim.revision?.kind === "supersedes") {
1903
+ for (const id of claim.revision.claimIds) supersededIds.add(id);
1904
+ }
1905
+ }
1906
+ const revisionOmissions = validated.claims.filter((claim) => !availableIds.has(claim.id)).map((claim) => {
1907
+ const retracted = retractedIds.has(claim.id);
1908
+ const superseded = supersededIds.has(claim.id);
1909
+ return {
1910
+ id: claim.id,
1911
+ reason: retracted ? "retracted" : superseded ? "superseded" : "retracted",
1912
+ gate: "revision-resolution",
1913
+ ...retracted || superseded ? {} : { detail: "the claim itself retracts prior knowledge and is kept as history" }
1914
+ };
1915
+ }).sort((left, right) => left.id.localeCompare(right.id));
1781
1916
  const scopeEligible = options.currentProjectId === void 0 ? available : available.filter((claim) => isScopeEligible(claim, options.currentProjectId, sources.get(claim.id)));
1782
1917
  const freshEligible = scopeEligible.filter((claim) => !isExpired(claim));
1918
+ const scopeEligibleIds = new Set(scopeEligible.map((claim) => claim.id));
1919
+ const scopeOmissions = available.filter((claim) => !scopeEligibleIds.has(claim.id)).map((claim) => {
1920
+ const owner = claimOwnerProject(claim, sources.get(claim.id));
1921
+ return {
1922
+ id: claim.id,
1923
+ reason: "scope",
1924
+ gate: "scope",
1925
+ detail: owner === void 0 ? "owner project could not be resolved" : `owned by project ${owner}`
1926
+ };
1927
+ }).sort((left, right) => left.id.localeCompare(right.id));
1928
+ const freshIds = new Set(freshEligible.map((claim) => claim.id));
1929
+ const freshnessOmissions = scopeEligible.filter((claim) => !freshIds.has(claim.id)).map((claim) => ({
1930
+ id: claim.id,
1931
+ reason: "expired",
1932
+ gate: "freshness",
1933
+ detail: `expired at ${new Date(claim.expiresAt).toISOString()}`
1934
+ })).sort((left, right) => left.id.localeCompare(right.id));
1783
1935
  const situationApplicability = deriveSituationApplicability(situation, options.facts);
1784
- const eligible = freshEligible.map((claim) => ({ claim, match: isEligibleByApplicability(claim, situationApplicability) })).filter((candidate) => candidate.match.eligible);
1936
+ const applicabilityMatches = new Map(
1937
+ freshEligible.map((claim) => [claim.id, isEligibleByApplicability(claim, situationApplicability)])
1938
+ );
1939
+ const eligible = freshEligible.map((claim) => ({ claim, match: applicabilityMatches.get(claim.id) })).filter((candidate) => candidate.match.eligible);
1940
+ const applicabilityOmissions = freshEligible.filter((claim) => !applicabilityMatches.get(claim.id).eligible).map((claim) => {
1941
+ const match = applicabilityMatches.get(claim.id);
1942
+ const mismatched = Object.entries(match.dimensions).filter(([, state4]) => state4 === "MISMATCH").map(([dimension]) => dimension);
1943
+ return {
1944
+ id: claim.id,
1945
+ reason: "applicability-mismatch",
1946
+ gate: "applicability",
1947
+ detail: `mismatching dimensions: ${mismatched.length > 0 ? mismatched.join(", ") : "none recorded"}`
1948
+ };
1949
+ }).sort((left, right) => left.id.localeCompare(right.id));
1785
1950
  if (DEV) {
1786
1951
  diagnostic(
1787
1952
  "[dotmem discovery] ACTIVE=" + JSON.stringify(
@@ -1793,12 +1958,15 @@ var init_discover = __esm({
1793
1958
  )
1794
1959
  );
1795
1960
  }
1961
+ const currentnessOf = /* @__PURE__ */ __name((claim) => deriveCurrentness(claim, { retractedIds, supersededIds, contestedIds }), "currentnessOf");
1796
1962
  if (queryTerms.length === 0) {
1797
- const baseline = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1963
+ const baselineAll = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1798
1964
  const leftTime = acquiredTime(left);
1799
1965
  const rightTime = acquiredTime(right);
1800
1966
  return rightTime - leftTime || Number(right.scope === "project") - Number(left.scope === "project") || left.id.localeCompare(right.id);
1801
- }).slice(0, maxCandidates);
1967
+ });
1968
+ const baseline = baselineAll.slice(offset, offset + maxCandidates);
1969
+ const limitOmissions = baselineAll.slice(offset + maxCandidates).map((claim) => ({ id: claim.id, reason: "limit", gate: "ranking" })).sort((left, right) => left.id.localeCompare(right.id));
1802
1970
  const baselineCandidates = baseline.map((claim) => {
1803
1971
  const explanation = {
1804
1972
  matchedTerms: [],
@@ -1811,7 +1979,8 @@ var init_discover = __esm({
1811
1979
  }
1812
1980
  return {
1813
1981
  claim,
1814
- explanation
1982
+ explanation,
1983
+ currentness: currentnessOf(claim)
1815
1984
  };
1816
1985
  });
1817
1986
  if (DEV) {
@@ -1824,10 +1993,18 @@ var init_discover = __esm({
1824
1993
  depth,
1825
1994
  queryTerms,
1826
1995
  situationApplicability,
1827
- candidates: baselineCandidates
1996
+ candidates: baselineCandidates,
1997
+ offset,
1998
+ omissions: [
1999
+ ...revisionOmissions,
2000
+ ...scopeOmissions,
2001
+ ...freshnessOmissions,
2002
+ ...applicabilityOmissions,
2003
+ ...limitOmissions
2004
+ ]
1828
2005
  };
1829
2006
  }
1830
- const candidates = eligible.map(
2007
+ const ranked = eligible.map(
1831
2008
  (candidate) => rankCandidate(
1832
2009
  candidate.claim,
1833
2010
  situation,
@@ -1839,16 +2016,40 @@ var init_discover = __esm({
1839
2016
  (candidate) => candidate !== null
1840
2017
  ).sort(
1841
2018
  (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)
1842
- ).slice(0, maxCandidates).map(({ claim, explanation }) => ({
2019
+ );
2020
+ const rankedIds = new Set(ranked.map((candidate) => candidate.claim.id));
2021
+ const rankingOmissions = [
2022
+ ...eligible.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2023
+ id: candidate.claim.id,
2024
+ reason: "no-term-match",
2025
+ gate: "ranking",
2026
+ detail: "passed every gate but shares no query term"
2027
+ })),
2028
+ ...ranked.slice(offset + maxCandidates).map((candidate) => ({
2029
+ id: candidate.claim.id,
2030
+ reason: "limit",
2031
+ gate: "ranking"
2032
+ }))
2033
+ ].sort((left, right) => left.id.localeCompare(right.id));
2034
+ const candidates = ranked.slice(offset, offset + maxCandidates).map(({ claim, explanation }) => ({
1843
2035
  claim,
1844
- explanation
2036
+ explanation,
2037
+ currentness: currentnessOf(claim)
1845
2038
  }));
1846
2039
  return {
1847
2040
  knowledgeVersion: validated.version,
1848
2041
  depth,
1849
2042
  queryTerms,
1850
2043
  situationApplicability,
1851
- candidates
2044
+ candidates,
2045
+ offset,
2046
+ omissions: [
2047
+ ...revisionOmissions,
2048
+ ...scopeOmissions,
2049
+ ...freshnessOmissions,
2050
+ ...applicabilityOmissions,
2051
+ ...rankingOmissions
2052
+ ]
1852
2053
  };
1853
2054
  }, "discoverAcquiredExperience");
1854
2055
  }
@@ -2905,7 +3106,7 @@ var init_policy_store = __esm({
2905
3106
  });
2906
3107
 
2907
3108
  // core/knowledge/acquisition-limits.ts
2908
- var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder, serializedBytes, measureKnowledge, checkAcquireLimits;
3109
+ var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder2, serializedBytes, measureKnowledge, checkAcquireLimits;
2909
3110
  var init_acquisition_limits = __esm({
2910
3111
  "core/knowledge/acquisition-limits.ts"() {
2911
3112
  MEMORY_ACQUIRE_LIMITS = Object.freeze({
@@ -2964,10 +3165,10 @@ var init_acquisition_limits = __esm({
2964
3165
  this.name = "MemoryAcquireDuplicateClaimError";
2965
3166
  }
2966
3167
  };
2967
- encoder = new TextEncoder();
3168
+ encoder2 = new TextEncoder();
2968
3169
  serializedBytes = /* @__PURE__ */ __name((value) => {
2969
3170
  const json = JSON.stringify(value);
2970
- return json === void 0 ? 0 : encoder.encode(json).length;
3171
+ return json === void 0 ? 0 : encoder2.encode(json).length;
2971
3172
  }, "serializedBytes");
2972
3173
  measureKnowledge = /* @__PURE__ */ __name((knowledge) => {
2973
3174
  const claimBytes = serializedBytes(knowledge);
@@ -3061,7 +3262,7 @@ var init_context_constants = __esm({
3061
3262
  });
3062
3263
 
3063
3264
  // core/knowledge/project.ts
3064
- var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_MAX_CHARACTERS, projectCandidate, renderHeader, renderExperience, renderText, projectDiscoveredExperience;
3265
+ 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;
3065
3266
  var init_project = __esm({
3066
3267
  "core/knowledge/project.ts"() {
3067
3268
  init_state();
@@ -3086,9 +3287,29 @@ var init_project = __esm({
3086
3287
  ...claim.provenance ? { provenance: claim.provenance } : {},
3087
3288
  ...claim.acquiredAt ? { acquiredAt: claim.acquiredAt } : {},
3088
3289
  ...claim.revision ? { revision: claim.revision } : {},
3089
- ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {}
3290
+ ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {},
3291
+ ...candidate.currentness ? { currentness: candidate.currentness } : {}
3090
3292
  });
3091
3293
  }, "projectCandidate");
3294
+ GIST_MAX_LENGTH = 80;
3295
+ GIST_KEYS = ["gist", "summary", "statement", "title", "reason", "principle", "finding", "detail"];
3296
+ MANIFEST_ID_LIMIT = 40;
3297
+ deriveGist = /* @__PURE__ */ __name((knowledge) => {
3298
+ if (typeof knowledge === "string") {
3299
+ return knowledge.length > GIST_MAX_LENGTH ? `${knowledge.slice(0, GIST_MAX_LENGTH)}\u2026` : knowledge;
3300
+ }
3301
+ if (knowledge && typeof knowledge === "object" && !Array.isArray(knowledge)) {
3302
+ const obj = knowledge;
3303
+ for (const key of GIST_KEYS) {
3304
+ const value = obj[key];
3305
+ if (typeof value === "string" && value.length > 0) {
3306
+ return value.length > GIST_MAX_LENGTH ? `${value.slice(0, GIST_MAX_LENGTH)}\u2026` : value;
3307
+ }
3308
+ }
3309
+ }
3310
+ const str = JSON.stringify(knowledge);
3311
+ return str.length > GIST_MAX_LENGTH ? `${str.slice(0, GIST_MAX_LENGTH)}\u2026` : str;
3312
+ }, "deriveGist");
3092
3313
  renderHeader = /* @__PURE__ */ __name((knowledgeVersion, totalCandidates) => {
3093
3314
  const lines = [
3094
3315
  `DOTMEM STORAGE: ${resolveUserDotMemPath()}`,
@@ -3114,27 +3335,70 @@ var init_project = __esm({
3114
3335
  evidence.supports ?? null
3115
3336
  ]),
3116
3337
  ...experience.epistemicType ? { epistemic: experience.epistemicType } : {},
3338
+ ...experience.currentness ? { currentness: experience.currentness } : {},
3117
3339
  ...experience.provenance ? { provenance: [experience.provenance.source, experience.provenance.detail ?? null] } : {},
3118
3340
  ...experience.acquiredAt ? { acquiredAt: experience.acquiredAt } : {},
3119
3341
  ...experience.revision ? { revision: experience.revision } : {},
3120
3342
  ...experience.sourceId ? { source: experience.sourceId } : {}
3121
3343
  }), "renderExperience");
3122
- renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates) => `${header}${experiences.length ? `
3123
- ${experiences.map(renderExperience).join("\n")}` : ""}
3124
- OMITTED:${omittedCandidates}`, "renderText");
3344
+ renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, render = renderExperience, currentnessSummary) => {
3345
+ const lines = [header];
3346
+ if (experiences.length > 0) lines.push(...experiences.map(render));
3347
+ lines.push(`OMITTED:${omittedCandidates}`);
3348
+ if (manifest && manifest.byReason.length > 0) {
3349
+ lines.push(`OMITTED_BY_REASON:${manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`);
3350
+ }
3351
+ if (manifest && manifest.items.length > 0) {
3352
+ lines.push(`OMITTED_IDS:${manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`);
3353
+ if (manifest.items.length > MANIFEST_ID_LIMIT) {
3354
+ lines.push(`OMITTED_IDS_TRUNCATED:${manifest.items.length - MANIFEST_ID_LIMIT}`);
3355
+ }
3356
+ }
3357
+ if (currentnessSummary) {
3358
+ lines.push(`CURRENTNESS:${currentnessSummary}`);
3359
+ }
3360
+ return lines.join("\n");
3361
+ }, "renderText");
3362
+ byteLength = /* @__PURE__ */ __name((value) => new TextEncoder().encode(value).length, "byteLength");
3363
+ summarizeOmissions = /* @__PURE__ */ __name((items) => {
3364
+ const counts = /* @__PURE__ */ new Map();
3365
+ for (const item of items) counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
3366
+ return [...counts.entries()].map(([reason, count]) => ({ reason, count })).sort((left, right) => left.reason.localeCompare(right.reason));
3367
+ }, "summarizeOmissions");
3368
+ renderManifestFitting = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, maxCharacters, render, currentnessSummary) => {
3369
+ const full = renderText(header, experiences, omittedCandidates, manifest, render, currentnessSummary);
3370
+ if (byteLength(full) <= maxCharacters) return full;
3371
+ const withoutIds = { ...manifest, items: [] };
3372
+ return renderText(header, experiences, omittedCandidates, withoutIds, render, currentnessSummary);
3373
+ }, "renderManifestFitting");
3374
+ renderCompactExperience = /* @__PURE__ */ __name((experience) => JSON.stringify({
3375
+ id: experience.id,
3376
+ status: "candidate",
3377
+ gist: deriveGist(experience.experience),
3378
+ epistemic: experience.epistemicType ?? null,
3379
+ currentness: experience.currentness ?? null,
3380
+ ...experience.revision ? { revision: experience.revision.kind } : {}
3381
+ }), "renderCompactExperience");
3125
3382
  projectDiscoveredExperience = /* @__PURE__ */ __name((discovery, options = {}) => {
3126
3383
  if (!discovery || !Number.isInteger(discovery.knowledgeVersion) || discovery.knowledgeVersion < 0 || !Array.isArray(discovery.candidates)) {
3127
3384
  throw new Error("Valid DiscoveryResult is required for context projection");
3128
3385
  }
3129
3386
  const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES;
3130
3387
  const maxCharacters = options.maxCharacters ?? DEFAULT_MAX_CHARACTERS;
3388
+ const format = options.format ?? "compact";
3389
+ if (format !== "compact" && format !== "standard" && format !== "full") {
3390
+ throw new Error("Projection format must be compact, standard or full");
3391
+ }
3131
3392
  if (!Number.isInteger(maxCandidates) || maxCandidates < 1) throw new Error("Projection maxCandidates must be a positive integer");
3132
3393
  if (!Number.isInteger(maxCharacters) || maxCharacters < MIN_MAX_CHARACTERS) {
3133
3394
  throw new Error(`Projection maxCharacters must be an integer of at least ${MIN_MAX_CHARACTERS}`);
3134
3395
  }
3135
- const totalCandidates = discovery.candidates.length;
3396
+ const render = /* @__PURE__ */ __name((experience) => format === "compact" ? renderCompactExperience(experience) : renderExperience(experience), "render");
3397
+ const gateOmissions = discovery.omissions ?? [];
3398
+ const totalCandidates = discovery.candidates.length + gateOmissions.length;
3136
3399
  const header = renderHeader(discovery.knowledgeVersion, totalCandidates);
3137
- if (renderText(header, [], totalCandidates).length > maxCharacters) {
3400
+ const emptyManifest = { considered: totalCandidates, included: 0, items: [], byReason: [] };
3401
+ if (byteLength(renderText(header, [], totalCandidates, emptyManifest)) > maxCharacters) {
3138
3402
  throw new Error("Projection maxCharacters is too small for the projection envelope");
3139
3403
  }
3140
3404
  const experiences = [];
@@ -3143,12 +3407,49 @@ OMITTED:${omittedCandidates}`, "renderText");
3143
3407
  const projected = projectCandidate(candidate);
3144
3408
  const possibleExperiences = [...experiences, projected];
3145
3409
  const possibleOmitted = totalCandidates - possibleExperiences.length;
3146
- if (renderText(header, possibleExperiences, possibleOmitted).length <= maxCharacters) {
3410
+ const candidateManifest = {
3411
+ considered: totalCandidates,
3412
+ included: possibleExperiences.length,
3413
+ items: gateOmissions,
3414
+ byReason: summarizeOmissions(gateOmissions)
3415
+ };
3416
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, candidateManifest, render)) <= maxCharacters) {
3417
+ experiences.push(projected);
3418
+ continue;
3419
+ }
3420
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, void 0, render)) <= maxCharacters) {
3147
3421
  experiences.push(projected);
3148
3422
  }
3149
3423
  }
3424
+ const projectedIds = new Set(experiences.map((experience) => experience.id));
3425
+ const budgetOmissions = discovery.candidates.filter((candidate) => !projectedIds.has(candidate.claim.id)).map((candidate) => ({ id: candidate.claim.id, reason: "budget", gate: "projection" }));
3426
+ const items = [...gateOmissions, ...budgetOmissions];
3150
3427
  const omittedCandidates = totalCandidates - experiences.length;
3151
- const text = renderText(header, experiences, omittedCandidates);
3428
+ const manifest = {
3429
+ considered: totalCandidates,
3430
+ included: experiences.length,
3431
+ items,
3432
+ byReason: summarizeOmissions(items)
3433
+ };
3434
+ const currentnessCounts = /* @__PURE__ */ new Map();
3435
+ for (const experience of experiences) {
3436
+ if (experience.currentness) {
3437
+ currentnessCounts.set(
3438
+ experience.currentness,
3439
+ (currentnessCounts.get(experience.currentness) ?? 0) + 1
3440
+ );
3441
+ }
3442
+ }
3443
+ const currentnessSummary = currentnessCounts.size > 0 ? [...currentnessCounts.entries()].map(([state3, count]) => `${state3}=${count}`).join(",") : void 0;
3444
+ const text = renderManifestFitting(
3445
+ header,
3446
+ experiences,
3447
+ omittedCandidates,
3448
+ manifest,
3449
+ maxCharacters,
3450
+ render,
3451
+ currentnessSummary
3452
+ );
3152
3453
  return {
3153
3454
  format: FORMAT,
3154
3455
  status: STATUS,
@@ -3157,6 +3458,7 @@ OMITTED:${omittedCandidates}`, "renderText");
3157
3458
  totalCandidates,
3158
3459
  omittedCandidates,
3159
3460
  experiences,
3461
+ manifest,
3160
3462
  text
3161
3463
  };
3162
3464
  }, "projectDiscoveredExperience");
@@ -3194,7 +3496,7 @@ var init_language_detect = __esm({
3194
3496
  var CANONICAL_KINDS, validateKind, buildClaimRecord;
3195
3497
  var init_claim_record = __esm({
3196
3498
  "core/knowledge/claim-record.ts"() {
3197
- CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note"];
3499
+ CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note", "rule"];
3198
3500
  validateKind = /* @__PURE__ */ __name((kind) => {
3199
3501
  if (!CANONICAL_KINDS.includes(kind)) {
3200
3502
  throw new Error(
@@ -4425,8 +4727,8 @@ var init_browser = __esm({
4425
4727
  this.p = null;
4426
4728
  }
4427
4729
  };
4428
- Unzip2.prototype.register = function(decoder2) {
4429
- this.o[decoder2.compression] = decoder2;
4730
+ Unzip2.prototype.register = function(decoder) {
4731
+ this.o[decoder.compression] = decoder;
4430
4732
  };
4431
4733
  return Unzip2;
4432
4734
  })();
@@ -4446,6 +4748,15 @@ function encodeMemFile(stateValue, preserved) {
4446
4748
  if (!map.claim.includes("kind")) {
4447
4749
  map.claim.push("kind");
4448
4750
  }
4751
+ if (!map.claim.includes("expires-at")) {
4752
+ map.claim.push("expires-at");
4753
+ }
4754
+ if (!map.claim.includes("bootstrap-priority")) {
4755
+ map.claim.push("bootstrap-priority");
4756
+ }
4757
+ if (!map.claim.includes("check")) {
4758
+ map.claim.push("check");
4759
+ }
4449
4760
  const indexes = Object.fromEntries(Object.keys(expectedFields).map((name) => [name, fieldIndexes(map, name)]));
4450
4761
  validateVocabulary(map.epistemicType, epistemicTypes, "epistemicType");
4451
4762
  validateVocabulary(map.revisionKind, revisionKinds, "revisionKind");
@@ -4495,6 +4806,15 @@ function encodeMemFile(stateValue, preserved) {
4495
4806
  if (indexes.claim.has("kind")) {
4496
4807
  putOptional(record, indexes.claim, "kind", claim.kind ?? void 0, original !== void 0);
4497
4808
  }
4809
+ if (indexes.claim.has("expires-at")) {
4810
+ putOptional(record, indexes.claim, "expires-at", claim.expiresAt, original !== void 0);
4811
+ }
4812
+ if (indexes.claim.has("bootstrap-priority")) {
4813
+ putOptional(record, indexes.claim, "bootstrap-priority", claim.bootstrapPriority, original !== void 0);
4814
+ }
4815
+ if (indexes.claim.has("check")) {
4816
+ putOptional(record, indexes.claim, "check", claim.check, original !== void 0);
4817
+ }
4498
4818
  return original ? record : trimRecord(record);
4499
4819
  }, "encodeClaim");
4500
4820
  const stateRecord = structuredClone(preserved?.data ?? []);
@@ -4563,8 +4883,37 @@ function decodeMemDocument(value) {
4563
4883
  const scope = optionalGet(record, indexes.claim, "scope");
4564
4884
  const sourceProject = optionalGet(record, indexes.claim, "source-project");
4565
4885
  const kindValue = optionalGet(record, indexes.claim, "kind");
4886
+ const expiresAtValue = indexes.claim.has("expires-at") ? optionalGet(record, indexes.claim, "expires-at") : void 0;
4887
+ const bootstrapPriorityValue = indexes.claim.has("bootstrap-priority") ? optionalGet(record, indexes.claim, "bootstrap-priority") : void 0;
4888
+ const checkValue = indexes.claim.has("check") ? optionalGet(record, indexes.claim, "check") : void 0;
4566
4889
  if (epistemicIndex !== void 0 && (!Number.isInteger(epistemicIndex) || epistemicIndex < 0 || epistemicIndex >= epistemic.length)) throw new Error("Invalid .mem epistemic value");
4567
4890
  if (kindIndex !== void 0 && (!Number.isInteger(kindIndex) || kindIndex < 0 || kindIndex >= revisions.length)) throw new Error("Invalid .mem revision value");
4891
+ if (expiresAtValue !== void 0 && (!Number.isInteger(expiresAtValue) || expiresAtValue < 0)) {
4892
+ throw new Error("Invalid .mem expiresAt value");
4893
+ }
4894
+ if (bootstrapPriorityValue !== void 0 && !bootstrapPriorities.includes(bootstrapPriorityValue)) {
4895
+ throw new Error("Invalid .mem bootstrapPriority value");
4896
+ }
4897
+ let check;
4898
+ if (checkValue !== void 0) {
4899
+ if (!checkValue || typeof checkValue !== "object" || Array.isArray(checkValue)) {
4900
+ throw new Error("Invalid .mem check record");
4901
+ }
4902
+ const checkRecord = checkValue;
4903
+ const description = checkRecord.description;
4904
+ if (typeof description !== "undefined" && typeof description !== "string") {
4905
+ throw new Error("Invalid .mem check record");
4906
+ }
4907
+ if (checkRecord.kind !== "regex" || typeof checkRecord.pattern !== "string" || checkRecord.pattern.length === 0 || !checkTargets.includes(checkRecord.on)) {
4908
+ throw new Error("Invalid .mem check record");
4909
+ }
4910
+ check = {
4911
+ kind: "regex",
4912
+ pattern: checkRecord.pattern,
4913
+ on: checkRecord.on,
4914
+ ...typeof description === "string" ? { description } : {}
4915
+ };
4916
+ }
4568
4917
  const understoodEpistemic = typeof epistemicIndex === "number" && epistemicTypes.includes(epistemic[epistemicIndex]) ? epistemic[epistemicIndex] : void 0;
4569
4918
  const understoodRevision = typeof kindIndex === "number" && revisionKinds.includes(revisions[kindIndex]);
4570
4919
  const claim = {
@@ -4589,6 +4938,9 @@ function decodeMemDocument(value) {
4589
4938
  } : {},
4590
4939
  ...scope === void 0 ? {} : { scope },
4591
4940
  ...sourceProject === void 0 ? {} : { sourceProject },
4941
+ ...expiresAtValue === void 0 ? {} : { expiresAt: expiresAtValue },
4942
+ ...bootstrapPriorityValue === void 0 ? {} : { bootstrapPriority: bootstrapPriorityValue },
4943
+ ...check === void 0 ? {} : { check },
4592
4944
  ...claimKinds.includes(kindValue) ? { kind: kindValue } : {}
4593
4945
  };
4594
4946
  return validateClaim(claim);
@@ -4598,7 +4950,7 @@ function decodeMemDocument(value) {
4598
4950
  preserved: { map: structuredClone(map), data: structuredClone(stateRecord) }
4599
4951
  };
4600
4952
  }
4601
- 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;
4953
+ 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;
4602
4954
  var init_mem_codec = __esm({
4603
4955
  "core/knowledge/mem-codec.ts"() {
4604
4956
  init_state();
@@ -4615,7 +4967,9 @@ var init_mem_codec = __esm({
4615
4967
  };
4616
4968
  epistemicTypes = ["observed", "inferred", "human-stated", "verified"];
4617
4969
  revisionKinds = ["refines", "supersedes", "retracts"];
4618
- claimKinds = ["experience", "agent", "relationship", "logic", "note"];
4970
+ claimKinds = ["experience", "agent", "relationship", "logic", "note", "rule"];
4971
+ bootstrapPriorities = ["P1", "P2", "P3", "P4", "P5", "unclassified"];
4972
+ checkTargets = ["staged", "committed", "working-tree"];
4619
4973
  isJsonValue2 = /* @__PURE__ */ __name((value) => {
4620
4974
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
4621
4975
  if (typeof value === "number") return Number.isFinite(value);
@@ -4719,14 +5073,14 @@ async function signMemPackage(input, privateKey, publicKey) {
4719
5073
  });
4720
5074
  }
4721
5075
  async function decodeMemArtifact(input) {
4722
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
5076
+ const bytes = typeof input === "string" ? encoder3.encode(input) : input;
4723
5077
  if (isZip(bytes)) {
4724
5078
  const { parts: _parts, integrity: _integrity, ...artifact } = await decodePackage(bytes);
4725
5079
  return artifact;
4726
5080
  }
4727
5081
  let value;
4728
5082
  try {
4729
- value = JSON.parse(decoder.decode(bytes).replace(/^\uFEFF/, ""));
5083
+ value = JSON.parse(decodeText(bytes));
4730
5084
  } catch (error) {
4731
5085
  throw new MemArtifactError("corrupt", `Unsupported or corrupt MEM artifact: ${error.message}`);
4732
5086
  }
@@ -4741,7 +5095,7 @@ async function decodeMemArtifact(input) {
4741
5095
  }
4742
5096
  async function inspectMem(input) {
4743
5097
  try {
4744
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
5098
+ const bytes = typeof input === "string" ? encodeText(input) : input;
4745
5099
  if (isZip(bytes)) {
4746
5100
  const artifact2 = await decodePackage(bytes);
4747
5101
  const knownMapKeys = /* @__PURE__ */ new Set(["state", "claim", "evidence", "provenance", "revision", "epistemicType", "revisionKind"]);
@@ -4782,11 +5136,12 @@ async function inspectMem(input) {
4782
5136
  return { status: artifactError.code, representation: "unknown", message: artifactError.message, parts: [] };
4783
5137
  }
4784
5138
  }
4785
- 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, signaturePayload, base64UrlEncode, base64UrlDecode, keyIdentity, signaturePath, encodePackage, isZip, decodePackage, verifySignature;
5139
+ 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, signaturePayload, base64UrlEncode, base64UrlDecode, keyIdentity, signaturePath, encodePackage, isZip, decodePackage, verifySignature;
4786
5140
  var init_mem_package = __esm({
4787
5141
  "core/knowledge/mem-package.ts"() {
4788
5142
  init_browser();
4789
5143
  init_mem_codec();
5144
+ init_text_encoding();
4790
5145
  MEM_PACKAGE_FORMAT = "dotmem.package";
4791
5146
  MEM_PACKAGE_FORMAT_LEGACY = "memorio.package";
4792
5147
  MEM_PACKAGE_VERSION = 1;
@@ -4810,8 +5165,7 @@ var init_mem_package = __esm({
4810
5165
  DATA_PATH = "memory/data.json";
4811
5166
  INTEGRITY_PATH = "security/integrity.json";
4812
5167
  requiredParts = [MANIFEST_PATH, MAP_PATH, DATA_PATH];
4813
- encoder2 = new TextEncoder();
4814
- decoder = new TextDecoder("utf-8", { fatal: true });
5168
+ encoder3 = new TextEncoder();
4815
5169
  MemArtifactError = class extends Error {
4816
5170
  constructor(code, message) {
4817
5171
  super(message);
@@ -4830,7 +5184,7 @@ var init_mem_package = __esm({
4830
5184
  }
4831
5185
  return value;
4832
5186
  }, "stableValue");
4833
- jsonBytes = /* @__PURE__ */ __name((value) => encoder2.encode(`${JSON.stringify(stableValue(value), null, 2)}
5187
+ jsonBytes = /* @__PURE__ */ __name((value) => encoder3.encode(`${JSON.stringify(stableValue(value), null, 2)}
4834
5188
  `), "jsonBytes");
4835
5189
  sha256 = /* @__PURE__ */ __name(async (data) => {
4836
5190
  if (!globalThis.crypto?.subtle) throw new MemArtifactError("unsupported", "SHA-256 is unavailable in this runtime");
@@ -4839,7 +5193,7 @@ var init_mem_package = __esm({
4839
5193
  }, "sha256");
4840
5194
  parseJson = /* @__PURE__ */ __name((bytes, path2) => {
4841
5195
  try {
4842
- return JSON.parse(decoder.decode(bytes));
5196
+ return JSON.parse(decodeText(bytes));
4843
5197
  } catch (error) {
4844
5198
  throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path2}: ${error.message}`);
4845
5199
  }
@@ -4905,7 +5259,7 @@ var init_mem_package = __esm({
4905
5259
  parts: { map: MAP_PATH, data: DATA_PATH, integrity: INTEGRITY_PATH }
4906
5260
  }), "createManifest");
4907
5261
  digestTableIdentity = /* @__PURE__ */ __name((files) => sha256(jsonBytes(files)), "digestTableIdentity");
4908
- signaturePayload = /* @__PURE__ */ __name((contentId) => encoder2.encode(`DOTMEM-PACKAGE-SIGNATURE-V1
5262
+ signaturePayload = /* @__PURE__ */ __name((contentId) => encoder3.encode(`DOTMEM-PACKAGE-SIGNATURE-V1
4909
5263
  ${contentId}
4910
5264
  `), "signaturePayload");
4911
5265
  base64UrlEncode = /* @__PURE__ */ __name((value) => {
@@ -5095,10 +5449,12 @@ ${contentId}
5095
5449
  });
5096
5450
 
5097
5451
  // core/storage-coordinator/index.ts
5098
- var nodeFs4, withStorageLock, readStorageGeneration, writeStorageGeneration;
5452
+ var nodeFs4, heldLocks, withStorageLock, readStorageGeneration, writeStorageGeneration;
5099
5453
  var init_storage_coordinator = __esm({
5100
5454
  "core/storage-coordinator/index.ts"() {
5455
+ init_text_encoding();
5101
5456
  nodeFs4 = /* @__PURE__ */ __name(async () => import('fs/promises'), "nodeFs");
5457
+ heldLocks = /* @__PURE__ */ new Map();
5102
5458
  withStorageLock = /* @__PURE__ */ __name(async (directoryPath, operationOrOptions, operation, _options = {}) => {
5103
5459
  const opts = typeof operationOrOptions === "function" ? operation ?? {} : operationOrOptions ?? {};
5104
5460
  const op = typeof operationOrOptions === "function" ? operationOrOptions : operation;
@@ -5108,6 +5464,15 @@ var init_storage_coordinator = __esm({
5108
5464
  const lockPath = `${directoryPath}/${lockName}`;
5109
5465
  const fs2 = await nodeFs4();
5110
5466
  const started = Date.now();
5467
+ const heldDepth = heldLocks.get(lockPath) ?? 0;
5468
+ if (heldDepth > 0) {
5469
+ heldLocks.set(lockPath, heldDepth + 1);
5470
+ try {
5471
+ return await op();
5472
+ } finally {
5473
+ heldLocks.set(lockPath, heldDepth);
5474
+ }
5475
+ }
5111
5476
  await fs2.mkdir(directoryPath, { recursive: true });
5112
5477
  while (true) {
5113
5478
  try {
@@ -5121,8 +5486,8 @@ var init_storage_coordinator = __esm({
5121
5486
  let stale = false;
5122
5487
  let processDead = false;
5123
5488
  try {
5124
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5125
- const parsed = JSON.parse(raw);
5489
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5490
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
5126
5491
  const ageStale = typeof parsed.createdAt === "number" && Date.now() - parsed.createdAt > staleMs;
5127
5492
  if (typeof parsed.pid === "number") {
5128
5493
  try {
@@ -5159,17 +5524,19 @@ var init_storage_coordinator = __esm({
5159
5524
  }
5160
5525
  let token = "";
5161
5526
  try {
5162
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5163
- token = JSON.parse(raw).token ?? "";
5527
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5528
+ token = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` })).token ?? "";
5164
5529
  } catch {
5165
5530
  token = "";
5166
5531
  }
5167
5532
  try {
5533
+ heldLocks.set(lockPath, 1);
5168
5534
  return await op();
5169
5535
  } finally {
5536
+ heldLocks.delete(lockPath);
5170
5537
  try {
5171
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5172
- const parsed = JSON.parse(raw);
5538
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5539
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
5173
5540
  if (parsed.token === token && token) {
5174
5541
  await fs2.rm(lockPath, { recursive: true, force: true });
5175
5542
  }
@@ -5180,8 +5547,8 @@ var init_storage_coordinator = __esm({
5180
5547
  readStorageGeneration = /* @__PURE__ */ __name(async (directoryPath) => {
5181
5548
  const fs2 = await nodeFs4();
5182
5549
  try {
5183
- const raw = await fs2.readFile(`${directoryPath}/.storage.generation`, "utf8");
5184
- const value = Number(raw.trim());
5550
+ const raw = await fs2.readFile(`${directoryPath}/.storage.generation`);
5551
+ const value = Number(decodeText(raw, { source: `${directoryPath}/.storage.generation` }).trim());
5185
5552
  return Number.isFinite(value) && value >= 0 ? value : 0;
5186
5553
  } catch {
5187
5554
  return 0;
@@ -5710,12 +6077,11 @@ function readJsonFile(path2) {
5710
6077
  if (!fs2) return null;
5711
6078
  let raw;
5712
6079
  try {
5713
- raw = fs2.readFileSync(path2, "utf8");
6080
+ raw = decodeText(fs2.readFileSync(path2), { source: path2 });
5714
6081
  } catch {
5715
6082
  return null;
5716
6083
  }
5717
6084
  if (typeof raw !== "string") return null;
5718
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
5719
6085
  try {
5720
6086
  return JSON.parse(raw);
5721
6087
  } catch {
@@ -5839,6 +6205,7 @@ var init_user_language = __esm({
5839
6205
  "core/knowledge/user-language.ts"() {
5840
6206
  init_user_paths();
5841
6207
  init_storage_paths();
6208
+ init_text_encoding();
5842
6209
  USER_LANGUAGE_FILE_NAME = "language.json";
5843
6210
  USER_LANGUAGE_PREFERENCE_FILE_NAME = "user-language.json";
5844
6211
  LANGUAGE_PREFERENCE_FILE_NAME = "language-preference.json";
@@ -9562,10 +9929,13 @@ var init_staging = __esm({
9562
9929
  epistemicType: sanitizedClaim.epistemicType,
9563
9930
  provenance: sanitizedClaim.provenance,
9564
9931
  acquiredAt: sanitizedClaim.acquiredAt,
9932
+ ...sanitizedClaim.expiresAt === void 0 ? {} : { expiresAt: sanitizedClaim.expiresAt },
9933
+ ...sanitizedClaim.bootstrapPriority === void 0 ? {} : { bootstrapPriority: sanitizedClaim.bootstrapPriority },
9565
9934
  revision,
9566
9935
  scope,
9567
9936
  sourceProject,
9568
- kind
9937
+ kind,
9938
+ ...sanitizedClaim.check === void 0 ? {} : { check: sanitizedClaim.check }
9569
9939
  });
9570
9940
  await withStoreQueue(acquisitionStoreKey(kind, scope, sourceProject), async () => {
9571
9941
  const state3 = await target.runtime.select([]);
@@ -9813,19 +10183,19 @@ var init_incidents = __esm({
9813
10183
  }
9814
10184
  });
9815
10185
 
9816
- // core/knowledge/rules-loader.ts
9817
- var init_rules_loader = __esm({
9818
- "core/knowledge/rules-loader.ts"() {
9819
- init_state();
9820
- }
9821
- });
9822
-
9823
10186
  // core/knowledge/violations.ts
9824
10187
  var init_violations = __esm({
9825
10188
  "core/knowledge/violations.ts"() {
9826
10189
  init_user_paths();
9827
10190
  }
9828
10191
  });
10192
+ var init_rules_loader = __esm({
10193
+ "core/knowledge/rules-loader.ts"() {
10194
+ init_state();
10195
+ init_user_paths();
10196
+ init_violations();
10197
+ }
10198
+ });
9829
10199
 
9830
10200
  // core/knowledge/session.ts
9831
10201
  function joinPath5(base, child) {
@@ -10332,8 +10702,8 @@ function loadBuiltInContext() {
10332
10702
  for (const candidate of candidates) {
10333
10703
  if (!fs.existsSync(candidate)) continue;
10334
10704
  try {
10335
- const raw = fs.readFileSync(candidate, "utf8");
10336
- const parsed = JSON.parse(raw);
10705
+ const raw = fs.readFileSync(candidate);
10706
+ const parsed = JSON.parse(decodeText(raw, { source: candidate }));
10337
10707
  const artifact = validateArtifact(parsed);
10338
10708
  cached = artifact;
10339
10709
  cachedStatus = {
@@ -10410,6 +10780,7 @@ function resetBuiltInContextCache() {
10410
10780
  var BUILT_IN_CONTEXT_FORMAT, BUILT_IN_CONTEXT_FORMAT_VERSION, cached, cachedStatus, _artifactPathOverride;
10411
10781
  var init_built_in_context = __esm({
10412
10782
  "core/knowledge/built-in-context.ts"() {
10783
+ init_text_encoding();
10413
10784
  BUILT_IN_CONTEXT_FORMAT = "dotmem.built-in-context";
10414
10785
  BUILT_IN_CONTEXT_FORMAT_VERSION = 1;
10415
10786
  cached = null;
@@ -10473,6 +10844,7 @@ var init_knowledge = __esm({
10473
10844
  init_state();
10474
10845
  init_select();
10475
10846
  init_discover();
10847
+ init_currentness();
10476
10848
  init_project();
10477
10849
  init_applicability();
10478
10850
  init_policy();
@@ -10580,7 +10952,6 @@ function _inferConfidence(claim) {
10580
10952
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, LogicEngine, logic, logic_default;
10581
10953
  var init_logic = __esm({
10582
10954
  "core/logic/index.ts"() {
10583
- init_suppress_idb_warning();
10584
10955
  init_knowledge();
10585
10956
  init_mem_repository();
10586
10957
  init_acquisition_boundary();
@@ -10848,18 +11219,6 @@ Do not store secrets unless dotmem explicitly supports secure secret storage.
10848
11219
  }
10849
11220
  });
10850
11221
 
10851
- // index.ts
10852
- init_suppress_idb_warning();
10853
-
10854
- // core/idb.ts
10855
- var idb = {
10856
- db: {},
10857
- table: {},
10858
- data: {},
10859
- _disabled: true,
10860
- _warning: "IndexedDB is not available in this environment. Use dotmem store or session for persistence."
10861
- };
10862
-
10863
11222
  // core/platform.ts
10864
11223
  var runtimeProcess = /* @__PURE__ */ __name(() => {
10865
11224
  try {
@@ -11190,11 +11549,7 @@ var security = {
11190
11549
  createSanitizer
11191
11550
  };
11192
11551
 
11193
- // core/memory/index.ts
11194
- init_suppress_idb_warning();
11195
-
11196
11552
  // core/memory/journal.ts
11197
- init_suppress_idb_warning();
11198
11553
  init_env();
11199
11554
  var g = globalThis;
11200
11555
  function namespace() {
@@ -11401,7 +11756,6 @@ var journal_default = journal;
11401
11756
  init_brain();
11402
11757
 
11403
11758
  // core/memory/knowledge-runtime.ts
11404
- init_suppress_idb_warning();
11405
11759
  init_knowledge();
11406
11760
  init_project_identity();
11407
11761
  init_user_paths();
@@ -11743,12 +12097,12 @@ var policy = {
11743
12097
  };
11744
12098
 
11745
12099
  // core/memory/entries.ts
11746
- init_suppress_idb_warning();
11747
12100
  init_env();
11748
12101
 
11749
12102
  // core/memory/durable-store.ts
11750
12103
  init_storage_coordinator();
11751
12104
  init_store_queue();
12105
+ init_text_encoding();
11752
12106
  var DurableStorageUnavailableError = class extends Error {
11753
12107
  static {
11754
12108
  __name(this, "DurableStorageUnavailableError");
@@ -11803,11 +12157,11 @@ var DurableMemoryStore = class {
11803
12157
  }
11804
12158
  let parsed;
11805
12159
  try {
11806
- parsed = JSON.parse(new TextDecoder().decode(raw));
12160
+ parsed = JSON.parse(decodeText(raw, { source: this.filePath }));
11807
12161
  } catch {
11808
12162
  try {
11809
12163
  const bakRaw = await fs2.readFile(`${this.filePath}.bak`);
11810
- parsed = JSON.parse(new TextDecoder().decode(bakRaw));
12164
+ parsed = JSON.parse(decodeText(bakRaw, { source: `${this.filePath}.bak` }));
11811
12165
  } catch {
11812
12166
  throw new DurableStorageUnavailableError(
11813
12167
  "Durable memory store is corrupt and no backup is available."
@@ -12615,7 +12969,6 @@ var context = {
12615
12969
  };
12616
12970
 
12617
12971
  // core/memory/acquire.ts
12618
- init_suppress_idb_warning();
12619
12972
  init_env();
12620
12973
  init_built_in_context();
12621
12974
  init_project_identity();
@@ -12789,16 +13142,16 @@ var profile = {
12789
13142
 
12790
13143
  // core/knowledge/note-types.ts
12791
13144
  async function sha256HexOfText(text) {
12792
- const encoder3 = new TextEncoder();
12793
- const bytes = encoder3.encode(text);
13145
+ const encoder4 = new TextEncoder();
13146
+ const bytes = encoder4.encode(text);
12794
13147
  const hashArray = await crypto.subtle.digest("SHA-256", bytes);
12795
13148
  return Array.from(new Uint8Array(hashArray)).map((b) => b.toString(16).padStart(2, "0")).join("");
12796
13149
  }
12797
13150
  __name(sha256HexOfText, "sha256HexOfText");
12798
13151
  async function buildNoteKnowledge(title, content, origin, tag) {
12799
13152
  const sha2563 = await sha256HexOfText(content);
12800
- const encoder3 = new TextEncoder();
12801
- const size = encoder3.encode(content).byteLength;
13153
+ const encoder4 = new TextEncoder();
13154
+ const size = encoder4.encode(content).byteLength;
12802
13155
  return {
12803
13156
  title,
12804
13157
  content,
@@ -13957,7 +14310,7 @@ var memory = {
13957
14310
  resetPolicyStoreCache();
13958
14311
  },
13959
14312
  // ----- namespaced surfaces -----
13960
- /** Local operation journal (namespaced). No-op substrate when sqlite/idb unavailable. */
14313
+ /** Local operation journal (namespaced). Persisted on `store`. */
13961
14314
  journal: journal_default,
13962
14315
  /** Configure the optional cloud-sync layer (namespace + provider). Chainable. */
13963
14316
  configure(opts) {
@@ -17791,7 +18144,7 @@ var EPITEMIC_STATUSES2 = [
17791
18144
 
17792
18145
  // app.json
17793
18146
  var app_default = {
17794
- version: "0.1.7"};
18147
+ version: "0.1.8"};
17795
18148
 
17796
18149
  // index.ts
17797
18150
  var dotmem = {
@@ -17805,4 +18158,4 @@ var dotmem = {
17805
18158
  };
17806
18159
  var index_default = dotmem;
17807
18160
 
17808
- export { BUILT_IN_CONTEXT_FORMAT, BUILT_IN_CONTEXT_FORMAT_VERSION, CompactionEngine, ContextCompiler, ContextLifecycleOrchestrator, EPITEMIC_STATUSES2 as EPITEMIC_STATUSES, GOVERNANCE_POLICY_STATUSES, GOVERNANCE_ROLES, GovernancePolicyError, GovernancePolicyStore, GuardrailError, GuardrailService, MEMORY_CATEGORIES, RecoveryService, addDecision, addOpenLoopRef, addRejectedApproach, addUnresolvedQuestion, appendReasoningStep, assertBuiltInContextAvailable, canTransitionEpistemic, clearUserIdentity, closeConversationalState, compileContext, continuity, continuityLedger, createCompactionEngine, createConversationalState, createGuardrailService, createNoOpHost, createRecoveryService, index_default as default, deleteConversationalState, dotmem, encryption, getBuiltInContextDocuments, getBuiltInContextStatus, getCapabilities, getPlatform, idb, inspectMem, isBrowser, isBuiltInContextAvailable, isBun, isDeno, isEdge, isLegacyRecord, isNode, listUnfinishedConversations, loadAllConversationalStates, loadBuiltInContext, loadConversationalStateById, markDerivedStale, memory, normalizeLegacyRecord, normalizeProjectId, recoverConversation, resetBuiltInContextCache, resolveProjectIdentity, resolveUserAgentMemoryPath, resolveUserBrainPath, resolveUserContractPath, resolveUserDotMemPath, resolveUserExperiencePath, resolveUserIdentity, resolveUserProjectMemoryPath, resolveUserReadmePath, roleHasPermission, saveConversationalState, security, setUserIdentity, signMemPackage, updateConversationalState, validateDerivedLineage, validateEpistemicTransition, validatePolicyAuthority as validateGovernanceAuthority, validateMemoryItem, validateProvenance, validateRelationshipTargets, validateResolutionRequest };
18161
+ export { BUILT_IN_CONTEXT_FORMAT, BUILT_IN_CONTEXT_FORMAT_VERSION, CompactionEngine, ContextCompiler, ContextLifecycleOrchestrator, EPITEMIC_STATUSES2 as EPITEMIC_STATUSES, GOVERNANCE_POLICY_STATUSES, GOVERNANCE_ROLES, GovernancePolicyError, GovernancePolicyStore, GuardrailError, GuardrailService, MEMORY_CATEGORIES, RecoveryService, addDecision, addOpenLoopRef, addRejectedApproach, addUnresolvedQuestion, appendReasoningStep, assertBuiltInContextAvailable, canTransitionEpistemic, clearUserIdentity, closeConversationalState, compileContext, continuity, continuityLedger, createCompactionEngine, createConversationalState, createGuardrailService, createNoOpHost, createRecoveryService, index_default as default, deleteConversationalState, dotmem, encryption, getBuiltInContextDocuments, getBuiltInContextStatus, getCapabilities, getPlatform, inspectMem, isBrowser, isBuiltInContextAvailable, isBun, isDeno, isEdge, isLegacyRecord, isNode, listUnfinishedConversations, loadAllConversationalStates, loadBuiltInContext, loadConversationalStateById, markDerivedStale, memory, normalizeLegacyRecord, normalizeProjectId, recoverConversation, resetBuiltInContextCache, resolveProjectIdentity, resolveUserAgentMemoryPath, resolveUserBrainPath, resolveUserContractPath, resolveUserDotMemPath, resolveUserExperiencePath, resolveUserIdentity, resolveUserProjectMemoryPath, resolveUserReadmePath, roleHasPermission, saveConversationalState, security, setUserIdentity, signMemPackage, updateConversationalState, validateDerivedLineage, validateEpistemicTransition, validatePolicyAuthority as validateGovernanceAuthority, validateMemoryItem, validateProvenance, validateRelationshipTargets, validateResolutionRequest };