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/mcp.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,56 @@ 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 decodeText(bytes, options = {}) {
124
+ const bom = detectBom(bytes);
125
+ if (bom === "utf-16le" || bom === "utf-16be") {
126
+ throw new UnsupportedEncodingError(
127
+ `UTF-16 encoded content detected in ${options.source ?? "unknown"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`
128
+ );
129
+ }
130
+ let content = bytes;
131
+ if (bom === "utf-8") {
132
+ content = bytes.subarray(3);
133
+ }
134
+ return strictDecoder.decode(content);
135
+ }
136
+ var strictDecoder, UnsupportedEncodingError, BOM_UTF8, BOM_UTF16LE_FIRST, BOM_UTF16LE_SECOND, BOM_UTF16BE_FIRST, BOM_UTF16BE_SECOND;
137
+ var init_text_encoding = __esm({
138
+ "core/knowledge/text-encoding.ts"() {
139
+ new TextEncoder();
140
+ strictDecoder = new TextDecoder("utf-8", { fatal: true });
141
+ UnsupportedEncodingError = class extends Error {
142
+ static {
143
+ __name(this, "UnsupportedEncodingError");
144
+ }
145
+ constructor(message) {
146
+ super(message);
147
+ this.name = "UnsupportedEncodingError";
148
+ }
149
+ };
150
+ BOM_UTF8 = 239;
151
+ BOM_UTF16LE_FIRST = 255;
152
+ BOM_UTF16LE_SECOND = 254;
153
+ BOM_UTF16BE_FIRST = 254;
154
+ BOM_UTF16BE_SECOND = 255;
155
+ __name(detectBom, "detectBom");
156
+ __name(decodeText, "decodeText");
157
+ }
158
+ });
159
+
122
160
  // core/knowledge/storage-settings.ts
123
161
  var DOTMEM_STORAGE_SETTINGS_FILE_NAME, SETTINGS_MODES, projectRoot, findProjectSettingsFile, discoverProjectSettingsFilePath, resolveUserSettingsFilePath, invalidSettings, parseSettings, resolveSettingsEntry, readTextFile, readStorageSettings;
