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.cjs CHANGED
@@ -32,18 +32,6 @@ var __export = (target, all) => {
32
32
  __defProp(target, name, { get: all[name], enumerable: true });
33
33
  };
34
34
 
35
- // core/suppress-idb-warning.ts
36
- var orig;
37
- var init_suppress_idb_warning = __esm({
38
- "core/suppress-idb-warning.ts"() {
39
- orig = console.warn.bind(console);
40
- console.warn = (...args) => {
41
- if (typeof args[0] === "string" && args[0].includes("IndexedDB is not available")) return;
42
- orig(...args);
43
- };
44
- }
45
- });
46
-
47
35
  // core/env.ts
48
36
  var DEV;
49
37
  var init_env = __esm({
@@ -119,6 +107,60 @@ var init_storage_paths = __esm({
119
107
  }
120
108
  });
121
109
 
110
+ // core/knowledge/text-encoding.ts
111
+ function detectBom(bytes) {
112
+ if (bytes.length >= 3 && bytes[0] === BOM_UTF8 && bytes[1] === 187 && bytes[2] === 191) {
113
+ return "utf-8";
114
+ }
115
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16LE_FIRST && bytes[1] === BOM_UTF16LE_SECOND) {
116
+ return "utf-16le";
117
+ }
118
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16BE_FIRST && bytes[1] === BOM_UTF16BE_SECOND) {
119
+ return "utf-16be";
120
+ }
121
+ return null;
122
+ }
123
+ function encodeText(value) {
124
+ return encoder.encode(value);
125
+ }
126
+ function decodeText(bytes, options = {}) {
127
+ const bom = detectBom(bytes);
128
+ if (bom === "utf-16le" || bom === "utf-16be") {
129
+ throw new UnsupportedEncodingError(
130
+ `UTF-16 encoded content detected in ${options.source ?? "unknown"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`
131
+ );
132
+ }
133
+ let content = bytes;
134
+ if (bom === "utf-8") {
135
+ content = bytes.subarray(3);
136
+ }
137
+ return strictDecoder.decode(content);
138
+ }
139
+ var encoder, strictDecoder, UnsupportedEncodingError, BOM_UTF8, BOM_UTF16LE_FIRST, BOM_UTF16LE_SECOND, BOM_UTF16BE_FIRST, BOM_UTF16BE_SECOND;
140
+ var init_text_encoding = __esm({
141
+ "core/knowledge/text-encoding.ts"() {
142
+ encoder = new TextEncoder();
143
+ strictDecoder = new TextDecoder("utf-8", { fatal: true });
144
+ UnsupportedEncodingError = class extends Error {
145
+ static {
146
+ __name(this, "UnsupportedEncodingError");
147
+ }
148
+ constructor(message) {
149
+ super(message);
150
+ this.name = "UnsupportedEncodingError";
151
+ }
152
+ };
153
+ BOM_UTF8 = 239;
154
+ BOM_UTF16LE_FIRST = 255;
155
+ BOM_UTF16LE_SECOND = 254;
156
+ BOM_UTF16BE_FIRST = 254;
157
+ BOM_UTF16BE_SECOND = 255;
158
+ __name(detectBom, "detectBom");
159
+ __name(encodeText, "encodeText");
160
+ __name(decodeText, "decodeText");
161
+ }
162
+ });
163
+
122
164
  // core/knowledge/storage-settings.ts
123
165
  var DOTMEM_STORAGE_SETTINGS_FILE_NAME, SETTINGS_MODES, projectRoot, findProjectSettingsFile, discoverProjectSettingsFilePath, resolveUserSettingsFilePath, invalidSettings, parseSettings, resolveSettingsEntry, readTextFile, readStorageSettings;