124
162
  var init_storage_settings = __esm({
@@ -250,15 +288,19 @@ function readDotMemStorageLocator() {
250
288
  const locatorFile = resolveLocatorFilePath(anchor);
251
289
  let raw;
252
290
  try {
253
- raw = fs2.readFileSync(locatorFile, "utf8");
291
+ raw = decodeText(fs2.readFileSync(locatorFile), { source: locatorFile });
254
292
  } catch (error) {
293
+ if (error instanceof UnsupportedEncodingError) {
294
+ throw new DotMemStorageLocationError(
295
+ `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.`
296
+ );
297
+ }
255
298
  const code = error?.code;
256
299
  if (code === "ENOENT") return null;
257
300
  throw new DotMemStorageLocationError(
258
301
  `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} cannot be read (${describeAccessFailure(error)}). No alternative location was selected automatically.`
259
302
  );
260
303
  }
261
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
262
304
  let parsed;
263
305
  try {
264
306
  parsed = JSON.parse(raw);
@@ -350,6 +392,7 @@ var DOTMEM_USER_ANCHOR_DIR_NAME, DOTMEM_STORAGE_LOCATOR_FILE_NAME, DOTMEM_STORAG
350
392
  var init_storage_location = __esm({
351
393
  "core/knowledge/storage-location.ts"() {
352
394
  init_storage_paths();
395
+ init_text_encoding();
353
396
  init_storage_settings();
354
397
  init_storage_paths();
355
398
  DOTMEM_USER_ANCHOR_DIR_NAME = ".dotmem";
@@ -1356,6 +1399,12 @@ var init_state = __esm({
1356
1399
  if (claim.sourceProject !== void 0 && !requiredText(claim.sourceProject)) {
1357
1400
  throw new Error(`Claim ${claim.id} has an invalid sourceProject`);
1358
1401
  }
1402
+ if (claim.check !== void 0) {
1403
+ const check = claim.check;
1404
+ 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)) {
1405
+ throw new Error(`Claim ${claim.id} has an invalid check`);
1406
+ }
1407
+ }
1359
1408
  return claim;
1360
1409
  }, "validateClaim");
1361
1410
  validateKnowledgeState = /* @__PURE__ */ __name((value) => {
@@ -1660,6 +1709,50 @@ var init_scope_eligibility = __esm({
1660
1709
  }
1661
1710
  });
1662
1711
 
1712
+ // core/knowledge/currentness.ts
1713
+ var asRecord, verifiedAtOf, findContestedIds, deriveCurrentness;
1714
+ var init_currentness = __esm({
1715
+ "core/knowledge/currentness.ts"() {
1716
+ asRecord = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0, "asRecord");
1717
+ verifiedAtOf = /* @__PURE__ */ __name((claim) => {
1718
+ const value = asRecord(claim.knowledge)?.verifiedAt;
1719
+ if (typeof value !== "string") return void 0;
1720
+ const parsed = Date.parse(value);
1721
+ return Number.isNaN(parsed) ? void 0 : parsed;
1722
+ }, "verifiedAtOf");
1723
+ findContestedIds = /* @__PURE__ */ __name((claims) => {
1724
+ const retracting = /* @__PURE__ */ new Map();
1725
+ for (const claim of claims) {
1726
+ if (claim.revision?.kind === "retracts" && claim.revision.claimIds.length > 0) {
1727
+ retracting.set(claim.id, new Set(claim.revision.claimIds));
1728
+ }
1729
+ }
1730
+ const contested = /* @__PURE__ */ new Set();
1731
+ for (const [id, targets] of retracting) {
1732
+ for (const target of targets) {
1733
+ if (retracting.get(target)?.has(id)) {
1734
+ contested.add(id);
1735
+ contested.add(target);
1736
+ }
1737
+ }
1738
+ }
1739
+ return contested;
1740
+ }, "findContestedIds");
1741
+ deriveCurrentness = /* @__PURE__ */ __name((claim, context2 = {}) => {
1742
+ const now3 = context2.now ?? Date.now();
1743
+ if (context2.contestedIds?.has(claim.id)) return "contested";
1744
+ if (claim.revision?.kind === "retracts") return "historical";
1745
+ if (context2.retractedIds?.has(claim.id)) return "historical";
1746
+ if (context2.supersededIds?.has(claim.id)) return "superseded";
1747
+ if (claim.expiresAt !== void 0 && now3 >= claim.expiresAt) return "expired";
1748
+ const verifiedAt = verifiedAtOf(claim);
1749
+ if (verifiedAt !== void 0) return "verified";
1750
+ if (claim.epistemicType === "verified") return "unverified";
1751
+ return "unknown-currentness";
1752
+ }, "deriveCurrentness");
1753
+ }
1754
+ });
1755
+
1663
1756
  // core/knowledge/discover.ts
1664
1757
  var diagnostic, DEFAULT_LIMITS, FIELD_ORDER, FIELD_WEIGHT, normalize, discoveryTerms, jsonText, fieldText, acquiredTime, isExpired, rankCandidate, discoverAcquiredExperience;
1665
1758
  var init_discover = __esm({
@@ -1667,6 +1760,7 @@ var init_discover = __esm({
1667
1760
  init_state();
1668
1761
  init_applicability();
1669
1762
  init_scope_eligibility();
1763
+ init_currentness();
1670
1764
  init_env();
1671
1765
  diagnostic = /* @__PURE__ */ __name((message) => {
1672
1766
  if (typeof process !== "undefined" && typeof process.stderr?.write === "function") {
@@ -1779,11 +1873,78 @@ var init_discover = __esm({
1779
1873
  throw new Error("Discovery maxCandidates must be a positive integer");
1780
1874
  }
1781
1875
  const queryTerms = discoveryTerms(situation);
1876
+ const offset = options.cursor?.offset ?? 0;
1877
+ if (!Number.isInteger(offset) || offset < 0) {
1878
+ throw new Error("Discovery cursor offset must be a non-negative integer");
1879
+ }
1880
+ if (options.cursor && options.cursor.knowledgeVersion !== validated.version) {
1881
+ return {
1882
+ knowledgeVersion: validated.version,
1883
+ depth,
1884
+ queryTerms,
1885
+ candidates: [],
1886
+ omissions: [],
1887
+ offset: 0,
1888
+ snapshotChanged: true
1889
+ };
1890
+ }
1782
1891
  const available = activeClaims(validated);
1892
+ const availableIds = new Set(available.map((claim) => claim.id));
1893
+ const retractedIds = /* @__PURE__ */ new Set();
1894
+ const supersededIds = /* @__PURE__ */ new Set();
1895
+ const contestedIds = findContestedIds(validated.claims);
1896
+ for (const claim of validated.claims) {
1897
+ if (claim.revision?.kind === "retracts") {
1898
+ for (const id of claim.revision.claimIds) retractedIds.add(id);
1899
+ }
1900
+ if (claim.revision?.kind === "supersedes") {
1901
+ for (const id of claim.revision.claimIds) supersededIds.add(id);
1902
+ }
1903
+ }
1904
+ const revisionOmissions = validated.claims.filter((claim) => !availableIds.has(claim.id)).map((claim) => {
1905
+ const retracted = retractedIds.has(claim.id);
1906
+ const superseded = supersededIds.has(claim.id);
1907
+ return {
1908
+ id: claim.id,
1909
+ reason: retracted ? "retracted" : superseded ? "superseded" : "retracted",
1910
+ gate: "revision-resolution",
1911
+ ...retracted || superseded ? {} : { detail: "the claim itself retracts prior knowledge and is kept as history" }
1912
+ };
1913
+ }).sort((left, right) => left.id.localeCompare(right.id));
1783
1914
  const scopeEligible = options.currentProjectId === void 0 ? available : available.filter((claim) => isScopeEligible(claim, options.currentProjectId, sources.get(claim.id)));
1784
1915
  const freshEligible = scopeEligible.filter((claim) => !isExpired(claim));
1916
+ const scopeEligibleIds = new Set(scopeEligible.map((claim) => claim.id));
1917
+ const scopeOmissions = available.filter((claim) => !scopeEligibleIds.has(claim.id)).map((claim) => {
1918
+ const owner = claimOwnerProject(claim, sources.get(claim.id));
1919
+ return {
1920
+ id: claim.id,
1921
+ reason: "scope",
1922
+ gate: "scope",
1923
+ detail: owner === void 0 ? "owner project could not be resolved" : `owned by project ${owner}`
1924
+ };
1925
+ }).sort((left, right) => left.id.localeCompare(right.id));
1926
+ const freshIds = new Set(freshEligible.map((claim) => claim.id));
1927
+ const freshnessOmissions = scopeEligible.filter((claim) => !freshIds.has(claim.id)).map((claim) => ({
1928
+ id: claim.id,
1929
+ reason: "expired",
1930
+ gate: "freshness",
1931
+ detail: `expired at ${new Date(claim.expiresAt).toISOString()}`
1932
+ })).sort((left, right) => left.id.localeCompare(right.id));
1785
1933
  const situationApplicability = deriveSituationApplicability(situation, options.facts);
1786
- const eligible = freshEligible.map((claim) => ({ claim, match: isEligibleByApplicability(claim, situationApplicability) })).filter((candidate) => candidate.match.eligible);
1934
+ const applicabilityMatches = new Map(
1935
+ freshEligible.map((claim) => [claim.id, isEligibleByApplicability(claim, situationApplicability)])
1936
+ );
1937
+ const eligible = freshEligible.map((claim) => ({ claim, match: applicabilityMatches.get(claim.id) })).filter((candidate) => candidate.match.eligible);
1938
+ const applicabilityOmissions = freshEligible.filter((claim) => !applicabilityMatches.get(claim.id).eligible).map((claim) => {
1939
+ const match = applicabilityMatches.get(claim.id);
1940
+ const mismatched = Object.entries(match.dimensions).filter(([, state3]) => state3 === "MISMATCH").map(([dimension]) => dimension);
1941
+ return {
1942
+ id: claim.id,
1943
+ reason: "applicability-mismatch",
1944
+ gate: "applicability",
1945
+ detail: `mismatching dimensions: ${mismatched.length > 0 ? mismatched.join(", ") : "none recorded"}`
1946
+ };
1947
+ }).sort((left, right) => left.id.localeCompare(right.id));
1787
1948
  if (DEV) {
1788
1949
  diagnostic(
1789
1950
  "[dotmem discovery] ACTIVE=" + JSON.stringify(
@@ -1795,12 +1956,15 @@ var init_discover = __esm({
1795
1956
  )
1796
1957
  );
1797
1958
  }
1959
+ const currentnessOf = /* @__PURE__ */ __name((claim) => deriveCurrentness(claim, { retractedIds, supersededIds, contestedIds }), "currentnessOf");
1798
1960
  if (queryTerms.length === 0) {
1799
- const baseline = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1961
+ const baselineAll = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1800
1962
  const leftTime = acquiredTime(left);
1801
1963
  const rightTime = acquiredTime(right);
1802
1964
  return rightTime - leftTime || Number(right.scope === "project") - Number(left.scope === "project") || left.id.localeCompare(right.id);
1803
- }).slice(0, maxCandidates);
1965
+ });
1966
+ const baseline = baselineAll.slice(offset, offset + maxCandidates);
1967
+ const limitOmissions = baselineAll.slice(offset + maxCandidates).map((claim) => ({ id: claim.id, reason: "limit", gate: "ranking" })).sort((left, right) => left.id.localeCompare(right.id));
1804
1968
  const baselineCandidates = baseline.map((claim) => {
1805
1969
  const explanation = {
1806
1970
  matchedTerms: [],
@@ -1813,7 +1977,8 @@ var init_discover = __esm({
1813
1977
  }
1814
1978
  return {
1815
1979
  claim,
1816
- explanation
1980
+ explanation,
1981
+ currentness: currentnessOf(claim)
1817
1982
  };
1818
1983
  });
1819
1984
  if (DEV) {
@@ -1826,10 +1991,18 @@ var init_discover = __esm({
1826
1991
  depth,
1827
1992
  queryTerms,
1828
1993
  situationApplicability,
1829
- candidates: baselineCandidates
1994
+ candidates: baselineCandidates,
1995
+ offset,
1996
+ omissions: [
1997
+ ...revisionOmissions,
1998
+ ...scopeOmissions,
1999
+ ...freshnessOmissions,
2000
+ ...applicabilityOmissions,
2001
+ ...limitOmissions
2002
+ ]
1830
2003
  };
1831
2004
  }
1832
- const candidates = eligible.map(
2005
+ const ranked = eligible.map(
1833
2006
  (candidate) => rankCandidate(
1834
2007
  candidate.claim,
1835
2008
  situation,
@@ -1841,16 +2014,40 @@ var init_discover = __esm({
1841
2014
  (candidate) => candidate !== null
1842
2015
  ).sort(
1843
2016
  (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)
1844
- ).slice(0, maxCandidates).map(({ claim, explanation }) => ({
2017
+ );
2018
+ const rankedIds = new Set(ranked.map((candidate) => candidate.claim.id));
2019
+ const rankingOmissions = [
2020
+ ...eligible.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2021
+ id: candidate.claim.id,
2022
+ reason: "no-term-match",
2023
+ gate: "ranking",
2024
+ detail: "passed every gate but shares no query term"
2025
+ })),
2026
+ ...ranked.slice(offset + maxCandidates).map((candidate) => ({
2027
+ id: candidate.claim.id,
2028
+ reason: "limit",
2029
+ gate: "ranking"
2030
+ }))
2031
+ ].sort((left, right) => left.id.localeCompare(right.id));
2032
+ const candidates = ranked.slice(offset, offset + maxCandidates).map(({ claim, explanation }) => ({
1845
2033
  claim,
1846
- explanation
2034
+ explanation,
2035
+ currentness: currentnessOf(claim)
1847
2036
  }));
1848
2037
  return {
1849
2038
  knowledgeVersion: validated.version,
1850
2039
  depth,
1851
2040
  queryTerms,
1852
2041
  situationApplicability,
1853
- candidates
2042
+ candidates,
2043
+ offset,
2044
+ omissions: [
2045
+ ...revisionOmissions,
2046
+ ...scopeOmissions,
2047
+ ...freshnessOmissions,
2048
+ ...applicabilityOmissions,
2049
+ ...rankingOmissions
2050
+ ]
1854
2051
  };
1855
2052
  }, "discoverAcquiredExperience");
1856
2053
  }
@@ -2907,7 +3104,7 @@ var init_policy_store = __esm({
2907
3104
  });
2908
3105
 
2909
3106
  // core/knowledge/acquisition-limits.ts
2910
- var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder, serializedBytes, measureKnowledge, checkAcquireLimits;
3107
+ var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder2, serializedBytes, measureKnowledge, checkAcquireLimits;
2911
3108
  var init_acquisition_limits = __esm({
2912
3109
  "core/knowledge/acquisition-limits.ts"() {
2913
3110
  MEMORY_ACQUIRE_LIMITS = Object.freeze({
@@ -2966,10 +3163,10 @@ var init_acquisition_limits = __esm({
2966
3163
  this.name = "MemoryAcquireDuplicateClaimError";
2967
3164
  }
2968
3165
  };
2969
- encoder = new TextEncoder();
3166
+ encoder2 = new TextEncoder();
2970
3167
  serializedBytes = /* @__PURE__ */ __name((value) => {
2971
3168
  const json = JSON.stringify(value);
2972
- return json === void 0 ? 0 : encoder.encode(json).length;
3169
+ return json === void 0 ? 0 : encoder2.encode(json).length;
2973
3170
  }, "serializedBytes");
2974
3171
  measureKnowledge = /* @__PURE__ */ __name((knowledge) => {
2975
3172
  const claimBytes = serializedBytes(knowledge);
@@ -3064,7 +3261,7 @@ var init_context_constants = __esm({
3064
3261
  });
3065
3262
 
3066
3263
  // core/knowledge/project.ts
3067
- var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_MAX_CHARACTERS, projectCandidate, renderHeader, renderExperience, renderText, projectDiscoveredExperience;
3264
+ 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, renderExpandedClaim;
3068
3265
  var init_project = __esm({
3069
3266
  "core/knowledge/project.ts"() {
3070
3267
  init_state();
@@ -3089,9 +3286,29 @@ var init_project = __esm({
3089
3286
  ...claim.provenance ? { provenance: claim.provenance } : {},
3090
3287
  ...claim.acquiredAt ? { acquiredAt: claim.acquiredAt } : {},
3091
3288
  ...claim.revision ? { revision: claim.revision } : {},
3092
- ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {}
3289
+ ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {},
3290
+ ...candidate.currentness ? { currentness: candidate.currentness } : {}
3093
3291
  });
3094
3292
  }, "projectCandidate");
3293
+ GIST_MAX_LENGTH = 80;
3294
+ GIST_KEYS = ["gist", "summary", "statement", "title", "reason", "principle", "finding", "detail"];
3295
+ MANIFEST_ID_LIMIT = 40;
3296
+ deriveGist = /* @__PURE__ */ __name((knowledge) => {
3297
+ if (typeof knowledge === "string") {
3298
+ return knowledge.length > GIST_MAX_LENGTH ? `${knowledge.slice(0, GIST_MAX_LENGTH)}\u2026` : knowledge;
3299
+ }
3300
+ if (knowledge && typeof knowledge === "object" && !Array.isArray(knowledge)) {
3301
+ const obj = knowledge;
3302
+ for (const key of GIST_KEYS) {
3303
+ const value = obj[key];
3304
+ if (typeof value === "string" && value.length > 0) {
3305
+ return value.length > GIST_MAX_LENGTH ? `${value.slice(0, GIST_MAX_LENGTH)}\u2026` : value;
3306
+ }
3307
+ }
3308
+ }
3309
+ const str = JSON.stringify(knowledge);
3310
+ return str.length > GIST_MAX_LENGTH ? `${str.slice(0, GIST_MAX_LENGTH)}\u2026` : str;
3311
+ }, "deriveGist");
3095
3312
  renderHeader = /* @__PURE__ */ __name((knowledgeVersion, totalCandidates) => {
3096
3313
  const lines = [
3097
3314
  `DOTMEM STORAGE: ${resolveUserDotMemPath()}`,
@@ -3117,27 +3334,70 @@ var init_project = __esm({
3117
3334
  evidence.supports ?? null
3118
3335
  ]),
3119
3336
  ...experience.epistemicType ? { epistemic: experience.epistemicType } : {},
3337
+ ...experience.currentness ? { currentness: experience.currentness } : {},
3120
3338
  ...experience.provenance ? { provenance: [experience.provenance.source, experience.provenance.detail ?? null] } : {},
3121
3339
  ...experience.acquiredAt ? { acquiredAt: experience.acquiredAt } : {},
3122
3340
  ...experience.revision ? { revision: experience.revision } : {},
3123
3341
  ...experience.sourceId ? { source: experience.sourceId } : {}
3124
3342
  }), "renderExperience");
3125
- renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates) => `${header}${experiences.length ? `
3126
- ${experiences.map(renderExperience).join("\n")}` : ""}
3127
- OMITTED:${omittedCandidates}`, "renderText");
3343
+ renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, render = renderExperience, currentnessSummary) => {
3344
+ const lines = [header];
3345
+ if (experiences.length > 0) lines.push(...experiences.map(render));
3346
+ lines.push(`OMITTED:${omittedCandidates}`);
3347
+ if (manifest && manifest.byReason.length > 0) {
3348
+ lines.push(`OMITTED_BY_REASON:${manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`);
3349
+ }
3350
+ if (manifest && manifest.items.length > 0) {
3351
+ lines.push(`OMITTED_IDS:${manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`);
3352
+ if (manifest.items.length > MANIFEST_ID_LIMIT) {
3353
+ lines.push(`OMITTED_IDS_TRUNCATED:${manifest.items.length - MANIFEST_ID_LIMIT}`);
3354
+ }
3355
+ }
3356
+ if (currentnessSummary) {
3357
+ lines.push(`CURRENTNESS:${currentnessSummary}`);
3358
+ }
3359
+ return lines.join("\n");
3360
+ }, "renderText");
3361
+ byteLength = /* @__PURE__ */ __name((value) => new TextEncoder().encode(value).length, "byteLength");
3362
+ summarizeOmissions = /* @__PURE__ */ __name((items) => {
3363
+ const counts = /* @__PURE__ */ new Map();
3364
+ for (const item of items) counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
3365
+ return [...counts.entries()].map(([reason, count]) => ({ reason, count })).sort((left, right) => left.reason.localeCompare(right.reason));
3366
+ }, "summarizeOmissions");
3367
+ renderManifestFitting = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, maxCharacters, render, currentnessSummary) => {
3368
+ const full = renderText(header, experiences, omittedCandidates, manifest, render, currentnessSummary);
3369
+ if (byteLength(full) <= maxCharacters) return full;
3370
+ const withoutIds = { ...manifest, items: [] };
3371
+ return renderText(header, experiences, omittedCandidates, withoutIds, render, currentnessSummary);
3372
+ }, "renderManifestFitting");
3373
+ renderCompactExperience = /* @__PURE__ */ __name((experience) => JSON.stringify({
3374
+ id: experience.id,
3375
+ status: "candidate",
3376
+ gist: deriveGist(experience.experience),
3377
+ epistemic: experience.epistemicType ?? null,
3378
+ currentness: experience.currentness ?? null,
3379
+ ...experience.revision ? { revision: experience.revision.kind } : {}
3380
+ }), "renderCompactExperience");
3128
3381
  projectDiscoveredExperience = /* @__PURE__ */ __name((discovery, options = {}) => {
3129
3382
  if (!discovery || !Number.isInteger(discovery.knowledgeVersion) || discovery.knowledgeVersion < 0 || !Array.isArray(discovery.candidates)) {
3130
3383
  throw new Error("Valid DiscoveryResult is required for context projection");
3131
3384
  }
3132
3385
  const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES;
3133
3386
  const maxCharacters = options.maxCharacters ?? DEFAULT_MAX_CHARACTERS;
3387
+ const format = options.format ?? "compact";
3388
+ if (format !== "compact" && format !== "standard" && format !== "full") {
3389
+ throw new Error("Projection format must be compact, standard or full");
3390
+ }
3134
3391
  if (!Number.isInteger(maxCandidates) || maxCandidates < 1) throw new Error("Projection maxCandidates must be a positive integer");
3135
3392
  if (!Number.isInteger(maxCharacters) || maxCharacters < MIN_MAX_CHARACTERS) {
3136
3393
  throw new Error(`Projection maxCharacters must be an integer of at least ${MIN_MAX_CHARACTERS}`);
3137
3394
  }
3138
- const totalCandidates = discovery.candidates.length;
3395
+ const render = /* @__PURE__ */ __name((experience) => format === "compact" ? renderCompactExperience(experience) : renderExperience(experience), "render");
3396
+ const gateOmissions = discovery.omissions ?? [];
3397
+ const totalCandidates = discovery.candidates.length + gateOmissions.length;
3139
3398
  const header = renderHeader(discovery.knowledgeVersion, totalCandidates);
3140
- if (renderText(header, [], totalCandidates).length > maxCharacters) {
3399
+ const emptyManifest = { considered: totalCandidates, included: 0, items: [], byReason: [] };
3400
+ if (byteLength(renderText(header, [], totalCandidates, emptyManifest)) > maxCharacters) {
3141
3401
  throw new Error("Projection maxCharacters is too small for the projection envelope");
3142
3402
  }
3143
3403
  const experiences = [];
@@ -3146,12 +3406,49 @@ OMITTED:${omittedCandidates}`, "renderText");
3146
3406
  const projected = projectCandidate(candidate);
3147
3407
  const possibleExperiences = [...experiences, projected];
3148
3408
  const possibleOmitted = totalCandidates - possibleExperiences.length;
3149
- if (renderText(header, possibleExperiences, possibleOmitted).length <= maxCharacters) {
3409
+ const candidateManifest = {
3410
+ considered: totalCandidates,
3411
+ included: possibleExperiences.length,
3412
+ items: gateOmissions,
3413
+ byReason: summarizeOmissions(gateOmissions)
3414
+ };
3415
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, candidateManifest, render)) <= maxCharacters) {
3416
+ experiences.push(projected);
3417
+ continue;
3418
+ }
3419
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, void 0, render)) <= maxCharacters) {
3150
3420
  experiences.push(projected);
3151
3421
  }
3152
3422
  }
3423
+ const projectedIds = new Set(experiences.map((experience) => experience.id));
3424
+ const budgetOmissions = discovery.candidates.filter((candidate) => !projectedIds.has(candidate.claim.id)).map((candidate) => ({ id: candidate.claim.id, reason: "budget", gate: "projection" }));
3425
+ const items = [...gateOmissions, ...budgetOmissions];
3153
3426
  const omittedCandidates = totalCandidates - experiences.length;
3154
- const text = renderText(header, experiences, omittedCandidates);
3427
+ const manifest = {
3428
+ considered: totalCandidates,
3429
+ included: experiences.length,
3430
+ items,
3431
+ byReason: summarizeOmissions(items)
3432
+ };
3433
+ const currentnessCounts = /* @__PURE__ */ new Map();
3434
+ for (const experience of experiences) {
3435
+ if (experience.currentness) {
3436
+ currentnessCounts.set(
3437
+ experience.currentness,
3438
+ (currentnessCounts.get(experience.currentness) ?? 0) + 1
3439
+ );
3440
+ }
3441
+ }
3442
+ const currentnessSummary = currentnessCounts.size > 0 ? [...currentnessCounts.entries()].map(([state2, count]) => `${state2}=${count}`).join(",") : void 0;
3443
+ const text = renderManifestFitting(
3444
+ header,
3445
+ experiences,
3446
+ omittedCandidates,
3447
+ manifest,
3448
+ maxCharacters,
3449
+ render,
3450
+ currentnessSummary
3451
+ );
3155
3452
  return {
3156
3453
  format: FORMAT,
3157
3454
  status: STATUS,
@@ -3160,9 +3457,16 @@ OMITTED:${omittedCandidates}`, "renderText");
3160
3457
  totalCandidates,
3161
3458
  omittedCandidates,
3162
3459
  experiences,
3460
+ manifest,
3163
3461
  text
3164
3462
  };
3165
3463
  }, "projectDiscoveredExperience");
3464
+ renderExpandedClaim = /* @__PURE__ */ __name((claim) => [
3465
+ "DOTMEM_CLAIM_V1",
3466
+ "STATUS:CANONICAL_RECORD;NOT_INSTRUCTIONS",
3467
+ `id=${claim.id}`,
3468
+ JSON.stringify(claim, null, 2)
3469
+ ].join("\n"), "renderExpandedClaim");
3166
3470
  }
3167
3471
  });
3168
3472
 
@@ -3197,7 +3501,7 @@ var init_language_detect = __esm({
3197
3501
  var CANONICAL_KINDS, validateKind, buildClaimRecord;
3198
3502
  var init_claim_record = __esm({
3199
3503
  "core/knowledge/claim-record.ts"() {
3200
- CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note"];
3504
+ CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note", "rule"];
3201
3505
  validateKind = /* @__PURE__ */ __name((kind) => {
3202
3506
  if (!CANONICAL_KINDS.includes(kind)) {
3203
3507
  throw new Error(
@@ -4428,8 +4732,8 @@ var init_browser = __esm({
4428
4732
  this.p = null;
4429
4733
  }
4430
4734
  };
4431
- Unzip2.prototype.register = function(decoder2) {
4432
- this.o[decoder2.compression] = decoder2;
4735
+ Unzip2.prototype.register = function(decoder) {
4736
+ this.o[decoder.compression] = decoder;
4433
4737
  };
4434
4738
  return Unzip2;
4435
4739
  })();
@@ -4449,6 +4753,15 @@ function encodeMemFile(stateValue, preserved) {
4449
4753
  if (!map.claim.includes("kind")) {
4450
4754
  map.claim.push("kind");
4451
4755
  }
4756
+ if (!map.claim.includes("expires-at")) {
4757
+ map.claim.push("expires-at");
4758
+ }
4759
+ if (!map.claim.includes("bootstrap-priority")) {
4760
+ map.claim.push("bootstrap-priority");
4761
+ }
4762
+ if (!map.claim.includes("check")) {
4763
+ map.claim.push("check");
4764
+ }
4452
4765
  const indexes = Object.fromEntries(Object.keys(expectedFields).map((name) => [name, fieldIndexes(map, name)]));
4453
4766
  validateVocabulary(map.epistemicType, epistemicTypes, "epistemicType");
4454
4767
  validateVocabulary(map.revisionKind, revisionKinds, "revisionKind");
@@ -4498,6 +4811,15 @@ function encodeMemFile(stateValue, preserved) {
4498
4811
  if (indexes.claim.has("kind")) {
4499
4812
  putOptional(record, indexes.claim, "kind", claim.kind ?? void 0, original !== void 0);
4500
4813
  }
4814
+ if (indexes.claim.has("expires-at")) {
4815
+ putOptional(record, indexes.claim, "expires-at", claim.expiresAt, original !== void 0);
4816
+ }
4817
+ if (indexes.claim.has("bootstrap-priority")) {
4818
+ putOptional(record, indexes.claim, "bootstrap-priority", claim.bootstrapPriority, original !== void 0);
4819
+ }
4820
+ if (indexes.claim.has("check")) {
4821
+ putOptional(record, indexes.claim, "check", claim.check, original !== void 0);
4822
+ }
4501
4823
  return original ? record : trimRecord(record);
4502
4824
  }, "encodeClaim");
4503
4825
  const stateRecord = structuredClone(preserved?.data ?? []);
@@ -4566,8 +4888,37 @@ function decodeMemDocument(value) {
4566
4888
  const scope = optionalGet(record, indexes.claim, "scope");
4567
4889
  const sourceProject = optionalGet(record, indexes.claim, "source-project");
4568
4890
  const kindValue = optionalGet(record, indexes.claim, "kind");
4891
+ const expiresAtValue = indexes.claim.has("expires-at") ? optionalGet(record, indexes.claim, "expires-at") : void 0;
4892
+ const bootstrapPriorityValue = indexes.claim.has("bootstrap-priority") ? optionalGet(record, indexes.claim, "bootstrap-priority") : void 0;
4893
+ const checkValue = indexes.claim.has("check") ? optionalGet(record, indexes.claim, "check") : void 0;
4569
4894
  if (epistemicIndex !== void 0 && (!Number.isInteger(epistemicIndex) || epistemicIndex < 0 || epistemicIndex >= epistemic.length)) throw new Error("Invalid .mem epistemic value");
4570
4895
  if (kindIndex !== void 0 && (!Number.isInteger(kindIndex) || kindIndex < 0 || kindIndex >= revisions.length)) throw new Error("Invalid .mem revision value");
4896
+ if (expiresAtValue !== void 0 && (!Number.isInteger(expiresAtValue) || expiresAtValue < 0)) {
4897
+ throw new Error("Invalid .mem expiresAt value");
4898
+ }
4899
+ if (bootstrapPriorityValue !== void 0 && !bootstrapPriorities.includes(bootstrapPriorityValue)) {
4900
+ throw new Error("Invalid .mem bootstrapPriority value");
4901
+ }
4902
+ let check;
4903
+ if (checkValue !== void 0) {
4904
+ if (!checkValue || typeof checkValue !== "object" || Array.isArray(checkValue)) {
4905
+ throw new Error("Invalid .mem check record");
4906
+ }
4907
+ const checkRecord = checkValue;
4908
+ const description = checkRecord.description;
4909
+ if (typeof description !== "undefined" && typeof description !== "string") {
4910
+ throw new Error("Invalid .mem check record");
4911
+ }
4912
+ if (checkRecord.kind !== "regex" || typeof checkRecord.pattern !== "string" || checkRecord.pattern.length === 0 || !checkTargets.includes(checkRecord.on)) {
4913
+ throw new Error("Invalid .mem check record");
4914
+ }
4915
+ check = {
4916
+ kind: "regex",
4917
+ pattern: checkRecord.pattern,
4918
+ on: checkRecord.on,
4919
+ ...typeof description === "string" ? { description } : {}
4920
+ };
4921
+ }
4571
4922
  const understoodEpistemic = typeof epistemicIndex === "number" && epistemicTypes.includes(epistemic[epistemicIndex]) ? epistemic[epistemicIndex] : void 0;
4572
4923
  const understoodRevision = typeof kindIndex === "number" && revisionKinds.includes(revisions[kindIndex]);
4573
4924
  const claim = {
@@ -4592,6 +4943,9 @@ function decodeMemDocument(value) {
4592
4943
  } : {},
4593
4944
  ...scope === void 0 ? {} : { scope },
4594
4945
  ...sourceProject === void 0 ? {} : { sourceProject },
4946
+ ...expiresAtValue === void 0 ? {} : { expiresAt: expiresAtValue },
4947
+ ...bootstrapPriorityValue === void 0 ? {} : { bootstrapPriority: bootstrapPriorityValue },
4948
+ ...check === void 0 ? {} : { check },
4595
4949
  ...claimKinds.includes(kindValue) ? { kind: kindValue } : {}
4596
4950
  };
4597
4951
  return validateClaim(claim);
@@ -4601,7 +4955,7 @@ function decodeMemDocument(value) {
4601
4955
  preserved: { map: structuredClone(map), data: structuredClone(stateRecord) }
4602
4956
  };
4603
4957
  }
4604
- 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;
4958
+ 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;
4605
4959
  var init_mem_codec = __esm({
4606
4960
  "core/knowledge/mem-codec.ts"() {
4607
4961
  init_state();
@@ -4618,7 +4972,9 @@ var init_mem_codec = __esm({
4618
4972
  };
4619
4973
  epistemicTypes = ["observed", "inferred", "human-stated", "verified"];
4620
4974
  revisionKinds = ["refines", "supersedes", "retracts"];
4621
- claimKinds = ["experience", "agent", "relationship", "logic", "note"];
4975
+ claimKinds = ["experience", "agent", "relationship", "logic", "note", "rule"];
4976
+ bootstrapPriorities = ["P1", "P2", "P3", "P4", "P5", "unclassified"];
4977
+ checkTargets = ["staged", "committed", "working-tree"];
4622
4978
  isJsonValue2 = /* @__PURE__ */ __name((value) => {
4623
4979
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
4624
4980
  if (typeof value === "number") return Number.isFinite(value);
@@ -4692,14 +5048,14 @@ async function encodeMemPackage(state2, semantic, preservedPackage) {
4692
5048
  return encodePackage(state2, semantic, preservedPackage);
4693
5049
  }
4694
5050
  async function decodeMemArtifact(input) {
4695
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
5051
+ const bytes = typeof input === "string" ? encoder3.encode(input) : input;
4696
5052
  if (isZip(bytes)) {
4697
5053
  const { parts: _parts, integrity: _integrity, ...artifact } = await decodePackage(bytes);
4698
5054
  return artifact;
4699
5055
  }
4700
5056
  let value;
4701
5057
  try {
4702
- value = JSON.parse(decoder.decode(bytes).replace(/^\uFEFF/, ""));
5058
+ value = JSON.parse(decodeText(bytes));
4703
5059
  } catch (error) {
4704
5060
  throw new MemArtifactError("corrupt", `Unsupported or corrupt MEM artifact: ${error.message}`);
4705
5061
  }
@@ -4712,11 +5068,12 @@ async function decodeMemArtifact(input) {
4712
5068
  throw new MemArtifactError(message.startsWith("Unsupported") ? "unsupported" : "invalid", message);
4713
5069
  }
4714
5070
  }
4715
- var MEM_PACKAGE_FORMAT, MEM_PACKAGE_FORMAT_LEGACY, MEM_PACKAGE_VERSION, MEM_PACKAGE_LIMITS, MEM_PACKAGE_WRITE_MARGIN_BYTES, MEM_PACKAGE_WRITE_LIMITS, MANIFEST_PATH, MAP_PATH, DATA_PATH, INTEGRITY_PATH, requiredParts, encoder2, decoder, MemArtifactError, stableValue, jsonBytes, sha256, parseJson, validEntryPath, concatenate, readZipParts, createManifest, digestTableIdentity, encodePackage, isZip, decodePackage;
5071
+ var MEM_PACKAGE_FORMAT, MEM_PACKAGE_FORMAT_LEGACY, MEM_PACKAGE_VERSION, MEM_PACKAGE_LIMITS, MEM_PACKAGE_WRITE_MARGIN_BYTES, MEM_PACKAGE_WRITE_LIMITS, MANIFEST_PATH, MAP_PATH, DATA_PATH, INTEGRITY_PATH, requiredParts, encoder3, MemArtifactError, stableValue, jsonBytes, sha256, parseJson, validEntryPath, concatenate, readZipParts, createManifest, digestTableIdentity, encodePackage, isZip, decodePackage;
4716
5072
  var init_mem_package = __esm({
4717
5073
  "core/knowledge/mem-package.ts"() {
4718
5074
  init_browser();
4719
5075
  init_mem_codec();
5076
+ init_text_encoding();
4720
5077
  MEM_PACKAGE_FORMAT = "dotmem.package";
4721
5078
  MEM_PACKAGE_FORMAT_LEGACY = "memorio.package";
4722
5079
  MEM_PACKAGE_VERSION = 1;
@@ -4740,8 +5097,7 @@ var init_mem_package = __esm({
4740
5097
  DATA_PATH = "memory/data.json";
4741
5098
  INTEGRITY_PATH = "security/integrity.json";
4742
5099
  requiredParts = [MANIFEST_PATH, MAP_PATH, DATA_PATH];
4743
- encoder2 = new TextEncoder();
4744
- decoder = new TextDecoder("utf-8", { fatal: true });
5100
+ encoder3 = new TextEncoder();
4745
5101
  MemArtifactError = class extends Error {
4746
5102
  constructor(code, message) {
4747
5103
  super(message);
@@ -4760,7 +5116,7 @@ var init_mem_package = __esm({
4760
5116
  }
4761
5117
  return value;
4762
5118
  }, "stableValue");
4763
- jsonBytes = /* @__PURE__ */ __name((value) => encoder2.encode(`${JSON.stringify(stableValue(value), null, 2)}
5119
+ jsonBytes = /* @__PURE__ */ __name((value) => encoder3.encode(`${JSON.stringify(stableValue(value), null, 2)}
4764
5120
  `), "jsonBytes");
4765
5121
  sha256 = /* @__PURE__ */ __name(async (data) => {
4766
5122
  if (!globalThis.crypto?.subtle) throw new MemArtifactError("unsupported", "SHA-256 is unavailable in this runtime");
@@ -4769,7 +5125,7 @@ var init_mem_package = __esm({
4769
5125
  }, "sha256");
4770
5126
  parseJson = /* @__PURE__ */ __name((bytes, path2) => {
4771
5127
  try {
4772
- return JSON.parse(decoder.decode(bytes));
5128
+ return JSON.parse(decodeText(bytes));
4773
5129
  } catch (error) {
4774
5130
  throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path2}: ${error.message}`);
4775
5131
  }
@@ -4939,10 +5295,12 @@ var init_mem_package = __esm({
4939
5295
  });
4940
5296
 
4941
5297
  // core/storage-coordinator/index.ts
4942
- var nodeFs4, withStorageLock, readStorageGeneration, writeStorageGeneration;
5298
+ var nodeFs4, heldLocks, withStorageLock, readStorageGeneration, writeStorageGeneration;
4943
5299
  var init_storage_coordinator = __esm({
4944
5300
  "core/storage-coordinator/index.ts"() {
5301
+ init_text_encoding();
4945
5302
  nodeFs4 = /* @__PURE__ */ __name(async () => import('fs/promises'), "nodeFs");
5303
+ heldLocks = /* @__PURE__ */ new Map();
4946
5304
  withStorageLock = /* @__PURE__ */ __name(async (directoryPath, operationOrOptions, operation, _options = {}) => {
4947
5305
  const opts = typeof operationOrOptions === "function" ? operation ?? {} : operationOrOptions ?? {};
4948
5306
  const op = typeof operationOrOptions === "function" ? operationOrOptions : operation;
@@ -4952,6 +5310,15 @@ var init_storage_coordinator = __esm({
4952
5310
  const lockPath = `${directoryPath}/${lockName}`;
4953
5311
  const fs2 = await nodeFs4();
4954
5312
  const started = Date.now();
5313
+ const heldDepth = heldLocks.get(lockPath) ?? 0;
5314
+ if (heldDepth > 0) {
5315
+ heldLocks.set(lockPath, heldDepth + 1);
5316
+ try {
5317
+ return await op();
5318
+ } finally {
5319
+ heldLocks.set(lockPath, heldDepth);
5320
+ }
5321
+ }
4955
5322
  await fs2.mkdir(directoryPath, { recursive: true });
4956
5323
  while (true) {
4957
5324
  try {
@@ -4965,8 +5332,8 @@ var init_storage_coordinator = __esm({
4965
5332
  let stale = false;
4966
5333
  let processDead = false;
4967
5334
  try {
4968
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
4969
- const parsed = JSON.parse(raw);
5335
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5336
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
4970
5337
  const ageStale = typeof parsed.createdAt === "number" && Date.now() - parsed.createdAt > staleMs;
4971
5338
  if (typeof parsed.pid === "number") {
4972
5339
  try {
@@ -5003,17 +5370,19 @@ var init_storage_coordinator = __esm({
5003
5370
  }
5004
5371
  let token = "";
5005
5372
  try {
5006
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5007
- token = JSON.parse(raw).token ?? "";
5373
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5374
+ token = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` })).token ?? "";
5008
5375
  } catch {
5009
5376
  token = "";
5010
5377
  }
5011
5378
  try {
5379
+ heldLocks.set(lockPath, 1);
5012
5380
  return await op();
5013
5381
  } finally {
5382
+ heldLocks.delete(lockPath);
5014
5383
  try {
5015
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5016
- const parsed = JSON.parse(raw);
5384
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5385
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
5017
5386
  if (parsed.token === token && token) {
5018
5387
  await fs2.rm(lockPath, { recursive: true, force: true });
5019
5388
  }
@@ -5024,8 +5393,8 @@ var init_storage_coordinator = __esm({
5024
5393
  readStorageGeneration = /* @__PURE__ */ __name(async (directoryPath) => {
5025
5394
  const fs2 = await nodeFs4();
5026
5395
  try {
5027
- const raw = await fs2.readFile(`${directoryPath}/.storage.generation`, "utf8");
5028
- const value = Number(raw.trim());
5396
+ const raw = await fs2.readFile(`${directoryPath}/.storage.generation`);
5397
+ const value = Number(decodeText(raw, { source: `${directoryPath}/.storage.generation` }).trim());
5029
5398
  return Number.isFinite(value) && value >= 0 ? value : 0;
5030
5399
  } catch {
5031
5400
  return 0;
@@ -5513,12 +5882,11 @@ function readJsonFile(path2) {
5513
5882
  if (!fs2) return null;
5514
5883
  let raw;
5515
5884
  try {
5516
- raw = fs2.readFileSync(path2, "utf8");
5885
+ raw = decodeText(fs2.readFileSync(path2), { source: path2 });
5517
5886
  } catch {
5518
5887
  return null;
5519
5888
  }
5520
5889
  if (typeof raw !== "string") return null;
5521
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
5522
5890
  try {
5523
5891
  return JSON.parse(raw);
5524
5892
  } catch {
@@ -5642,6 +6010,7 @@ var init_user_language = __esm({
5642
6010
  "core/knowledge/user-language.ts"() {
5643
6011
  init_user_paths();
5644
6012
  init_storage_paths();
6013
+ init_text_encoding();
5645
6014
  USER_LANGUAGE_FILE_NAME = "language.json";
5646
6015
  USER_LANGUAGE_PREFERENCE_FILE_NAME = "user-language.json";
5647
6016
  LANGUAGE_PREFERENCE_FILE_NAME = "language-preference.json";
@@ -9365,10 +9734,13 @@ var init_staging = __esm({
9365
9734
  epistemicType: sanitizedClaim.epistemicType,
9366
9735
  provenance: sanitizedClaim.provenance,
9367
9736
  acquiredAt: sanitizedClaim.acquiredAt,
9737
+ ...sanitizedClaim.expiresAt === void 0 ? {} : { expiresAt: sanitizedClaim.expiresAt },
9738
+ ...sanitizedClaim.bootstrapPriority === void 0 ? {} : { bootstrapPriority: sanitizedClaim.bootstrapPriority },
9368
9739
  revision,
9369
9740
  scope,
9370
9741
  sourceProject,
9371
- kind
9742
+ kind,
9743
+ ...sanitizedClaim.check === void 0 ? {} : { check: sanitizedClaim.check }
9372
9744
  });
9373
9745
  await withStoreQueue(acquisitionStoreKey(kind, scope, sourceProject), async () => {
9374
9746
  const state2 = await target.runtime.select([]);
@@ -9616,7 +9988,14 @@ var init_incidents = __esm({
9616
9988
  }
9617
9989
  });
9618
9990
 
9619
- // core/knowledge/rules-loader.ts
9991
+ // core/knowledge/violations.ts
9992
+ var VIOLATION_FILE_NAME;
9993
+ var init_violations = __esm({
9994
+ "core/knowledge/violations.ts"() {
9995
+ init_user_paths();
9996
+ VIOLATION_FILE_NAME = "violations.json";
9997
+ }
9998
+ });
9620
9999
  function isRuleClaim(claim) {
9621
10000
  const knowledge = claim.knowledge;
9622
10001
  return knowledge?.kind === "rule";
@@ -9624,7 +10003,7 @@ function isRuleClaim(claim) {
9624
10003
  function isIronRule(claim) {
9625
10004
  return claim.epistemicType === "human-stated" && isRuleClaim(claim);
9626
10005
  }
9627
- function extractIronRules(state2) {
10006
+ function extractIronRules(state2, violations = {}) {
9628
10007
  const validated = validateKnowledgeState(state2);
9629
10008
  const claims = activeClaims(validated);
9630
10009
  const rules = [];
@@ -9641,7 +10020,7 @@ function extractIronRules(state2) {
9641
10020
  appliesWhen: String(knowledge.appliesWhen ?? knowledge.when ?? ""),
9642
10021
  violatedOn: Array.isArray(knowledge.violatedOn) ? knowledge.violatedOn : void 0,
9643
10022
  lastViolation: typeof knowledge.lastViolation === "string" ? knowledge.lastViolation : void 0,
9644
- frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : 0
10023
+ frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : violations[claim.id] ?? 0
9645
10024
  });
9646
10025
  }
9647
10026
  return rules;
@@ -9656,28 +10035,69 @@ function sortRulesByViolationFrequency(rules) {
9656
10035
  });
9657
10036
  }
9658
10037
  function loadIronRules(state2) {
9659
- const rules = sortRulesByViolationFrequency(extractIronRules(state2));
10038
+ const rules = sortRulesByViolationFrequency(
10039
+ extractIronRules(state2, readViolationCounts(`${resolveUserDotMemPath()}/${VIOLATION_FILE_NAME}`))
10040
+ );
9660
10041
  return {
9661
10042
  rules,
9662
10043
  count: rules.length,
9663
10044
  sortedBy: "violation-frequency"
9664
10045
  };
9665
10046
  }
10047
+ function formatRulesForSessionStart(rules) {
10048
+ if (rules.length === 0) {
10049
+ return "";
10050
+ }
10051
+ const lines = ["---", "IRON RULES (must always arrive)", "---"];
10052
+ for (const rule of rules) {
10053
+ lines.push(`${rule.id}: ${rule.text}`);
10054
+ }
10055
+ return lines.join("\n");
10056
+ }
10057
+ var readViolationCounts, ruleSetSignature, formatRulesReference;
9666
10058
  var init_rules_loader = __esm({
9667
10059
  "core/knowledge/rules-loader.ts"() {
9668
10060
  init_state();
10061
+ init_user_paths();
10062
+ init_violations();
9669
10063
  __name(isRuleClaim, "isRuleClaim");
9670
10064
  __name(isIronRule, "isIronRule");
9671
10065
  __name(extractIronRules, "extractIronRules");
10066
+ readViolationCounts = /* @__PURE__ */ __name((file) => {
10067
+ try {
10068
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
10069
+ const counts = {};
10070
+ for (const violation of Array.isArray(parsed.violations) ? parsed.violations : []) {
10071
+ const ruleId = typeof violation?.ruleId === "string" ? violation.ruleId : "";
10072
+ if (!ruleId) continue;
10073
+ counts[ruleId] = (counts[ruleId] ?? 0) + 1;
10074
+ }
10075
+ return counts;
10076
+ } catch {
10077
+ return {};
10078
+ }
10079
+ }, "readViolationCounts");
9672
10080
  __name(sortRulesByViolationFrequency, "sortRulesByViolationFrequency");
9673
10081
  __name(loadIronRules, "loadIronRules");
9674
- }
9675
- });
9676
-
9677
- // core/knowledge/violations.ts
9678
- var init_violations = __esm({
9679
- "core/knowledge/violations.ts"() {
9680
- init_user_paths();
10082
+ ruleSetSignature = /* @__PURE__ */ __name((rules) => {
10083
+ const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
10084
+ let hash = 2166136261;
10085
+ for (let index = 0; index < material.length; index += 1) {
10086
+ hash ^= material.charCodeAt(index);
10087
+ hash = Math.imul(hash, 16777619) >>> 0;
10088
+ }
10089
+ return hash.toString(16).padStart(8, "0");
10090
+ }, "ruleSetSignature");
10091
+ formatRulesReference = /* @__PURE__ */ __name((rules) => {
10092
+ if (rules.length === 0) return "DOTMEM_IRON_RULES_V1\ncount=0";
10093
+ return [
10094
+ "DOTMEM_IRON_RULES_V1",
10095
+ `count=${rules.length}`,
10096
+ `signature=${ruleSetSignature(rules)}`,
10097
+ `ids=${rules.map((rule) => rule.id).join(",")}`
10098
+ ].join("\n");
10099
+ }, "formatRulesReference");
10100
+ __name(formatRulesForSessionStart, "formatRulesForSessionStart");
9681
10101
  }
9682
10102
  });
9683
10103
 
@@ -10186,8 +10606,8 @@ function loadBuiltInContext() {
10186
10606
  for (const candidate of candidates) {
10187
10607
  if (!fs__default.default.existsSync(candidate)) continue;
10188
10608
  try {
10189
- const raw = fs__default.default.readFileSync(candidate, "utf8");
10190
- const parsed = JSON.parse(raw);
10609
+ const raw = fs__default.default.readFileSync(candidate);
10610
+ const parsed = JSON.parse(decodeText(raw, { source: candidate }));
10191
10611
  const artifact = validateArtifact(parsed);
10192
10612
  cached = artifact;
10193
10613
  cachedStatus = {
@@ -10244,6 +10664,7 @@ function assertBuiltInContextAvailable() {
10244
10664
  var BUILT_IN_CONTEXT_FORMAT, BUILT_IN_CONTEXT_FORMAT_VERSION, cached, cachedStatus, _artifactPathOverride;
10245
10665
  var init_built_in_context = __esm({
10246
10666
  "core/knowledge/built-in-context.ts"() {
10667
+ init_text_encoding();
10247
10668
  BUILT_IN_CONTEXT_FORMAT = "dotmem.built-in-context";
10248
10669
  BUILT_IN_CONTEXT_FORMAT_VERSION = 1;
10249
10670
  cached = null;
@@ -10303,6 +10724,7 @@ var init_knowledge = __esm({
10303
10724
  init_state();
10304
10725
  init_select();
10305
10726
  init_discover();
10727
+ init_currentness();
10306
10728
  init_project();
10307
10729
  init_applicability();
10308
10730
  init_policy();
@@ -10410,7 +10832,6 @@ function _inferConfidence(claim) {
10410
10832
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, LogicEngine, logic, logic_default;
10411
10833
  var init_logic = __esm({
10412
10834
  "core/logic/index.ts"() {
10413
- init_suppress_idb_warning();
10414
10835
  init_knowledge();
10415
10836
  init_mem_repository();
10416
10837
  init_acquisition_boundary();
@@ -10689,15 +11110,15 @@ __export(note_types_exports, {
10689
11110
  sha256HexOfText: () => sha256HexOfText
10690
11111
  });
10691
11112
  async function sha256HexOfText(text) {
10692
- const encoder3 = new TextEncoder();
10693
- const bytes = encoder3.encode(text);
11113
+ const encoder4 = new TextEncoder();
11114
+ const bytes = encoder4.encode(text);
10694
11115
  const hashArray = await crypto.subtle.digest("SHA-256", bytes);
10695
11116
  return Array.from(new Uint8Array(hashArray)).map((b) => b.toString(16).padStart(2, "0")).join("");
10696
11117
  }
10697
11118
  async function buildNoteKnowledge(title, content, origin, tag) {
10698
11119
  const sha2563 = await sha256HexOfText(content);
10699
- const encoder3 = new TextEncoder();
10700
- const size = encoder3.encode(content).byteLength;
11120
+ const encoder4 = new TextEncoder();
11121
+ const size = encoder4.encode(content).byteLength;
10701
11122
  return {
10702
11123
  title,
10703
11124
  content,
@@ -10774,18 +11195,11 @@ var init_note_types = __esm({
10774
11195
  }
10775
11196
  });
10776
11197
 
10777
- // core/mcp/index.ts
10778
- init_suppress_idb_warning();
10779
-
10780
11198
  // package.json
10781
11199
  var package_default = {
10782
- version: "0.1.7"};
10783
-
10784
- // core/memory/index.ts
10785
- init_suppress_idb_warning();
11200
+ version: "0.1.8"};
10786
11201
 
10787
11202
  // core/memory/journal.ts
10788
- init_suppress_idb_warning();
10789
11203
  init_env();
10790
11204
  var g = globalThis;
10791
11205
  function namespace() {
@@ -10992,7 +11406,6 @@ var journal_default = journal;
10992
11406
  init_brain();
10993
11407
 
10994
11408
  // core/memory/knowledge-runtime.ts
10995
- init_suppress_idb_warning();
10996
11409
  init_knowledge();
10997
11410
  init_project_identity();
10998
11411
  init_user_paths();
@@ -11383,12 +11796,12 @@ var policy = {
11383
11796
  };
11384
11797
 
11385
11798
  // core/memory/entries.ts
11386
- init_suppress_idb_warning();
11387
11799
  init_env();
11388
11800
 
11389
11801
  // core/memory/durable-store.ts
11390
11802
  init_storage_coordinator();
11391
11803
  init_store_queue();
11804
+ init_text_encoding();
11392
11805
  var DurableStorageUnavailableError = class extends Error {
11393
11806
  static {
11394
11807
  __name(this, "DurableStorageUnavailableError");
@@ -11443,11 +11856,11 @@ var DurableMemoryStore = class {
11443
11856
  }
11444
11857
  let parsed;
11445
11858
  try {
11446
- parsed = JSON.parse(new TextDecoder().decode(raw));
11859
+ parsed = JSON.parse(decodeText(raw, { source: this.filePath }));
11447
11860
  } catch {
11448
11861
  try {
11449
11862
  const bakRaw = await fs2.readFile(`${this.filePath}.bak`);
11450
- parsed = JSON.parse(new TextDecoder().decode(bakRaw));
11863
+ parsed = JSON.parse(decodeText(bakRaw, { source: `${this.filePath}.bak` }));
11451
11864
  } catch {
11452
11865
  throw new DurableStorageUnavailableError(
11453
11866
  "Durable memory store is corrupt and no backup is available."
@@ -12255,7 +12668,6 @@ var context = {
12255
12668
  };
12256
12669
 
12257
12670
  // core/memory/acquire.ts
12258
- init_suppress_idb_warning();
12259
12671
  init_env();
12260
12672
  init_built_in_context();
12261
12673
  init_project_identity();
@@ -13529,7 +13941,7 @@ var memory = {
13529
13941
  resetPolicyStoreCache();
13530
13942
  },
13531
13943
  // ----- namespaced surfaces -----
13532
- /** Local operation journal (namespaced). No-op substrate when sqlite/idb unavailable. */
13944
+ /** Local operation journal (namespaced). Persisted on `store`. */
13533
13945
  journal: journal_default,
13534
13946
  /** Configure the optional cloud-sync layer (namespace + provider). Chainable. */
13535
13947
  configure(opts) {
@@ -13665,6 +14077,7 @@ init_profile();
13665
14077
  init_acquisition_limits();
13666
14078
  init_mem_package();
13667
14079
  init_built_in_context();
14080
+ init_project();
13668
14081
  init_policy();
13669
14082
  init_context_constants();
13670
14083
 
@@ -15737,12 +16150,23 @@ var toolError = /* @__PURE__ */ __name((error) => {
15737
16150
  const code = stableErrorCode(error);
15738
16151
  return code ? codedErrorResult(code, isRetryable(error)) : errorResult2(sanitizeMcpError(error));
15739
16152
  }, "toolError");
15740
- async function dotmemContext(situation, dotmem = memory) {
16153
+ async function dotmemContext(situation, dotmem = memory, options = {}) {
16154
+ if (options.claimId) {
16155
+ const state2 = await loadCombinedKnowledgeState();
16156
+ const claim = state2.claims.find((candidate) => candidate.id === options.claimId);
16157
+ if (!claim) {
16158
+ return errorResult2(`No claim with id ${options.claimId} is present in the loaded stores.`);
16159
+ }
16160
+ const text = renderExpandedClaim(claim);
16161
+ return { content: [{ type: "text", text }], structuredContent: { text, claim } };
16162
+ }
15741
16163
  if (typeof situation !== "string") {
15742
16164
  return errorResult2("dotmem context requires a string situation.");
15743
16165
  }
15744
16166
  try {
15745
- const discovery = await dotmem.discover(situation);
16167
+ const discovery = await dotmem.discover(situation, {
16168
+ ...options.cursor ? { cursor: options.cursor } : {}
16169
+ });
15746
16170
  const projection = dotmem.project(
15747
16171
  discovery,
15748
16172
  {
@@ -15915,13 +16339,13 @@ async function dotmemNoteWrite(input) {
15915
16339
  }
15916
16340
  }
15917
16341
  __name(dotmemNoteWrite, "dotmemNoteWrite");
15918
- async function dotmemRules(loadRules) {
16342
+ async function dotmemRules(loadRules, options = {}) {
15919
16343
  try {
15920
16344
  const rules = await loadRules();
15921
- const text = rules.length === 0 ? "No iron rules found." : rules.map((rule) => `[${rule.id}] ${rule.text}`).join("\n");
16345
+ const text = options.expand ? rules.length === 0 ? "No iron rules found." : formatRulesForSessionStart(rules) : formatRulesReference(rules);
15922
16346
  return {
15923
16347
  content: [{ type: "text", text }],
15924
- structuredContent: { count: rules.length, rules }
16348
+ structuredContent: { count: rules.length, signature: ruleSetSignature(rules), rules }
15925
16349
  };
15926
16350
  } catch (error) {
15927
16351
  return toolError(error);
@@ -15957,7 +16381,7 @@ var buildMcpInstructions = /* @__PURE__ */ __name((options) => {
15957
16381
  const signal = buildInstructions(options);
15958
16382
  return [profileGuidance, signal].join("\n\n");
15959
16383
  }, "buildMcpInstructions");
15960
- function createDotMemMcpServer(dotmem = memory, loadRules = defaultLoadRules, hasExperience = false, language2) {
16384
+ function createDotMemMcpServer(dotmem = memory, loadRules = defaultLoadRules, hasExperience = false, language2, orchestrationCoordinator) {
15961
16385
  assertBuiltInContextAvailable();
15962
16386
  const writeEnabled = mcpWriteEnabled();
15963
16387
  const server$1 = new server.McpServer(
@@ -15977,10 +16401,15 @@ function createDotMemMcpServer(dotmem = memory, loadRules = defaultLoadRules, ha
15977
16401
  situation: zod.z.string().trim().max(
15978
16402
  DOTMEM_CONTEXT_MAX_SITUATION_LENGTH,
15979
16403
  "situation exceeds maximum length"
15980
- ).optional()
16404
+ ).optional(),
16405
+ claimId: zod.z.string().trim().min(1).optional(),
16406
+ cursor: zod.z.object({
16407
+ offset: zod.z.number().int().nonnegative(),
16408
+ knowledgeVersion: zod.z.number().int().nonnegative()
16409
+ }).optional()
15981
16410
  })
15982
16411
  },
15983
- ({ situation }) => dotmemContext(situation ?? "", dotmem)
16412
+ ({ situation, claimId, cursor }) => dotmemContext(situation ?? "", dotmem, { claimId, ...cursor ? { cursor } : {} })
15984
16413
  );
15985
16414
  if (mcpWriteEnabled()) {
15986
16415
  server$1.registerTool(
@@ -15996,9 +16425,9 @@ function createDotMemMcpServer(dotmem = memory, loadRules = defaultLoadRules, ha
15996
16425
  DOTMEM_RULES_TOOL_NAME,
15997
16426
  {
15998
16427
  description: DOTMEM_RULES_TOOL_DESCRIPTION,
15999
- inputSchema: zod.z.object({})
16428
+ inputSchema: zod.z.object({ expand: zod.z.boolean().optional() })
16000
16429
  },
16001
- () => dotmemRules(loadRules)
16430
+ ({ expand }) => dotmemRules(loadRules, { expand })
16002
16431
  );
16003
16432
  server$1.registerTool(
16004
16433
  DOTMEM_NOTE_READ_TOOL_NAME,
@@ -16074,6 +16503,179 @@ function createDotMemMcpServer(dotmem = memory, loadRules = defaultLoadRules, ha
16074
16503
  return dotmemContinuity(input, { orchestrator });
16075
16504
  }
16076
16505
  );
16506
+ if (orchestrationCoordinator) {
16507
+ server$1.registerTool(
16508
+ "dotmem_orchestrate_discover",
16509
+ {
16510
+ description: "Discover agents from all configured provider adapters and return their capabilities and eligibility.",
16511
+ inputSchema: {
16512
+ runId: zod.z.string().trim().min(1).optional()
16513
+ }
16514
+ },
16515
+ async (args) => {
16516
+ const runId = args.runId;
16517
+ const id = runId || `orchestrate-${Date.now()}`;
16518
+ try {
16519
+ const result = await orchestrationCoordinator.discoverAndSnapshot(id, "User-requested discovery");
16520
+ return {
16521
+ content: [{ type: "text", text: JSON.stringify({
16522
+ ok: true,
16523
+ runId: id,
16524
+ agentsDiscovered: result.run.discoverySnapshot.length,
16525
+ agentsEligible: result.eligibleAgents.length,
16526
+ agents: result.eligibleAgents.map((a) => ({
16527
+ compositeId: a.compositeId,
16528
+ providerId: a.providerId,
16529
+ agentId: a.agentId,
16530
+ displayName: a.displayName,
16531
+ capabilities: a.capabilities,
16532
+ authorizationStatus: a.authorizationStatus
16533
+ })),
16534
+ exceptions: result.exceptions.map((e) => ({ category: e.category, reason: e.reason, agentCompositeId: e.agentCompositeId }))
16535
+ }) }]
16536
+ };
16537
+ } catch (err2) {
16538
+ return errorResult2(`Discovery failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
16539
+ }
16540
+ }
16541
+ );
16542
+ server$1.registerTool(
16543
+ "dotmem_orchestrate_inspect",
16544
+ {
16545
+ description: "Inspect an orchestration run: its task graph, assignments, states, and exceptions.",
16546
+ inputSchema: {
16547
+ runId: zod.z.string().trim().min(1)
16548
+ }
16549
+ },
16550
+ async (args) => {
16551
+ const runId = args.runId;
16552
+ try {
16553
+ const run = await orchestrationCoordinator.getRunStatus(runId);
16554
+ if (!run) return errorResult2(`Run not found: ${runId}`);
16555
+ const tasks = await orchestrationCoordinator.listTasksForRun(runId);
16556
+ const assignments = await orchestrationCoordinator.listAssignmentsForRun(runId);
16557
+ return {
16558
+ content: [{ type: "text", text: JSON.stringify({
16559
+ ok: true,
16560
+ runId,
16561
+ status: run.status,
16562
+ userObjective: run.userObjective,
16563
+ createdAt: run.createdAt,
16564
+ updatedAt: run.updatedAt,
16565
+ tasks: tasks.map((t) => ({
16566
+ taskId: t.taskId,
16567
+ objective: t.objective,
16568
+ state: t.state,
16569
+ assignedAgent: t.assignedAgentCompositeId,
16570
+ accepted: t.accepted
16571
+ })),
16572
+ assignments: assignments.map((a) => ({
16573
+ assignmentId: a.assignmentId,
16574
+ taskId: a.taskId,
16575
+ agentCompositeId: a.agentCompositeId,
16576
+ state: a.state,
16577
+ accepted: a.accepted
16578
+ })),
16579
+ exceptions: run.exceptions.map((e) => ({
16580
+ exceptionId: e.exceptionId,
16581
+ category: e.category,
16582
+ agentCompositeId: e.agentCompositeId,
16583
+ reason: e.reason,
16584
+ resolved: e.resolved
16585
+ }))
16586
+ }) }]
16587
+ };
16588
+ } catch (err2) {
16589
+ return errorResult2(`Inspect failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
16590
+ }
16591
+ }
16592
+ );
16593
+ server$1.registerTool(
16594
+ "dotmem_orchestrate_report",
16595
+ {
16596
+ description: "Retrieve the final orchestration run report with participation, outcomes, and risks.",
16597
+ inputSchema: {
16598
+ runId: zod.z.string().trim().min(1),
16599
+ userApprovalGranted: zod.z.boolean().optional()
16600
+ }
16601
+ },
16602
+ async (args) => {
16603
+ const runId = args.runId;
16604
+ const userApprovalGranted = args.userApprovalGranted;
16605
+ try {
16606
+ const run = await orchestrationCoordinator.getRunStatus(runId);
16607
+ if (!run) return errorResult2(`Run not found: ${runId}`);
16608
+ const { report } = await orchestrationCoordinator.finalizeRun(runId, !!userApprovalGranted);
16609
+ return {
16610
+ content: [{ type: "text", text: JSON.stringify({ ok: true, report }) }]
16611
+ };
16612
+ } catch (err2) {
16613
+ return errorResult2(`Report failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
16614
+ }
16615
+ }
16616
+ );
16617
+ server$1.registerTool(
16618
+ "dotmem_orchestrate_start",
16619
+ {
16620
+ description: "Start a new orchestration run from a user objective. Discovers agents, decomposes the objective, and creates distinct assignments.",
16621
+ inputSchema: {
16622
+ objective: zod.z.string().trim().min(1, "objective is required"),
16623
+ scope: zod.z.string().trim().optional(),
16624
+ constraints: zod.z.record(zod.z.string(), zod.z.any()).optional(),
16625
+ correlationKey: zod.z.string().trim().optional()
16626
+ }
16627
+ },
16628
+ async (args) => {
16629
+ const objective = args.objective;
16630
+ const scope = args.scope;
16631
+ args.constraints;
16632
+ const correlationKey = args.correlationKey;
16633
+ const runId = correlationKey || `orchestrate-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
16634
+ try {
16635
+ const discoverResult = await orchestrationCoordinator.discoverAndSnapshot(
16636
+ runId,
16637
+ objective,
16638
+ scope
16639
+ );
16640
+ const decomposeResult = await orchestrationCoordinator.decomposeAndAssign(
16641
+ runId,
16642
+ objective,
16643
+ scope,
16644
+ discoverResult.eligibleAgents
16645
+ );
16646
+ return {
16647
+ content: [{ type: "text", text: JSON.stringify({
16648
+ ok: true,
16649
+ runId,
16650
+ status: "assigned",
16651
+ agentsDiscovered: discoverResult.run.discoverySnapshot.length,
16652
+ agentsEligible: discoverResult.eligibleAgents.length,
16653
+ assignments: decomposeResult.assignments.map((a) => ({
16654
+ taskId: a.task.taskId,
16655
+ agentCompositeId: a.agent.compositeId,
16656
+ providerId: a.agent.providerId,
16657
+ agentId: a.agent.agentId,
16658
+ displayName: a.agent.displayName,
16659
+ taskObjective: a.task.objective,
16660
+ acceptanceCriteria: a.task.acceptanceCriteria.map((c) => c.description),
16661
+ state: a.task.state
16662
+ })),
16663
+ exceptions: [...discoverResult.exceptions, ...decomposeResult.exceptions].map((e) => ({
16664
+ exceptionId: e.exceptionId,
16665
+ category: e.category,
16666
+ reason: e.reason,
16667
+ agentCompositeId: e.agentCompositeId,
16668
+ providerId: e.providerId,
16669
+ taskId: e.taskId
16670
+ }))
16671
+ }) }]
16672
+ };
16673
+ } catch (err2) {
16674
+ return errorResult2(`Start failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
16675
+ }
16676
+ }
16677
+ );
16678
+ }
16077
16679
  return server$1;
16078
16680
  }
16079
16681
  __name(createDotMemMcpServer, "createDotMemMcpServer");