124
166
  var init_storage_settings = __esm({
@@ -250,15 +292,19 @@ function readDotMemStorageLocator() {
250
292
  const locatorFile = resolveLocatorFilePath(anchor);
251
293
  let raw;
252
294
  try {
253
- raw = fs2.readFileSync(locatorFile, "utf8");
295
+ raw = decodeText(fs2.readFileSync(locatorFile), { source: locatorFile });
254
296
  } catch (error) {
297
+ if (error instanceof UnsupportedEncodingError) {
298
+ throw new DotMemStorageLocationError(
299
+ `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.`
300
+ );
301
+ }
255
302
  const code = error?.code;
256
303
  if (code === "ENOENT") return null;
257
304
  throw new DotMemStorageLocationError(
258
305
  `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} cannot be read (${describeAccessFailure(error)}). No alternative location was selected automatically.`
259
306
  );
260
307
  }
261
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
262
308
  let parsed;
263
309
  try {
264
310
  parsed = JSON.parse(raw);
@@ -350,6 +396,7 @@ var DOTMEM_USER_ANCHOR_DIR_NAME, DOTMEM_STORAGE_LOCATOR_FILE_NAME, DOTMEM_STORAG
350
396
  var init_storage_location = __esm({
351
397
  "core/knowledge/storage-location.ts"() {
352
398
  init_storage_paths();
399
+ init_text_encoding();
353
400
  init_storage_settings();
354
401
  init_storage_paths();
355
402
  DOTMEM_USER_ANCHOR_DIR_NAME = ".dotmem";
@@ -1364,6 +1411,12 @@ var init_state = __esm({
1364
1411
  if (claim.sourceProject !== void 0 && !requiredText(claim.sourceProject)) {
1365
1412
  throw new Error(`Claim ${claim.id} has an invalid sourceProject`);
1366
1413
  }
1414
+ if (claim.check !== void 0) {
1415
+ const check = claim.check;
1416
+ 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)) {
1417
+ throw new Error(`Claim ${claim.id} has an invalid check`);
1418
+ }
1419
+ }
1367
1420
  return claim;
1368
1421
  }, "validateClaim");
1369
1422
  validateKnowledgeState = /* @__PURE__ */ __name((value) => {
@@ -1668,6 +1721,50 @@ var init_scope_eligibility = __esm({
1668
1721
  }
1669
1722
  });
1670
1723
 
1724
+ // core/knowledge/currentness.ts
1725
+ var asRecord, verifiedAtOf, findContestedIds, deriveCurrentness;
1726
+ var init_currentness = __esm({
1727
+ "core/knowledge/currentness.ts"() {
1728
+ asRecord = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0, "asRecord");
1729
+ verifiedAtOf = /* @__PURE__ */ __name((claim) => {
1730
+ const value = asRecord(claim.knowledge)?.verifiedAt;
1731
+ if (typeof value !== "string") return void 0;
1732
+ const parsed = Date.parse(value);
1733
+ return Number.isNaN(parsed) ? void 0 : parsed;
1734
+ }, "verifiedAtOf");
1735
+ findContestedIds = /* @__PURE__ */ __name((claims) => {
1736
+ const retracting = /* @__PURE__ */ new Map();
1737
+ for (const claim of claims) {
1738
+ if (claim.revision?.kind === "retracts" && claim.revision.claimIds.length > 0) {
1739
+ retracting.set(claim.id, new Set(claim.revision.claimIds));
1740
+ }
1741
+ }
1742
+ const contested = /* @__PURE__ */ new Set();
1743
+ for (const [id, targets] of retracting) {
1744
+ for (const target of targets) {
1745
+ if (retracting.get(target)?.has(id)) {
1746
+ contested.add(id);
1747
+ contested.add(target);
1748
+ }
1749
+ }
1750
+ }
1751
+ return contested;
1752
+ }, "findContestedIds");
1753
+ deriveCurrentness = /* @__PURE__ */ __name((claim, context2 = {}) => {
1754
+ const now3 = context2.now ?? Date.now();
1755
+ if (context2.contestedIds?.has(claim.id)) return "contested";
1756
+ if (claim.revision?.kind === "retracts") return "historical";
1757
+ if (context2.retractedIds?.has(claim.id)) return "historical";
1758
+ if (context2.supersededIds?.has(claim.id)) return "superseded";
1759
+ if (claim.expiresAt !== void 0 && now3 >= claim.expiresAt) return "expired";
1760
+ const verifiedAt = verifiedAtOf(claim);
1761
+ if (verifiedAt !== void 0) return "verified";
1762
+ if (claim.epistemicType === "verified") return "unverified";
1763
+ return "unknown-currentness";
1764
+ }, "deriveCurrentness");
1765
+ }
1766
+ });
1767
+
1671
1768
  // core/knowledge/discover.ts
1672
1769
  var diagnostic, DEFAULT_LIMITS, FIELD_ORDER, FIELD_WEIGHT, normalize, discoveryTerms, jsonText, fieldText, acquiredTime, isExpired, rankCandidate, discoverAcquiredExperience;
1673
1770
  var init_discover = __esm({
@@ -1675,6 +1772,7 @@ var init_discover = __esm({
1675
1772
  init_state();
1676
1773
  init_applicability();
1677
1774
  init_scope_eligibility();
1775
+ init_currentness();
1678
1776
  init_env();
1679
1777
  diagnostic = /* @__PURE__ */ __name((message) => {
1680
1778
  if (typeof process !== "undefined" && typeof process.stderr?.write === "function") {
@@ -1787,11 +1885,78 @@ var init_discover = __esm({
1787
1885
  throw new Error("Discovery maxCandidates must be a positive integer");
1788
1886
  }
1789
1887
  const queryTerms = discoveryTerms(situation);
1888
+ const offset = options.cursor?.offset ?? 0;
1889
+ if (!Number.isInteger(offset) || offset < 0) {
1890
+ throw new Error("Discovery cursor offset must be a non-negative integer");
1891
+ }
1892
+ if (options.cursor && options.cursor.knowledgeVersion !== validated.version) {
1893
+ return {
1894
+ knowledgeVersion: validated.version,
1895
+ depth,
1896
+ queryTerms,
1897
+ candidates: [],
1898
+ omissions: [],
1899
+ offset: 0,
1900
+ snapshotChanged: true
1901
+ };
1902
+ }
1790
1903
  const available = activeClaims(validated);
1904
+ const availableIds = new Set(available.map((claim) => claim.id));
1905
+ const retractedIds = /* @__PURE__ */ new Set();
1906
+ const supersededIds = /* @__PURE__ */ new Set();
1907
+ const contestedIds = findContestedIds(validated.claims);
1908
+ for (const claim of validated.claims) {
1909
+ if (claim.revision?.kind === "retracts") {
1910
+ for (const id of claim.revision.claimIds) retractedIds.add(id);
1911
+ }
1912
+ if (claim.revision?.kind === "supersedes") {
1913
+ for (const id of claim.revision.claimIds) supersededIds.add(id);
1914
+ }
1915
+ }
1916
+ const revisionOmissions = validated.claims.filter((claim) => !availableIds.has(claim.id)).map((claim) => {
1917
+ const retracted = retractedIds.has(claim.id);
1918
+ const superseded = supersededIds.has(claim.id);
1919
+ return {
1920
+ id: claim.id,
1921
+ reason: retracted ? "retracted" : superseded ? "superseded" : "retracted",
1922
+ gate: "revision-resolution",
1923
+ ...retracted || superseded ? {} : { detail: "the claim itself retracts prior knowledge and is kept as history" }
1924
+ };
1925
+ }).sort((left, right) => left.id.localeCompare(right.id));
1791
1926
  const scopeEligible = options.currentProjectId === void 0 ? available : available.filter((claim) => isScopeEligible(claim, options.currentProjectId, sources.get(claim.id)));
1792
1927
  const freshEligible = scopeEligible.filter((claim) => !isExpired(claim));
1928
+ const scopeEligibleIds = new Set(scopeEligible.map((claim) => claim.id));
1929
+ const scopeOmissions = available.filter((claim) => !scopeEligibleIds.has(claim.id)).map((claim) => {
1930
+ const owner = claimOwnerProject(claim, sources.get(claim.id));
1931
+ return {
1932
+ id: claim.id,
1933
+ reason: "scope",
1934
+ gate: "scope",
1935
+ detail: owner === void 0 ? "owner project could not be resolved" : `owned by project ${owner}`
1936
+ };
1937
+ }).sort((left, right) => left.id.localeCompare(right.id));
1938
+ const freshIds = new Set(freshEligible.map((claim) => claim.id));
1939
+ const freshnessOmissions = scopeEligible.filter((claim) => !freshIds.has(claim.id)).map((claim) => ({
1940
+ id: claim.id,
1941
+ reason: "expired",
1942
+ gate: "freshness",
1943
+ detail: `expired at ${new Date(claim.expiresAt).toISOString()}`
1944
+ })).sort((left, right) => left.id.localeCompare(right.id));
1793
1945
  const situationApplicability = deriveSituationApplicability(situation, options.facts);
1794
- const eligible = freshEligible.map((claim) => ({ claim, match: isEligibleByApplicability(claim, situationApplicability) })).filter((candidate) => candidate.match.eligible);
1946
+ const applicabilityMatches = new Map(
1947
+ freshEligible.map((claim) => [claim.id, isEligibleByApplicability(claim, situationApplicability)])
1948
+ );
1949
+ const eligible = freshEligible.map((claim) => ({ claim, match: applicabilityMatches.get(claim.id) })).filter((candidate) => candidate.match.eligible);
1950
+ const applicabilityOmissions = freshEligible.filter((claim) => !applicabilityMatches.get(claim.id).eligible).map((claim) => {
1951
+ const match = applicabilityMatches.get(claim.id);
1952
+ const mismatched = Object.entries(match.dimensions).filter(([, state4]) => state4 === "MISMATCH").map(([dimension]) => dimension);
1953
+ return {
1954
+ id: claim.id,
1955
+ reason: "applicability-mismatch",
1956
+ gate: "applicability",
1957
+ detail: `mismatching dimensions: ${mismatched.length > 0 ? mismatched.join(", ") : "none recorded"}`
1958
+ };
1959
+ }).sort((left, right) => left.id.localeCompare(right.id));
1795
1960
  if (DEV) {
1796
1961
  diagnostic(
1797
1962
  "[dotmem discovery] ACTIVE=" + JSON.stringify(
@@ -1803,12 +1968,15 @@ var init_discover = __esm({
1803
1968
  )
1804
1969
  );
1805
1970
  }
1971
+ const currentnessOf = /* @__PURE__ */ __name((claim) => deriveCurrentness(claim, { retractedIds, supersededIds, contestedIds }), "currentnessOf");
1806
1972
  if (queryTerms.length === 0) {
1807
- const baseline = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1973
+ const baselineAll = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1808
1974
  const leftTime = acquiredTime(left);
1809
1975
  const rightTime = acquiredTime(right);
1810
1976
  return rightTime - leftTime || Number(right.scope === "project") - Number(left.scope === "project") || left.id.localeCompare(right.id);
1811
- }).slice(0, maxCandidates);
1977
+ });
1978
+ const baseline = baselineAll.slice(offset, offset + maxCandidates);
1979
+ const limitOmissions = baselineAll.slice(offset + maxCandidates).map((claim) => ({ id: claim.id, reason: "limit", gate: "ranking" })).sort((left, right) => left.id.localeCompare(right.id));
1812
1980
  const baselineCandidates = baseline.map((claim) => {
1813
1981
  const explanation = {
1814
1982
  matchedTerms: [],
@@ -1821,7 +1989,8 @@ var init_discover = __esm({
1821
1989
  }
1822
1990
  return {
1823
1991
  claim,
1824
- explanation
1992
+ explanation,
1993
+ currentness: currentnessOf(claim)
1825
1994
  };
1826
1995
  });
1827
1996
  if (DEV) {
@@ -1834,10 +2003,18 @@ var init_discover = __esm({
1834
2003
  depth,
1835
2004
  queryTerms,
1836
2005
  situationApplicability,
1837
- candidates: baselineCandidates
2006
+ candidates: baselineCandidates,
2007
+ offset,
2008
+ omissions: [
2009
+ ...revisionOmissions,
2010
+ ...scopeOmissions,
2011
+ ...freshnessOmissions,
2012
+ ...applicabilityOmissions,
2013
+ ...limitOmissions
2014
+ ]
1838
2015
  };
1839
2016
  }
1840
- const candidates = eligible.map(
2017
+ const ranked = eligible.map(
1841
2018
  (candidate) => rankCandidate(
1842
2019
  candidate.claim,
1843
2020
  situation,
@@ -1849,16 +2026,40 @@ var init_discover = __esm({
1849
2026
  (candidate) => candidate !== null
1850
2027
  ).sort(
1851
2028
  (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)
1852
- ).slice(0, maxCandidates).map(({ claim, explanation }) => ({
2029
+ );
2030
+ const rankedIds = new Set(ranked.map((candidate) => candidate.claim.id));
2031
+ const rankingOmissions = [
2032
+ ...eligible.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2033
+ id: candidate.claim.id,
2034
+ reason: "no-term-match",
2035
+ gate: "ranking",
2036
+ detail: "passed every gate but shares no query term"
2037
+ })),
2038
+ ...ranked.slice(offset + maxCandidates).map((candidate) => ({
2039
+ id: candidate.claim.id,
2040
+ reason: "limit",
2041
+ gate: "ranking"
2042
+ }))
2043
+ ].sort((left, right) => left.id.localeCompare(right.id));
2044
+ const candidates = ranked.slice(offset, offset + maxCandidates).map(({ claim, explanation }) => ({
1853
2045
  claim,
1854
- explanation
2046
+ explanation,
2047
+ currentness: currentnessOf(claim)
1855
2048
  }));
1856
2049
  return {
1857
2050
  knowledgeVersion: validated.version,
1858
2051
  depth,
1859
2052
  queryTerms,
1860
2053
  situationApplicability,
1861
- candidates
2054
+ candidates,
2055
+ offset,
2056
+ omissions: [
2057
+ ...revisionOmissions,
2058
+ ...scopeOmissions,
2059
+ ...freshnessOmissions,
2060
+ ...applicabilityOmissions,
2061
+ ...rankingOmissions
2062
+ ]
1862
2063
  };
1863
2064
  }, "discoverAcquiredExperience");
1864
2065
  }
@@ -2915,7 +3116,7 @@ var init_policy_store = __esm({
2915
3116
  });
2916
3117
 
2917
3118
  // core/knowledge/acquisition-limits.ts
2918
- var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder, serializedBytes, measureKnowledge, checkAcquireLimits;
3119
+ var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder2, serializedBytes, measureKnowledge, checkAcquireLimits;
2919
3120
  var init_acquisition_limits = __esm({
2920
3121
  "core/knowledge/acquisition-limits.ts"() {
2921
3122
  MEMORY_ACQUIRE_LIMITS = Object.freeze({
@@ -2974,10 +3175,10 @@ var init_acquisition_limits = __esm({
2974
3175
  this.name = "MemoryAcquireDuplicateClaimError";
2975
3176
  }
2976
3177
  };
2977
- encoder = new TextEncoder();
3178
+ encoder2 = new TextEncoder();
2978
3179
  serializedBytes = /* @__PURE__ */ __name((value) => {
2979
3180
  const json = JSON.stringify(value);
2980
- return json === void 0 ? 0 : encoder.encode(json).length;
3181
+ return json === void 0 ? 0 : encoder2.encode(json).length;
2981
3182
  }, "serializedBytes");
2982
3183
  measureKnowledge = /* @__PURE__ */ __name((knowledge) => {
2983
3184
  const claimBytes = serializedBytes(knowledge);
@@ -3071,7 +3272,7 @@ var init_context_constants = __esm({
3071
3272
  });
3072
3273
 
3073
3274
  // core/knowledge/project.ts
3074
- var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_MAX_CHARACTERS, projectCandidate, renderHeader, renderExperience, renderText, projectDiscoveredExperience;
3275
+ 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;
3075
3276
  var init_project = __esm({
3076
3277
  "core/knowledge/project.ts"() {
3077
3278
  init_state();
@@ -3096,9 +3297,29 @@ var init_project = __esm({
3096
3297
  ...claim.provenance ? { provenance: claim.provenance } : {},
3097
3298
  ...claim.acquiredAt ? { acquiredAt: claim.acquiredAt } : {},
3098
3299
  ...claim.revision ? { revision: claim.revision } : {},
3099
- ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {}
3300
+ ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {},
3301
+ ...candidate.currentness ? { currentness: candidate.currentness } : {}
3100
3302
  });
3101
3303
  }, "projectCandidate");
3304
+ GIST_MAX_LENGTH = 80;
3305
+ GIST_KEYS = ["gist", "summary", "statement", "title", "reason", "principle", "finding", "detail"];
3306
+ MANIFEST_ID_LIMIT = 40;
3307
+ deriveGist = /* @__PURE__ */ __name((knowledge) => {
3308
+ if (typeof knowledge === "string") {
3309
+ return knowledge.length > GIST_MAX_LENGTH ? `${knowledge.slice(0, GIST_MAX_LENGTH)}\u2026` : knowledge;
3310
+ }
3311
+ if (knowledge && typeof knowledge === "object" && !Array.isArray(knowledge)) {
3312
+ const obj = knowledge;
3313
+ for (const key of GIST_KEYS) {
3314
+ const value = obj[key];
3315
+ if (typeof value === "string" && value.length > 0) {
3316
+ return value.length > GIST_MAX_LENGTH ? `${value.slice(0, GIST_MAX_LENGTH)}\u2026` : value;
3317
+ }
3318
+ }
3319
+ }
3320
+ const str = JSON.stringify(knowledge);
3321
+ return str.length > GIST_MAX_LENGTH ? `${str.slice(0, GIST_MAX_LENGTH)}\u2026` : str;
3322
+ }, "deriveGist");
3102
3323
  renderHeader = /* @__PURE__ */ __name((knowledgeVersion, totalCandidates) => {
3103
3324
  const lines = [
3104
3325
  `DOTMEM STORAGE: ${resolveUserDotMemPath()}`,
@@ -3124,27 +3345,70 @@ var init_project = __esm({
3124
3345
  evidence.supports ?? null
3125
3346
  ]),
3126
3347
  ...experience.epistemicType ? { epistemic: experience.epistemicType } : {},
3348
+ ...experience.currentness ? { currentness: experience.currentness } : {},
3127
3349
  ...experience.provenance ? { provenance: [experience.provenance.source, experience.provenance.detail ?? null] } : {},
3128
3350
  ...experience.acquiredAt ? { acquiredAt: experience.acquiredAt } : {},
3129
3351
  ...experience.revision ? { revision: experience.revision } : {},
3130
3352
  ...experience.sourceId ? { source: experience.sourceId } : {}
3131
3353
  }), "renderExperience");
3132
- renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates) => `${header}${experiences.length ? `
3133
- ${experiences.map(renderExperience).join("\n")}` : ""}
3134
- OMITTED:${omittedCandidates}`, "renderText");
3354
+ renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, render = renderExperience, currentnessSummary) => {
3355
+ const lines = [header];
3356
+ if (experiences.length > 0) lines.push(...experiences.map(render));
3357
+ lines.push(`OMITTED:${omittedCandidates}`);
3358
+ if (manifest && manifest.byReason.length > 0) {
3359
+ lines.push(`OMITTED_BY_REASON:${manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`);
3360
+ }
3361
+ if (manifest && manifest.items.length > 0) {
3362
+ lines.push(`OMITTED_IDS:${manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`);
3363
+ if (manifest.items.length > MANIFEST_ID_LIMIT) {
3364
+ lines.push(`OMITTED_IDS_TRUNCATED:${manifest.items.length - MANIFEST_ID_LIMIT}`);
3365
+ }
3366
+ }
3367
+ if (currentnessSummary) {
3368
+ lines.push(`CURRENTNESS:${currentnessSummary}`);
3369
+ }
3370
+ return lines.join("\n");
3371
+ }, "renderText");
3372
+ byteLength = /* @__PURE__ */ __name((value) => new TextEncoder().encode(value).length, "byteLength");
3373
+ summarizeOmissions = /* @__PURE__ */ __name((items) => {
3374
+ const counts = /* @__PURE__ */ new Map();
3375
+ for (const item of items) counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
3376
+ return [...counts.entries()].map(([reason, count]) => ({ reason, count })).sort((left, right) => left.reason.localeCompare(right.reason));
3377
+ }, "summarizeOmissions");
3378
+ renderManifestFitting = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, maxCharacters, render, currentnessSummary) => {
3379
+ const full = renderText(header, experiences, omittedCandidates, manifest, render, currentnessSummary);
3380
+ if (byteLength(full) <= maxCharacters) return full;
3381
+ const withoutIds = { ...manifest, items: [] };
3382
+ return renderText(header, experiences, omittedCandidates, withoutIds, render, currentnessSummary);
3383
+ }, "renderManifestFitting");
3384
+ renderCompactExperience = /* @__PURE__ */ __name((experience) => JSON.stringify({
3385
+ id: experience.id,
3386
+ status: "candidate",
3387
+ gist: deriveGist(experience.experience),
3388
+ epistemic: experience.epistemicType ?? null,
3389
+ currentness: experience.currentness ?? null,
3390
+ ...experience.revision ? { revision: experience.revision.kind } : {}
3391
+ }), "renderCompactExperience");
3135
3392
  projectDiscoveredExperience = /* @__PURE__ */ __name((discovery, options = {}) => {
3136
3393
  if (!discovery || !Number.isInteger(discovery.knowledgeVersion) || discovery.knowledgeVersion < 0 || !Array.isArray(discovery.candidates)) {
3137
3394
  throw new Error("Valid DiscoveryResult is required for context projection");
3138
3395
  }
3139
3396
  const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES;
3140
3397
  const maxCharacters = options.maxCharacters ?? DEFAULT_MAX_CHARACTERS;
3398
+ const format = options.format ?? "compact";
3399
+ if (format !== "compact" && format !== "standard" && format !== "full") {
3400
+ throw new Error("Projection format must be compact, standard or full");
3401
+ }
3141
3402
  if (!Number.isInteger(maxCandidates) || maxCandidates < 1) throw new Error("Projection maxCandidates must be a positive integer");
3142
3403
  if (!Number.isInteger(maxCharacters) || maxCharacters < MIN_MAX_CHARACTERS) {
3143
3404
  throw new Error(`Projection maxCharacters must be an integer of at least ${MIN_MAX_CHARACTERS}`);
3144
3405
  }
3145
- const totalCandidates = discovery.candidates.length;
3406
+ const render = /* @__PURE__ */ __name((experience) => format === "compact" ? renderCompactExperience(experience) : renderExperience(experience), "render");
3407
+ const gateOmissions = discovery.omissions ?? [];
3408
+ const totalCandidates = discovery.candidates.length + gateOmissions.length;
3146
3409
  const header = renderHeader(discovery.knowledgeVersion, totalCandidates);
3147
- if (renderText(header, [], totalCandidates).length > maxCharacters) {
3410
+ const emptyManifest = { considered: totalCandidates, included: 0, items: [], byReason: [] };
3411
+ if (byteLength(renderText(header, [], totalCandidates, emptyManifest)) > maxCharacters) {
3148
3412
  throw new Error("Projection maxCharacters is too small for the projection envelope");
3149
3413
  }
3150
3414
  const experiences = [];
@@ -3153,12 +3417,49 @@ OMITTED:${omittedCandidates}`, "renderText");
3153
3417
  const projected = projectCandidate(candidate);
3154
3418
  const possibleExperiences = [...experiences, projected];
3155
3419
  const possibleOmitted = totalCandidates - possibleExperiences.length;
3156
- if (renderText(header, possibleExperiences, possibleOmitted).length <= maxCharacters) {
3420
+ const candidateManifest = {
3421
+ considered: totalCandidates,
3422
+ included: possibleExperiences.length,
3423
+ items: gateOmissions,
3424
+ byReason: summarizeOmissions(gateOmissions)
3425
+ };
3426
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, candidateManifest, render)) <= maxCharacters) {
3427
+ experiences.push(projected);
3428
+ continue;
3429
+ }
3430
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, void 0, render)) <= maxCharacters) {
3157
3431
  experiences.push(projected);
3158
3432
  }
3159
3433
  }
3434
+ const projectedIds = new Set(experiences.map((experience) => experience.id));
3435
+ const budgetOmissions = discovery.candidates.filter((candidate) => !projectedIds.has(candidate.claim.id)).map((candidate) => ({ id: candidate.claim.id, reason: "budget", gate: "projection" }));
3436
+ const items = [...gateOmissions, ...budgetOmissions];
3160
3437
  const omittedCandidates = totalCandidates - experiences.length;
3161
- const text = renderText(header, experiences, omittedCandidates);
3438
+ const manifest = {
3439
+ considered: totalCandidates,
3440
+ included: experiences.length,
3441
+ items,
3442
+ byReason: summarizeOmissions(items)
3443
+ };
3444
+ const currentnessCounts = /* @__PURE__ */ new Map();
3445
+ for (const experience of experiences) {
3446
+ if (experience.currentness) {
3447
+ currentnessCounts.set(
3448
+ experience.currentness,
3449
+ (currentnessCounts.get(experience.currentness) ?? 0) + 1
3450
+ );
3451
+ }
3452
+ }
3453
+ const currentnessSummary = currentnessCounts.size > 0 ? [...currentnessCounts.entries()].map(([state3, count]) => `${state3}=${count}`).join(",") : void 0;
3454
+ const text = renderManifestFitting(
3455
+ header,
3456
+ experiences,
3457
+ omittedCandidates,
3458
+ manifest,
3459
+ maxCharacters,
3460
+ render,
3461
+ currentnessSummary
3462
+ );
3162
3463
  return {
3163
3464
  format: FORMAT,
3164
3465
  status: STATUS,
@@ -3167,6 +3468,7 @@ OMITTED:${omittedCandidates}`, "renderText");
3167
3468
  totalCandidates,
3168
3469
  omittedCandidates,
3169
3470
  experiences,
3471
+ manifest,
3170
3472
  text
3171
3473
  };
3172
3474
  }, "projectDiscoveredExperience");
@@ -3204,7 +3506,7 @@ var init_language_detect = __esm({
3204
3506
  var CANONICAL_KINDS, validateKind, buildClaimRecord;
3205
3507
  var init_claim_record = __esm({
3206
3508
  "core/knowledge/claim-record.ts"() {
3207
- CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note"];
3509
+ CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note", "rule"];
3208
3510
  validateKind = /* @__PURE__ */ __name((kind) => {
3209
3511
  if (!CANONICAL_KINDS.includes(kind)) {
3210
3512
  throw new Error(
@@ -4435,8 +4737,8 @@ var init_browser = __esm({
4435
4737
  this.p = null;
4436
4738
  }
4437
4739
  };
4438
- Unzip2.prototype.register = function(decoder2) {
4439
- this.o[decoder2.compression] = decoder2;
4740
+ Unzip2.prototype.register = function(decoder) {
4741
+ this.o[decoder.compression] = decoder;
4440
4742
  };
4441
4743
  return Unzip2;
4442
4744
  })();
@@ -4456,6 +4758,15 @@ function encodeMemFile(stateValue, preserved) {
4456
4758
  if (!map.claim.includes("kind")) {
4457
4759
  map.claim.push("kind");
4458
4760
  }
4761
+ if (!map.claim.includes("expires-at")) {
4762
+ map.claim.push("expires-at");
4763
+ }
4764
+ if (!map.claim.includes("bootstrap-priority")) {
4765
+ map.claim.push("bootstrap-priority");
4766
+ }
4767
+ if (!map.claim.includes("check")) {
4768
+ map.claim.push("check");
4769
+ }
4459
4770
  const indexes = Object.fromEntries(Object.keys(expectedFields).map((name) => [name, fieldIndexes(map, name)]));
4460
4771
  validateVocabulary(map.epistemicType, epistemicTypes, "epistemicType");
4461
4772
  validateVocabulary(map.revisionKind, revisionKinds, "revisionKind");
@@ -4505,6 +4816,15 @@ function encodeMemFile(stateValue, preserved) {
4505
4816
  if (indexes.claim.has("kind")) {
4506
4817
  putOptional(record, indexes.claim, "kind", claim.kind ?? void 0, original !== void 0);
4507
4818
  }
4819
+ if (indexes.claim.has("expires-at")) {
4820
+ putOptional(record, indexes.claim, "expires-at", claim.expiresAt, original !== void 0);
4821
+ }
4822
+ if (indexes.claim.has("bootstrap-priority")) {
4823
+ putOptional(record, indexes.claim, "bootstrap-priority", claim.bootstrapPriority, original !== void 0);
4824
+ }
4825
+ if (indexes.claim.has("check")) {
4826
+ putOptional(record, indexes.claim, "check", claim.check, original !== void 0);
4827
+ }
4508
4828
  return original ? record : trimRecord(record);
4509
4829
  }, "encodeClaim");
4510
4830
  const stateRecord = structuredClone(preserved?.data ?? []);
@@ -4573,8 +4893,37 @@ function decodeMemDocument(value) {
4573
4893
  const scope = optionalGet(record, indexes.claim, "scope");
4574
4894
  const sourceProject = optionalGet(record, indexes.claim, "source-project");
4575
4895
  const kindValue = optionalGet(record, indexes.claim, "kind");
4896
+ const expiresAtValue = indexes.claim.has("expires-at") ? optionalGet(record, indexes.claim, "expires-at") : void 0;
4897
+ const bootstrapPriorityValue = indexes.claim.has("bootstrap-priority") ? optionalGet(record, indexes.claim, "bootstrap-priority") : void 0;
4898
+ const checkValue = indexes.claim.has("check") ? optionalGet(record, indexes.claim, "check") : void 0;
4576
4899
  if (epistemicIndex !== void 0 && (!Number.isInteger(epistemicIndex) || epistemicIndex < 0 || epistemicIndex >= epistemic.length)) throw new Error("Invalid .mem epistemic value");
4577
4900
  if (kindIndex !== void 0 && (!Number.isInteger(kindIndex) || kindIndex < 0 || kindIndex >= revisions.length)) throw new Error("Invalid .mem revision value");
4901
+ if (expiresAtValue !== void 0 && (!Number.isInteger(expiresAtValue) || expiresAtValue < 0)) {
4902
+ throw new Error("Invalid .mem expiresAt value");
4903
+ }
4904
+ if (bootstrapPriorityValue !== void 0 && !bootstrapPriorities.includes(bootstrapPriorityValue)) {
4905
+ throw new Error("Invalid .mem bootstrapPriority value");
4906
+ }
4907
+ let check;
4908
+ if (checkValue !== void 0) {
4909
+ if (!checkValue || typeof checkValue !== "object" || Array.isArray(checkValue)) {
4910
+ throw new Error("Invalid .mem check record");
4911
+ }
4912
+ const checkRecord = checkValue;
4913
+ const description = checkRecord.description;
4914
+ if (typeof description !== "undefined" && typeof description !== "string") {
4915
+ throw new Error("Invalid .mem check record");
4916
+ }
4917
+ if (checkRecord.kind !== "regex" || typeof checkRecord.pattern !== "string" || checkRecord.pattern.length === 0 || !checkTargets.includes(checkRecord.on)) {
4918
+ throw new Error("Invalid .mem check record");
4919
+ }
4920
+ check = {
4921
+ kind: "regex",
4922
+ pattern: checkRecord.pattern,
4923
+ on: checkRecord.on,
4924
+ ...typeof description === "string" ? { description } : {}
4925
+ };
4926
+ }
4578
4927
  const understoodEpistemic = typeof epistemicIndex === "number" && epistemicTypes.includes(epistemic[epistemicIndex]) ? epistemic[epistemicIndex] : void 0;
4579
4928
  const understoodRevision = typeof kindIndex === "number" && revisionKinds.includes(revisions[kindIndex]);
4580
4929
  const claim = {
@@ -4599,6 +4948,9 @@ function decodeMemDocument(value) {
4599
4948
  } : {},
4600
4949
  ...scope === void 0 ? {} : { scope },
4601
4950
  ...sourceProject === void 0 ? {} : { sourceProject },
4951
+ ...expiresAtValue === void 0 ? {} : { expiresAt: expiresAtValue },
4952
+ ...bootstrapPriorityValue === void 0 ? {} : { bootstrapPriority: bootstrapPriorityValue },
4953
+ ...check === void 0 ? {} : { check },
4602
4954
  ...claimKinds.includes(kindValue) ? { kind: kindValue } : {}
4603
4955
  };
4604
4956
  return validateClaim(claim);
@@ -4608,7 +4960,7 @@ function decodeMemDocument(value) {
4608
4960
  preserved: { map: structuredClone(map), data: structuredClone(stateRecord) }
4609
4961
  };
4610
4962
  }
4611
- 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;
4963
+ 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;
4612
4964
  var init_mem_codec = __esm({
4613
4965
  "core/knowledge/mem-codec.ts"() {
4614
4966
  init_state();
@@ -4625,7 +4977,9 @@ var init_mem_codec = __esm({
4625
4977
  };
4626
4978
  epistemicTypes = ["observed", "inferred", "human-stated", "verified"];
4627
4979
  revisionKinds = ["refines", "supersedes", "retracts"];
4628
- claimKinds = ["experience", "agent", "relationship", "logic", "note"];
4980
+ claimKinds = ["experience", "agent", "relationship", "logic", "note", "rule"];
4981
+ bootstrapPriorities = ["P1", "P2", "P3", "P4", "P5", "unclassified"];
4982
+ checkTargets = ["staged", "committed", "working-tree"];
4629
4983
  isJsonValue2 = /* @__PURE__ */ __name((value) => {
4630
4984
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
4631
4985
  if (typeof value === "number") return Number.isFinite(value);
@@ -4729,14 +5083,14 @@ async function signMemPackage(input, privateKey, publicKey) {
4729
5083
  });
4730
5084
  }
4731
5085
  async function decodeMemArtifact(input) {
4732
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
5086
+ const bytes = typeof input === "string" ? encoder3.encode(input) : input;
4733
5087
  if (isZip(bytes)) {
4734
5088
  const { parts: _parts, integrity: _integrity, ...artifact } = await decodePackage(bytes);
4735
5089
  return artifact;
4736
5090
  }
4737
5091
  let value;
4738
5092
  try {
4739
- value = JSON.parse(decoder.decode(bytes).replace(/^\uFEFF/, ""));
5093
+ value = JSON.parse(decodeText(bytes));
4740
5094
  } catch (error) {
4741
5095
  throw new MemArtifactError("corrupt", `Unsupported or corrupt MEM artifact: ${error.message}`);
4742
5096
  }
@@ -4751,7 +5105,7 @@ async function decodeMemArtifact(input) {
4751
5105
  }
4752
5106
  async function inspectMem(input) {
4753
5107
  try {
4754
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
5108
+ const bytes = typeof input === "string" ? encodeText(input) : input;
4755
5109
  if (isZip(bytes)) {
4756
5110
  const artifact2 = await decodePackage(bytes);
4757
5111
  const knownMapKeys = /* @__PURE__ */ new Set(["state", "claim", "evidence", "provenance", "revision", "epistemicType", "revisionKind"]);
@@ -4792,11 +5146,12 @@ async function inspectMem(input) {
4792
5146
  return { status: artifactError.code, representation: "unknown", message: artifactError.message, parts: [] };
4793
5147
  }
4794
5148
  }
4795
- 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;
5149
+ 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;
4796
5150
  var init_mem_package = __esm({
4797
5151
  "core/knowledge/mem-package.ts"() {
4798
5152
  init_browser();
4799
5153
  init_mem_codec();
5154
+ init_text_encoding();
4800
5155
  MEM_PACKAGE_FORMAT = "dotmem.package";
4801
5156
  MEM_PACKAGE_FORMAT_LEGACY = "memorio.package";
4802
5157
  MEM_PACKAGE_VERSION = 1;
@@ -4820,8 +5175,7 @@ var init_mem_package = __esm({
4820
5175
  DATA_PATH = "memory/data.json";
4821
5176
  INTEGRITY_PATH = "security/integrity.json";
4822
5177
  requiredParts = [MANIFEST_PATH, MAP_PATH, DATA_PATH];
4823
- encoder2 = new TextEncoder();
4824
- decoder = new TextDecoder("utf-8", { fatal: true });
5178
+ encoder3 = new TextEncoder();
4825
5179
  MemArtifactError = class extends Error {
4826
5180
  constructor(code, message) {
4827
5181
  super(message);
@@ -4840,7 +5194,7 @@ var init_mem_package = __esm({
4840
5194
  }
4841
5195
  return value;
4842
5196
  }, "stableValue");
4843
- jsonBytes = /* @__PURE__ */ __name((value) => encoder2.encode(`${JSON.stringify(stableValue(value), null, 2)}
5197
+ jsonBytes = /* @__PURE__ */ __name((value) => encoder3.encode(`${JSON.stringify(stableValue(value), null, 2)}
4844
5198
  `), "jsonBytes");
4845
5199
  sha256 = /* @__PURE__ */ __name(async (data) => {
4846
5200
  if (!globalThis.crypto?.subtle) throw new MemArtifactError("unsupported", "SHA-256 is unavailable in this runtime");
@@ -4849,7 +5203,7 @@ var init_mem_package = __esm({
4849
5203
  }, "sha256");
4850
5204
  parseJson = /* @__PURE__ */ __name((bytes, path2) => {
4851
5205
  try {
4852
- return JSON.parse(decoder.decode(bytes));
5206
+ return JSON.parse(decodeText(bytes));
4853
5207
  } catch (error) {
4854
5208
  throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path2}: ${error.message}`);
4855
5209
  }
@@ -4915,7 +5269,7 @@ var init_mem_package = __esm({
4915
5269
  parts: { map: MAP_PATH, data: DATA_PATH, integrity: INTEGRITY_PATH }
4916
5270
  }), "createManifest");
4917
5271
  digestTableIdentity = /* @__PURE__ */ __name((files) => sha256(jsonBytes(files)), "digestTableIdentity");
4918
- signaturePayload = /* @__PURE__ */ __name((contentId) => encoder2.encode(`DOTMEM-PACKAGE-SIGNATURE-V1
5272
+ signaturePayload = /* @__PURE__ */ __name((contentId) => encoder3.encode(`DOTMEM-PACKAGE-SIGNATURE-V1
4919
5273
  ${contentId}
4920
5274
  `), "signaturePayload");
4921
5275
  base64UrlEncode = /* @__PURE__ */ __name((value) => {
@@ -5105,10 +5459,12 @@ ${contentId}
5105
5459
  });
5106
5460
 
5107
5461
  // core/storage-coordinator/index.ts
5108
- var nodeFs4, withStorageLock, readStorageGeneration, writeStorageGeneration;
5462
+ var nodeFs4, heldLocks, withStorageLock, readStorageGeneration, writeStorageGeneration;
5109
5463
  var init_storage_coordinator = __esm({
5110
5464
  "core/storage-coordinator/index.ts"() {
5465
+ init_text_encoding();
5111
5466
  nodeFs4 = /* @__PURE__ */ __name(async () => import('fs/promises'), "nodeFs");
5467
+ heldLocks = /* @__PURE__ */ new Map();
5112
5468
  withStorageLock = /* @__PURE__ */ __name(async (directoryPath, operationOrOptions, operation, _options = {}) => {
5113
5469
  const opts = typeof operationOrOptions === "function" ? operation ?? {} : operationOrOptions ?? {};
5114
5470
  const op = typeof operationOrOptions === "function" ? operationOrOptions : operation;
@@ -5118,6 +5474,15 @@ var init_storage_coordinator = __esm({
5118
5474
  const lockPath = `${directoryPath}/${lockName}`;
5119
5475
  const fs2 = await nodeFs4();
5120
5476
  const started = Date.now();
5477
+ const heldDepth = heldLocks.get(lockPath) ?? 0;
5478
+ if (heldDepth > 0) {
5479
+ heldLocks.set(lockPath, heldDepth + 1);
5480
+ try {
5481
+ return await op();
5482
+ } finally {
5483
+ heldLocks.set(lockPath, heldDepth);
5484
+ }
5485
+ }
5121
5486
  await fs2.mkdir(directoryPath, { recursive: true });
5122
5487
  while (true) {
5123
5488
  try {
@@ -5131,8 +5496,8 @@ var init_storage_coordinator = __esm({
5131
5496
  let stale = false;
5132
5497
  let processDead = false;
5133
5498
  try {
5134
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5135
- const parsed = JSON.parse(raw);
5499
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5500
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
5136
5501
  const ageStale = typeof parsed.createdAt === "number" && Date.now() - parsed.createdAt > staleMs;
5137
5502
  if (typeof parsed.pid === "number") {
5138
5503
  try {
@@ -5169,17 +5534,19 @@ var init_storage_coordinator = __esm({
5169
5534
  }
5170
5535
  let token = "";
5171
5536
  try {
5172
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5173
- token = JSON.parse(raw).token ?? "";
5537
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5538
+ token = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` })).token ?? "";
5174
5539
  } catch {
5175
5540
  token = "";
5176
5541
  }
5177
5542
  try {
5543
+ heldLocks.set(lockPath, 1);
5178
5544
  return await op();
5179
5545
  } finally {
5546
+ heldLocks.delete(lockPath);
5180
5547
  try {
5181
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5182
- const parsed = JSON.parse(raw);
5548
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5549
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
5183
5550
  if (parsed.token === token && token) {
5184
5551
  await fs2.rm(lockPath, { recursive: true, force: true });
5185
5552
  }
@@ -5190,8 +5557,8 @@ var init_storage_coordinator = __esm({
5190
5557
  readStorageGeneration = /* @__PURE__ */ __name(async (directoryPath) => {
5191
5558
  const fs2 = await nodeFs4();
5192
5559
  try {
5193
- const raw = await fs2.readFile(`${directoryPath}/.storage.generation`, "utf8");
5194
- const value = Number(raw.trim());
5560
+ const raw = await fs2.readFile(`${directoryPath}/.storage.generation`);
5561
+ const value = Number(decodeText(raw, { source: `${directoryPath}/.storage.generation` }).trim());
5195
5562
  return Number.isFinite(value) && value >= 0 ? value : 0;
5196
5563
  } catch {
5197
5564
  return 0;
@@ -5720,12 +6087,11 @@ function readJsonFile(path2) {
5720
6087
  if (!fs2) return null;
5721
6088
  let raw;
5722
6089
  try {
5723
- raw = fs2.readFileSync(path2, "utf8");
6090
+ raw = decodeText(fs2.readFileSync(path2), { source: path2 });
5724
6091
  } catch {
5725
6092
  return null;
5726
6093
  }
5727
6094
  if (typeof raw !== "string") return null;
5728
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
5729
6095
  try {
5730
6096
  return JSON.parse(raw);
5731
6097
  } catch {
@@ -5849,6 +6215,7 @@ var init_user_language = __esm({
5849
6215
  "core/knowledge/user-language.ts"() {
5850
6216
  init_user_paths();
5851
6217
  init_storage_paths();
6218
+ init_text_encoding();
5852
6219
  USER_LANGUAGE_FILE_NAME = "language.json";
5853
6220
  USER_LANGUAGE_PREFERENCE_FILE_NAME = "user-language.json";
5854
6221
  LANGUAGE_PREFERENCE_FILE_NAME = "language-preference.json";
@@ -9572,10 +9939,13 @@ var init_staging = __esm({
9572
9939
  epistemicType: sanitizedClaim.epistemicType,
9573
9940
  provenance: sanitizedClaim.provenance,
9574
9941
  acquiredAt: sanitizedClaim.acquiredAt,
9942
+ ...sanitizedClaim.expiresAt === void 0 ? {} : { expiresAt: sanitizedClaim.expiresAt },
9943
+ ...sanitizedClaim.bootstrapPriority === void 0 ? {} : { bootstrapPriority: sanitizedClaim.bootstrapPriority },
9575
9944
  revision,
9576
9945
  scope,
9577
9946
  sourceProject,
9578
- kind
9947
+ kind,
9948
+ ...sanitizedClaim.check === void 0 ? {} : { check: sanitizedClaim.check }
9579
9949
  });
9580
9950
  await withStoreQueue(acquisitionStoreKey(kind, scope, sourceProject), async () => {
9581
9951
  const state3 = await target.runtime.select([]);
@@ -9823,19 +10193,19 @@ var init_incidents = __esm({
9823
10193
  }
9824
10194
  });
9825
10195
 
9826
- // core/knowledge/rules-loader.ts
9827
- var init_rules_loader = __esm({
9828
- "core/knowledge/rules-loader.ts"() {
9829
- init_state();
9830
- }
9831
- });
9832
-
9833
10196
  // core/knowledge/violations.ts
9834
10197
  var init_violations = __esm({
9835
10198
  "core/knowledge/violations.ts"() {
9836
10199
  init_user_paths();
9837
10200
  }
9838
10201
  });
10202
+ var init_rules_loader = __esm({
10203
+ "core/knowledge/rules-loader.ts"() {
10204
+ init_state();
10205
+ init_user_paths();
10206
+ init_violations();
10207
+ }
10208
+ });
9839
10209
 
9840
10210
  // core/knowledge/session.ts
9841
10211
  function joinPath5(base, child) {
@@ -10342,8 +10712,8 @@ function loadBuiltInContext() {
10342
10712
  for (const candidate of candidates) {
10343
10713
  if (!fs__default.default.existsSync(candidate)) continue;
10344
10714
  try {
10345
- const raw = fs__default.default.readFileSync(candidate, "utf8");
10346
- const parsed = JSON.parse(raw);
10715
+ const raw = fs__default.default.readFileSync(candidate);
10716
+ const parsed = JSON.parse(decodeText(raw, { source: candidate }));
10347
10717
  const artifact = validateArtifact(parsed);
10348
10718
  cached = artifact;
10349
10719
  cachedStatus = {
@@ -10420,6 +10790,7 @@ function resetBuiltInContextCache() {
10420
10790
  exports.BUILT_IN_CONTEXT_FORMAT = void 0; exports.BUILT_IN_CONTEXT_FORMAT_VERSION = void 0; var cached, cachedStatus, _artifactPathOverride;
10421
10791
  var init_built_in_context = __esm({
10422
10792
  "core/knowledge/built-in-context.ts"() {
10793
+ init_text_encoding();
10423
10794
  exports.BUILT_IN_CONTEXT_FORMAT = "dotmem.built-in-context";
10424
10795
  exports.BUILT_IN_CONTEXT_FORMAT_VERSION = 1;
10425
10796
  cached = null;
@@ -10483,6 +10854,7 @@ var init_knowledge = __esm({
10483
10854
  init_state();
10484
10855
  init_select();
10485
10856
  init_discover();
10857
+ init_currentness();
10486
10858
  init_project();
10487
10859
  init_applicability();
10488
10860
  init_policy();
@@ -10590,7 +10962,6 @@ function _inferConfidence(claim) {
10590
10962
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, LogicEngine, logic, logic_default;
10591
10963
  var init_logic = __esm({
10592
10964
  "core/logic/index.ts"() {
10593
- init_suppress_idb_warning();
10594
10965
  init_knowledge();
10595
10966
  init_mem_repository();
10596
10967
  init_acquisition_boundary();
@@ -10858,18 +11229,6 @@ Do not store secrets unless dotmem explicitly supports secure secret storage.
10858
11229
  }
10859
11230
  });
10860
11231
 
10861
- // index.ts
10862
- init_suppress_idb_warning();
10863
-
10864
- // core/idb.ts
10865
- var idb = {
10866
- db: {},
10867
- table: {},
10868
- data: {},
10869
- _disabled: true,
10870
- _warning: "IndexedDB is not available in this environment. Use dotmem store or session for persistence."
10871
- };
10872
-
10873
11232
  // core/platform.ts
10874
11233
  var runtimeProcess = /* @__PURE__ */ __name(() => {
10875
11234
  try {
@@ -11200,11 +11559,7 @@ var security = {
11200
11559
  createSanitizer
11201
11560
  };
11202
11561
 
11203
- // core/memory/index.ts
11204
- init_suppress_idb_warning();
11205
-
11206
11562
  // core/memory/journal.ts
11207
- init_suppress_idb_warning();
11208
11563
  init_env();
11209
11564
  var g = globalThis;
11210
11565
  function namespace() {
@@ -11411,7 +11766,6 @@ var journal_default = journal;
11411
11766
  init_brain();
11412
11767
 
11413
11768
  // core/memory/knowledge-runtime.ts
11414
- init_suppress_idb_warning();
11415
11769
  init_knowledge();
11416
11770
  init_project_identity();
11417
11771
  init_user_paths();
@@ -11753,12 +12107,12 @@ var policy = {
11753
12107
  };
11754
12108
 
11755
12109
  // core/memory/entries.ts
11756
- init_suppress_idb_warning();
11757
12110
  init_env();
11758
12111
 
11759
12112
  // core/memory/durable-store.ts
11760
12113
  init_storage_coordinator();
11761
12114
  init_store_queue();
12115
+ init_text_encoding();
11762
12116
  var DurableStorageUnavailableError = class extends Error {
11763
12117
  static {
11764
12118
  __name(this, "DurableStorageUnavailableError");
@@ -11813,11 +12167,11 @@ var DurableMemoryStore = class {
11813
12167
  }
11814
12168
  let parsed;
11815
12169
  try {
11816
- parsed = JSON.parse(new TextDecoder().decode(raw));
12170
+ parsed = JSON.parse(decodeText(raw, { source: this.filePath }));
11817
12171
  } catch {
11818
12172
  try {
11819
12173
  const bakRaw = await fs2.readFile(`${this.filePath}.bak`);
11820
- parsed = JSON.parse(new TextDecoder().decode(bakRaw));
12174
+ parsed = JSON.parse(decodeText(bakRaw, { source: `${this.filePath}.bak` }));
11821
12175
  } catch {
11822
12176
  throw new DurableStorageUnavailableError(
11823
12177
  "Durable memory store is corrupt and no backup is available."
@@ -12625,7 +12979,6 @@ var context = {
12625
12979
  };
12626
12980
 
12627
12981
  // core/memory/acquire.ts
12628
- init_suppress_idb_warning();
12629
12982
  init_env();
12630
12983
  init_built_in_context();
12631
12984
  init_project_identity();
@@ -12799,16 +13152,16 @@ var profile = {
12799
13152
 
12800
13153
  // core/knowledge/note-types.ts
12801
13154
  async function sha256HexOfText(text) {
12802
- const encoder3 = new TextEncoder();
12803
- const bytes = encoder3.encode(text);
13155
+ const encoder4 = new TextEncoder();
13156
+ const bytes = encoder4.encode(text);
12804
13157
  const hashArray = await crypto.subtle.digest("SHA-256", bytes);
12805
13158
  return Array.from(new Uint8Array(hashArray)).map((b) => b.toString(16).padStart(2, "0")).join("");
12806
13159
  }
12807
13160
  __name(sha256HexOfText, "sha256HexOfText");
12808
13161
  async function buildNoteKnowledge(title, content, origin, tag) {
12809
13162
  const sha2563 = await sha256HexOfText(content);
12810
- const encoder3 = new TextEncoder();
12811
- const size = encoder3.encode(content).byteLength;
13163
+ const encoder4 = new TextEncoder();
13164
+ const size = encoder4.encode(content).byteLength;
12812
13165
  return {
12813
13166
  title,
12814
13167
  content,
@@ -13967,7 +14320,7 @@ var memory = {
13967
14320
  resetPolicyStoreCache();
13968
14321
  },
13969
14322
  // ----- namespaced surfaces -----
13970
- /** Local operation journal (namespaced). No-op substrate when sqlite/idb unavailable. */
14323
+ /** Local operation journal (namespaced). Persisted on `store`. */
13971
14324
  journal: journal_default,
13972
14325
  /** Configure the optional cloud-sync layer (namespace + provider). Chainable. */
13973
14326
  configure(opts) {
@@ -17801,7 +18154,7 @@ var EPITEMIC_STATUSES2 = [
17801
18154
 
17802
18155
  // app.json
17803
18156
  var app_default = {
17804
- version: "0.1.7"};
18157
+ version: "0.1.8"};
17805
18158
 
17806
18159
  // index.ts
17807
18160
  var dotmem = {
@@ -17872,7 +18225,6 @@ exports.getBuiltInContextDocuments = getBuiltInContextDocuments;
17872
18225
  exports.getBuiltInContextStatus = getBuiltInContextStatus;
17873
18226
  exports.getCapabilities = getCapabilities;
17874
18227
  exports.getPlatform = getPlatform;
17875
- exports.idb = idb;
17876
18228
  exports.inspectMem = inspectMem;
17877
18229
  exports.isBrowser = isBrowser;
17878
18230
  exports.isBuiltInContextAvailable = isBuiltInContextAvailable;