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.js CHANGED
@@ -1,4 +1,4 @@
1
- import fs from 'fs';
1
+ import fs, { readFileSync } from 'fs';
2
2
  import path from 'path';
3
3
  import { fileURLToPath } from 'url';
4
4
  import crypto2 from 'crypto';
@@ -23,18 +23,6 @@ var __export = (target, all) => {
23
23
  __defProp(target, name, { get: all[name], enumerable: true });
24
24
  };
25
25
 
26
- // core/suppress-idb-warning.ts
27
- var orig;
28
- var init_suppress_idb_warning = __esm({
29
- "core/suppress-idb-warning.ts"() {
30
- orig = console.warn.bind(console);
31
- console.warn = (...args) => {
32
- if (typeof args[0] === "string" && args[0].includes("IndexedDB is not available")) return;
33
- orig(...args);
34
- };
35
- }
36
- });
37
-
38
26
  // core/env.ts
39
27
  var DEV;
40
28
  var init_env = __esm({
@@ -110,6 +98,56 @@ var init_storage_paths = __esm({
110
98
  }
111
99
  });
112
100
 
101
+ // core/knowledge/text-encoding.ts
102
+ function detectBom(bytes) {
103
+ if (bytes.length >= 3 && bytes[0] === BOM_UTF8 && bytes[1] === 187 && bytes[2] === 191) {
104
+ return "utf-8";
105
+ }
106
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16LE_FIRST && bytes[1] === BOM_UTF16LE_SECOND) {
107
+ return "utf-16le";
108
+ }
109
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16BE_FIRST && bytes[1] === BOM_UTF16BE_SECOND) {
110
+ return "utf-16be";
111
+ }
112
+ return null;
113
+ }
114
+ function decodeText(bytes, options = {}) {
115
+ const bom = detectBom(bytes);
116
+ if (bom === "utf-16le" || bom === "utf-16be") {
117
+ throw new UnsupportedEncodingError(
118
+ `UTF-16 encoded content detected in ${options.source ?? "unknown"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`
119
+ );
120
+ }
121
+ let content = bytes;
122
+ if (bom === "utf-8") {
123
+ content = bytes.subarray(3);
124
+ }
125
+ return strictDecoder.decode(content);
126
+ }
127
+ var strictDecoder, UnsupportedEncodingError, BOM_UTF8, BOM_UTF16LE_FIRST, BOM_UTF16LE_SECOND, BOM_UTF16BE_FIRST, BOM_UTF16BE_SECOND;
128
+ var init_text_encoding = __esm({
129
+ "core/knowledge/text-encoding.ts"() {
130
+ new TextEncoder();
131
+ strictDecoder = new TextDecoder("utf-8", { fatal: true });
132
+ UnsupportedEncodingError = class extends Error {
133
+ static {
134
+ __name(this, "UnsupportedEncodingError");
135
+ }
136
+ constructor(message) {
137
+ super(message);
138
+ this.name = "UnsupportedEncodingError";
139
+ }
140
+ };
141
+ BOM_UTF8 = 239;
142
+ BOM_UTF16LE_FIRST = 255;
143
+ BOM_UTF16LE_SECOND = 254;
144
+ BOM_UTF16BE_FIRST = 254;
145
+ BOM_UTF16BE_SECOND = 255;
146
+ __name(detectBom, "detectBom");
147
+ __name(decodeText, "decodeText");
148
+ }
149
+ });
150
+
113
151
  // core/knowledge/storage-settings.ts
114
152
  var DOTMEM_STORAGE_SETTINGS_FILE_NAME, SETTINGS_MODES, projectRoot, findProjectSettingsFile, discoverProjectSettingsFilePath, resolveUserSettingsFilePath, invalidSettings, parseSettings, resolveSettingsEntry, readTextFile, readStorageSettings;
115
153
  var init_storage_settings = __esm({
@@ -241,15 +279,19 @@ function readDotMemStorageLocator() {
241
279
  const locatorFile = resolveLocatorFilePath(anchor);
242
280
  let raw;
243
281
  try {
244
- raw = fs2.readFileSync(locatorFile, "utf8");
282
+ raw = decodeText(fs2.readFileSync(locatorFile), { source: locatorFile });
245
283
  } catch (error) {
284
+ if (error instanceof UnsupportedEncodingError) {
285
+ throw new DotMemStorageLocationError(
286
+ `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.`
287
+ );
288
+ }
246
289
  const code = error?.code;
247
290
  if (code === "ENOENT") return null;
248
291
  throw new DotMemStorageLocationError(
249
292
  `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} cannot be read (${describeAccessFailure(error)}). No alternative location was selected automatically.`
250
293
  );
251
294
  }
252
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
253
295
  let parsed;
254
296
  try {
255
297
  parsed = JSON.parse(raw);
@@ -341,6 +383,7 @@ var DOTMEM_USER_ANCHOR_DIR_NAME, DOTMEM_STORAGE_LOCATOR_FILE_NAME, DOTMEM_STORAG
341
383
  var init_storage_location = __esm({
342
384
  "core/knowledge/storage-location.ts"() {
343
385
  init_storage_paths();
386
+ init_text_encoding();
344
387
  init_storage_settings();
345
388
  init_storage_paths();
346
389
  DOTMEM_USER_ANCHOR_DIR_NAME = ".dotmem";
@@ -1347,6 +1390,12 @@ var init_state = __esm({
1347
1390
  if (claim.sourceProject !== void 0 && !requiredText(claim.sourceProject)) {
1348
1391
  throw new Error(`Claim ${claim.id} has an invalid sourceProject`);
1349
1392
  }
1393
+ if (claim.check !== void 0) {
1394
+ const check = claim.check;
1395
+ 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)) {
1396
+ throw new Error(`Claim ${claim.id} has an invalid check`);
1397
+ }
1398
+ }
1350
1399
  return claim;
1351
1400
  }, "validateClaim");
1352
1401
  validateKnowledgeState = /* @__PURE__ */ __name((value) => {
@@ -1651,6 +1700,50 @@ var init_scope_eligibility = __esm({
1651
1700
  }
1652
1701
  });
1653
1702
 
1703
+ // core/knowledge/currentness.ts
1704
+ var asRecord, verifiedAtOf, findContestedIds, deriveCurrentness;
1705
+ var init_currentness = __esm({
1706
+ "core/knowledge/currentness.ts"() {
1707
+ asRecord = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0, "asRecord");
1708
+ verifiedAtOf = /* @__PURE__ */ __name((claim) => {
1709
+ const value = asRecord(claim.knowledge)?.verifiedAt;
1710
+ if (typeof value !== "string") return void 0;
1711
+ const parsed = Date.parse(value);
1712
+ return Number.isNaN(parsed) ? void 0 : parsed;
1713
+ }, "verifiedAtOf");
1714
+ findContestedIds = /* @__PURE__ */ __name((claims) => {
1715
+ const retracting = /* @__PURE__ */ new Map();
1716
+ for (const claim of claims) {
1717
+ if (claim.revision?.kind === "retracts" && claim.revision.claimIds.length > 0) {
1718
+ retracting.set(claim.id, new Set(claim.revision.claimIds));
1719
+ }
1720
+ }
1721
+ const contested = /* @__PURE__ */ new Set();
1722
+ for (const [id, targets] of retracting) {
1723
+ for (const target of targets) {
1724
+ if (retracting.get(target)?.has(id)) {
1725
+ contested.add(id);
1726
+ contested.add(target);
1727
+ }
1728
+ }
1729
+ }
1730
+ return contested;
1731
+ }, "findContestedIds");
1732
+ deriveCurrentness = /* @__PURE__ */ __name((claim, context2 = {}) => {
1733
+ const now3 = context2.now ?? Date.now();
1734
+ if (context2.contestedIds?.has(claim.id)) return "contested";
1735
+ if (claim.revision?.kind === "retracts") return "historical";
1736
+ if (context2.retractedIds?.has(claim.id)) return "historical";
1737
+ if (context2.supersededIds?.has(claim.id)) return "superseded";
1738
+ if (claim.expiresAt !== void 0 && now3 >= claim.expiresAt) return "expired";
1739
+ const verifiedAt = verifiedAtOf(claim);
1740
+ if (verifiedAt !== void 0) return "verified";
1741
+ if (claim.epistemicType === "verified") return "unverified";
1742
+ return "unknown-currentness";
1743
+ }, "deriveCurrentness");
1744
+ }
1745
+ });
1746
+
1654
1747
  // core/knowledge/discover.ts
1655
1748
  var diagnostic, DEFAULT_LIMITS, FIELD_ORDER, FIELD_WEIGHT, normalize, discoveryTerms, jsonText, fieldText, acquiredTime, isExpired, rankCandidate, discoverAcquiredExperience;
1656
1749
  var init_discover = __esm({
@@ -1658,6 +1751,7 @@ var init_discover = __esm({
1658
1751
  init_state();
1659
1752
  init_applicability();
1660
1753
  init_scope_eligibility();
1754
+ init_currentness();
1661
1755
  init_env();
1662
1756
  diagnostic = /* @__PURE__ */ __name((message) => {
1663
1757
  if (typeof process !== "undefined" && typeof process.stderr?.write === "function") {
@@ -1770,11 +1864,78 @@ var init_discover = __esm({
1770
1864
  throw new Error("Discovery maxCandidates must be a positive integer");
1771
1865
  }
1772
1866
  const queryTerms = discoveryTerms(situation);
1867
+ const offset = options.cursor?.offset ?? 0;
1868
+ if (!Number.isInteger(offset) || offset < 0) {
1869
+ throw new Error("Discovery cursor offset must be a non-negative integer");
1870
+ }
1871
+ if (options.cursor && options.cursor.knowledgeVersion !== validated.version) {
1872
+ return {
1873
+ knowledgeVersion: validated.version,
1874
+ depth,
1875
+ queryTerms,
1876
+ candidates: [],
1877
+ omissions: [],
1878
+ offset: 0,
1879
+ snapshotChanged: true
1880
+ };
1881
+ }
1773
1882
  const available = activeClaims(validated);
1883
+ const availableIds = new Set(available.map((claim) => claim.id));
1884
+ const retractedIds = /* @__PURE__ */ new Set();
1885
+ const supersededIds = /* @__PURE__ */ new Set();
1886
+ const contestedIds = findContestedIds(validated.claims);
1887
+ for (const claim of validated.claims) {
1888
+ if (claim.revision?.kind === "retracts") {
1889
+ for (const id of claim.revision.claimIds) retractedIds.add(id);
1890
+ }
1891
+ if (claim.revision?.kind === "supersedes") {
1892
+ for (const id of claim.revision.claimIds) supersededIds.add(id);
1893
+ }
1894
+ }
1895
+ const revisionOmissions = validated.claims.filter((claim) => !availableIds.has(claim.id)).map((claim) => {
1896
+ const retracted = retractedIds.has(claim.id);
1897
+ const superseded = supersededIds.has(claim.id);
1898
+ return {
1899
+ id: claim.id,
1900
+ reason: retracted ? "retracted" : superseded ? "superseded" : "retracted",
1901
+ gate: "revision-resolution",
1902
+ ...retracted || superseded ? {} : { detail: "the claim itself retracts prior knowledge and is kept as history" }
1903
+ };
1904
+ }).sort((left, right) => left.id.localeCompare(right.id));
1774
1905
  const scopeEligible = options.currentProjectId === void 0 ? available : available.filter((claim) => isScopeEligible(claim, options.currentProjectId, sources.get(claim.id)));
1775
1906
  const freshEligible = scopeEligible.filter((claim) => !isExpired(claim));
1907
+ const scopeEligibleIds = new Set(scopeEligible.map((claim) => claim.id));
1908
+ const scopeOmissions = available.filter((claim) => !scopeEligibleIds.has(claim.id)).map((claim) => {
1909
+ const owner = claimOwnerProject(claim, sources.get(claim.id));
1910
+ return {
1911
+ id: claim.id,
1912
+ reason: "scope",
1913
+ gate: "scope",
1914
+ detail: owner === void 0 ? "owner project could not be resolved" : `owned by project ${owner}`
1915
+ };
1916
+ }).sort((left, right) => left.id.localeCompare(right.id));
1917
+ const freshIds = new Set(freshEligible.map((claim) => claim.id));
1918
+ const freshnessOmissions = scopeEligible.filter((claim) => !freshIds.has(claim.id)).map((claim) => ({
1919
+ id: claim.id,
1920
+ reason: "expired",
1921
+ gate: "freshness",
1922
+ detail: `expired at ${new Date(claim.expiresAt).toISOString()}`
1923
+ })).sort((left, right) => left.id.localeCompare(right.id));
1776
1924
  const situationApplicability = deriveSituationApplicability(situation, options.facts);
1777
- const eligible = freshEligible.map((claim) => ({ claim, match: isEligibleByApplicability(claim, situationApplicability) })).filter((candidate) => candidate.match.eligible);
1925
+ const applicabilityMatches = new Map(
1926
+ freshEligible.map((claim) => [claim.id, isEligibleByApplicability(claim, situationApplicability)])
1927
+ );
1928
+ const eligible = freshEligible.map((claim) => ({ claim, match: applicabilityMatches.get(claim.id) })).filter((candidate) => candidate.match.eligible);
1929
+ const applicabilityOmissions = freshEligible.filter((claim) => !applicabilityMatches.get(claim.id).eligible).map((claim) => {
1930
+ const match = applicabilityMatches.get(claim.id);
1931
+ const mismatched = Object.entries(match.dimensions).filter(([, state3]) => state3 === "MISMATCH").map(([dimension]) => dimension);
1932
+ return {
1933
+ id: claim.id,
1934
+ reason: "applicability-mismatch",
1935
+ gate: "applicability",
1936
+ detail: `mismatching dimensions: ${mismatched.length > 0 ? mismatched.join(", ") : "none recorded"}`
1937
+ };
1938
+ }).sort((left, right) => left.id.localeCompare(right.id));
1778
1939
  if (DEV) {
1779
1940
  diagnostic(
1780
1941
  "[dotmem discovery] ACTIVE=" + JSON.stringify(
@@ -1786,12 +1947,15 @@ var init_discover = __esm({
1786
1947
  )
1787
1948
  );
1788
1949
  }
1950
+ const currentnessOf = /* @__PURE__ */ __name((claim) => deriveCurrentness(claim, { retractedIds, supersededIds, contestedIds }), "currentnessOf");
1789
1951
  if (queryTerms.length === 0) {
1790
- const baseline = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1952
+ const baselineAll = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
1791
1953
  const leftTime = acquiredTime(left);
1792
1954
  const rightTime = acquiredTime(right);
1793
1955
  return rightTime - leftTime || Number(right.scope === "project") - Number(left.scope === "project") || left.id.localeCompare(right.id);
1794
- }).slice(0, maxCandidates);
1956
+ });
1957
+ const baseline = baselineAll.slice(offset, offset + maxCandidates);
1958
+ const limitOmissions = baselineAll.slice(offset + maxCandidates).map((claim) => ({ id: claim.id, reason: "limit", gate: "ranking" })).sort((left, right) => left.id.localeCompare(right.id));
1795
1959
  const baselineCandidates = baseline.map((claim) => {
1796
1960
  const explanation = {
1797
1961
  matchedTerms: [],
@@ -1804,7 +1968,8 @@ var init_discover = __esm({
1804
1968
  }
1805
1969
  return {
1806
1970
  claim,
1807
- explanation
1971
+ explanation,
1972
+ currentness: currentnessOf(claim)
1808
1973
  };
1809
1974
  });
1810
1975
  if (DEV) {
@@ -1817,10 +1982,18 @@ var init_discover = __esm({
1817
1982
  depth,
1818
1983
  queryTerms,
1819
1984
  situationApplicability,
1820
- candidates: baselineCandidates
1985
+ candidates: baselineCandidates,
1986
+ offset,
1987
+ omissions: [
1988
+ ...revisionOmissions,
1989
+ ...scopeOmissions,
1990
+ ...freshnessOmissions,
1991
+ ...applicabilityOmissions,
1992
+ ...limitOmissions
1993
+ ]
1821
1994
  };
1822
1995
  }
1823
- const candidates = eligible.map(
1996
+ const ranked = eligible.map(
1824
1997
  (candidate) => rankCandidate(
1825
1998
  candidate.claim,
1826
1999
  situation,
@@ -1832,16 +2005,40 @@ var init_discover = __esm({
1832
2005
  (candidate) => candidate !== null
1833
2006
  ).sort(
1834
2007
  (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)
1835
- ).slice(0, maxCandidates).map(({ claim, explanation }) => ({
2008
+ );
2009
+ const rankedIds = new Set(ranked.map((candidate) => candidate.claim.id));
2010
+ const rankingOmissions = [
2011
+ ...eligible.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2012
+ id: candidate.claim.id,
2013
+ reason: "no-term-match",
2014
+ gate: "ranking",
2015
+ detail: "passed every gate but shares no query term"
2016
+ })),
2017
+ ...ranked.slice(offset + maxCandidates).map((candidate) => ({
2018
+ id: candidate.claim.id,
2019
+ reason: "limit",
2020
+ gate: "ranking"
2021
+ }))
2022
+ ].sort((left, right) => left.id.localeCompare(right.id));
2023
+ const candidates = ranked.slice(offset, offset + maxCandidates).map(({ claim, explanation }) => ({
1836
2024
  claim,
1837
- explanation
2025
+ explanation,
2026
+ currentness: currentnessOf(claim)
1838
2027
  }));
1839
2028
  return {
1840
2029
  knowledgeVersion: validated.version,
1841
2030
  depth,
1842
2031
  queryTerms,
1843
2032
  situationApplicability,
1844
- candidates
2033
+ candidates,
2034
+ offset,
2035
+ omissions: [
2036
+ ...revisionOmissions,
2037
+ ...scopeOmissions,
2038
+ ...freshnessOmissions,
2039
+ ...applicabilityOmissions,
2040
+ ...rankingOmissions
2041
+ ]
1845
2042
  };
1846
2043
  }, "discoverAcquiredExperience");
1847
2044
  }
@@ -2898,7 +3095,7 @@ var init_policy_store = __esm({
2898
3095
  });
2899
3096
 
2900
3097
  // core/knowledge/acquisition-limits.ts
2901
- var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder, serializedBytes, measureKnowledge, checkAcquireLimits;
3098
+ var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder2, serializedBytes, measureKnowledge, checkAcquireLimits;
2902
3099
  var init_acquisition_limits = __esm({
2903
3100
  "core/knowledge/acquisition-limits.ts"() {
2904
3101
  MEMORY_ACQUIRE_LIMITS = Object.freeze({
@@ -2957,10 +3154,10 @@ var init_acquisition_limits = __esm({
2957
3154
  this.name = "MemoryAcquireDuplicateClaimError";
2958
3155
  }
2959
3156
  };
2960
- encoder = new TextEncoder();
3157
+ encoder2 = new TextEncoder();
2961
3158
  serializedBytes = /* @__PURE__ */ __name((value) => {
2962
3159
  const json = JSON.stringify(value);
2963
- return json === void 0 ? 0 : encoder.encode(json).length;
3160
+ return json === void 0 ? 0 : encoder2.encode(json).length;
2964
3161
  }, "serializedBytes");
2965
3162
  measureKnowledge = /* @__PURE__ */ __name((knowledge) => {
2966
3163
  const claimBytes = serializedBytes(knowledge);
@@ -3055,7 +3252,7 @@ var init_context_constants = __esm({
3055
3252
  });
3056
3253
 
3057
3254
  // core/knowledge/project.ts
3058
- var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_MAX_CHARACTERS, projectCandidate, renderHeader, renderExperience, renderText, projectDiscoveredExperience;
3255
+ 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;
3059
3256
  var init_project = __esm({
3060
3257
  "core/knowledge/project.ts"() {
3061
3258
  init_state();
@@ -3080,9 +3277,29 @@ var init_project = __esm({
3080
3277
  ...claim.provenance ? { provenance: claim.provenance } : {},
3081
3278
  ...claim.acquiredAt ? { acquiredAt: claim.acquiredAt } : {},
3082
3279
  ...claim.revision ? { revision: claim.revision } : {},
3083
- ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {}
3280
+ ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {},
3281
+ ...candidate.currentness ? { currentness: candidate.currentness } : {}
3084
3282
  });
3085
3283
  }, "projectCandidate");
3284
+ GIST_MAX_LENGTH = 80;
3285
+ GIST_KEYS = ["gist", "summary", "statement", "title", "reason", "principle", "finding", "detail"];
3286
+ MANIFEST_ID_LIMIT = 40;
3287
+ deriveGist = /* @__PURE__ */ __name((knowledge) => {
3288
+ if (typeof knowledge === "string") {
3289
+ return knowledge.length > GIST_MAX_LENGTH ? `${knowledge.slice(0, GIST_MAX_LENGTH)}\u2026` : knowledge;
3290
+ }
3291
+ if (knowledge && typeof knowledge === "object" && !Array.isArray(knowledge)) {
3292
+ const obj = knowledge;
3293
+ for (const key of GIST_KEYS) {
3294
+ const value = obj[key];
3295
+ if (typeof value === "string" && value.length > 0) {
3296
+ return value.length > GIST_MAX_LENGTH ? `${value.slice(0, GIST_MAX_LENGTH)}\u2026` : value;
3297
+ }
3298
+ }
3299
+ }
3300
+ const str = JSON.stringify(knowledge);
3301
+ return str.length > GIST_MAX_LENGTH ? `${str.slice(0, GIST_MAX_LENGTH)}\u2026` : str;
3302
+ }, "deriveGist");
3086
3303
  renderHeader = /* @__PURE__ */ __name((knowledgeVersion, totalCandidates) => {
3087
3304
  const lines = [
3088
3305
  `DOTMEM STORAGE: ${resolveUserDotMemPath()}`,
@@ -3108,27 +3325,70 @@ var init_project = __esm({
3108
3325
  evidence.supports ?? null
3109
3326
  ]),
3110
3327
  ...experience.epistemicType ? { epistemic: experience.epistemicType } : {},
3328
+ ...experience.currentness ? { currentness: experience.currentness } : {},
3111
3329
  ...experience.provenance ? { provenance: [experience.provenance.source, experience.provenance.detail ?? null] } : {},
3112
3330
  ...experience.acquiredAt ? { acquiredAt: experience.acquiredAt } : {},
3113
3331
  ...experience.revision ? { revision: experience.revision } : {},
3114
3332
  ...experience.sourceId ? { source: experience.sourceId } : {}
3115
3333
  }), "renderExperience");
3116
- renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates) => `${header}${experiences.length ? `
3117
- ${experiences.map(renderExperience).join("\n")}` : ""}
3118
- OMITTED:${omittedCandidates}`, "renderText");
3334
+ renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, render = renderExperience, currentnessSummary) => {
3335
+ const lines = [header];
3336
+ if (experiences.length > 0) lines.push(...experiences.map(render));
3337
+ lines.push(`OMITTED:${omittedCandidates}`);
3338
+ if (manifest && manifest.byReason.length > 0) {
3339
+ lines.push(`OMITTED_BY_REASON:${manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`);
3340
+ }
3341
+ if (manifest && manifest.items.length > 0) {
3342
+ lines.push(`OMITTED_IDS:${manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`);
3343
+ if (manifest.items.length > MANIFEST_ID_LIMIT) {
3344
+ lines.push(`OMITTED_IDS_TRUNCATED:${manifest.items.length - MANIFEST_ID_LIMIT}`);
3345
+ }
3346
+ }
3347
+ if (currentnessSummary) {
3348
+ lines.push(`CURRENTNESS:${currentnessSummary}`);
3349
+ }
3350
+ return lines.join("\n");
3351
+ }, "renderText");
3352
+ byteLength = /* @__PURE__ */ __name((value) => new TextEncoder().encode(value).length, "byteLength");
3353
+ summarizeOmissions = /* @__PURE__ */ __name((items) => {
3354
+ const counts = /* @__PURE__ */ new Map();
3355
+ for (const item of items) counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
3356
+ return [...counts.entries()].map(([reason, count]) => ({ reason, count })).sort((left, right) => left.reason.localeCompare(right.reason));
3357
+ }, "summarizeOmissions");
3358
+ renderManifestFitting = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, maxCharacters, render, currentnessSummary) => {
3359
+ const full = renderText(header, experiences, omittedCandidates, manifest, render, currentnessSummary);
3360
+ if (byteLength(full) <= maxCharacters) return full;
3361
+ const withoutIds = { ...manifest, items: [] };
3362
+ return renderText(header, experiences, omittedCandidates, withoutIds, render, currentnessSummary);
3363
+ }, "renderManifestFitting");
3364
+ renderCompactExperience = /* @__PURE__ */ __name((experience) => JSON.stringify({
3365
+ id: experience.id,
3366
+ status: "candidate",
3367
+ gist: deriveGist(experience.experience),
3368
+ epistemic: experience.epistemicType ?? null,
3369
+ currentness: experience.currentness ?? null,
3370
+ ...experience.revision ? { revision: experience.revision.kind } : {}
3371
+ }), "renderCompactExperience");
3119
3372
  projectDiscoveredExperience = /* @__PURE__ */ __name((discovery, options = {}) => {
3120
3373
  if (!discovery || !Number.isInteger(discovery.knowledgeVersion) || discovery.knowledgeVersion < 0 || !Array.isArray(discovery.candidates)) {
3121
3374
  throw new Error("Valid DiscoveryResult is required for context projection");
3122
3375
  }
3123
3376
  const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES;
3124
3377
  const maxCharacters = options.maxCharacters ?? DEFAULT_MAX_CHARACTERS;
3378
+ const format = options.format ?? "compact";
3379
+ if (format !== "compact" && format !== "standard" && format !== "full") {
3380
+ throw new Error("Projection format must be compact, standard or full");
3381
+ }
3125
3382
  if (!Number.isInteger(maxCandidates) || maxCandidates < 1) throw new Error("Projection maxCandidates must be a positive integer");
3126
3383
  if (!Number.isInteger(maxCharacters) || maxCharacters < MIN_MAX_CHARACTERS) {
3127
3384
  throw new Error(`Projection maxCharacters must be an integer of at least ${MIN_MAX_CHARACTERS}`);
3128
3385
  }
3129
- const totalCandidates = discovery.candidates.length;
3386
+ const render = /* @__PURE__ */ __name((experience) => format === "compact" ? renderCompactExperience(experience) : renderExperience(experience), "render");
3387
+ const gateOmissions = discovery.omissions ?? [];
3388
+ const totalCandidates = discovery.candidates.length + gateOmissions.length;
3130
3389
  const header = renderHeader(discovery.knowledgeVersion, totalCandidates);
3131
- if (renderText(header, [], totalCandidates).length > maxCharacters) {
3390
+ const emptyManifest = { considered: totalCandidates, included: 0, items: [], byReason: [] };
3391
+ if (byteLength(renderText(header, [], totalCandidates, emptyManifest)) > maxCharacters) {
3132
3392
  throw new Error("Projection maxCharacters is too small for the projection envelope");
3133
3393
  }
3134
3394
  const experiences = [];
@@ -3137,12 +3397,49 @@ OMITTED:${omittedCandidates}`, "renderText");
3137
3397
  const projected = projectCandidate(candidate);
3138
3398
  const possibleExperiences = [...experiences, projected];
3139
3399
  const possibleOmitted = totalCandidates - possibleExperiences.length;
3140
- if (renderText(header, possibleExperiences, possibleOmitted).length <= maxCharacters) {
3400
+ const candidateManifest = {
3401
+ considered: totalCandidates,
3402
+ included: possibleExperiences.length,
3403
+ items: gateOmissions,
3404
+ byReason: summarizeOmissions(gateOmissions)
3405
+ };
3406
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, candidateManifest, render)) <= maxCharacters) {
3407
+ experiences.push(projected);
3408
+ continue;
3409
+ }
3410
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, void 0, render)) <= maxCharacters) {
3141
3411
  experiences.push(projected);
3142
3412
  }
3143
3413
  }
3414
+ const projectedIds = new Set(experiences.map((experience) => experience.id));
3415
+ const budgetOmissions = discovery.candidates.filter((candidate) => !projectedIds.has(candidate.claim.id)).map((candidate) => ({ id: candidate.claim.id, reason: "budget", gate: "projection" }));
3416
+ const items = [...gateOmissions, ...budgetOmissions];
3144
3417
  const omittedCandidates = totalCandidates - experiences.length;
3145
- const text = renderText(header, experiences, omittedCandidates);
3418
+ const manifest = {
3419
+ considered: totalCandidates,
3420
+ included: experiences.length,
3421
+ items,
3422
+ byReason: summarizeOmissions(items)
3423
+ };
3424
+ const currentnessCounts = /* @__PURE__ */ new Map();
3425
+ for (const experience of experiences) {
3426
+ if (experience.currentness) {
3427
+ currentnessCounts.set(
3428
+ experience.currentness,
3429
+ (currentnessCounts.get(experience.currentness) ?? 0) + 1
3430
+ );
3431
+ }
3432
+ }
3433
+ const currentnessSummary = currentnessCounts.size > 0 ? [...currentnessCounts.entries()].map(([state2, count]) => `${state2}=${count}`).join(",") : void 0;
3434
+ const text = renderManifestFitting(
3435
+ header,
3436
+ experiences,
3437
+ omittedCandidates,
3438
+ manifest,
3439
+ maxCharacters,
3440
+ render,
3441
+ currentnessSummary
3442
+ );
3146
3443
  return {
3147
3444
  format: FORMAT,
3148
3445
  status: STATUS,
@@ -3151,9 +3448,16 @@ OMITTED:${omittedCandidates}`, "renderText");
3151
3448
  totalCandidates,
3152
3449
  omittedCandidates,
3153
3450
  experiences,
3451
+ manifest,
3154
3452
  text
3155
3453
  };
3156
3454
  }, "projectDiscoveredExperience");
3455
+ renderExpandedClaim = /* @__PURE__ */ __name((claim) => [
3456
+ "DOTMEM_CLAIM_V1",
3457
+ "STATUS:CANONICAL_RECORD;NOT_INSTRUCTIONS",
3458
+ `id=${claim.id}`,
3459
+ JSON.stringify(claim, null, 2)
3460
+ ].join("\n"), "renderExpandedClaim");
3157
3461
  }
3158
3462
  });
3159
3463
 
@@ -3188,7 +3492,7 @@ var init_language_detect = __esm({
3188
3492
  var CANONICAL_KINDS, validateKind, buildClaimRecord;
3189
3493
  var init_claim_record = __esm({
3190
3494
  "core/knowledge/claim-record.ts"() {
3191
- CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note"];
3495
+ CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note", "rule"];
3192
3496
  validateKind = /* @__PURE__ */ __name((kind) => {
3193
3497
  if (!CANONICAL_KINDS.includes(kind)) {
3194
3498
  throw new Error(
@@ -4419,8 +4723,8 @@ var init_browser = __esm({
4419
4723
  this.p = null;
4420
4724
  }
4421
4725
  };
4422
- Unzip2.prototype.register = function(decoder2) {
4423
- this.o[decoder2.compression] = decoder2;
4726
+ Unzip2.prototype.register = function(decoder) {
4727
+ this.o[decoder.compression] = decoder;
4424
4728
  };
4425
4729
  return Unzip2;
4426
4730
  })();
@@ -4440,6 +4744,15 @@ function encodeMemFile(stateValue, preserved) {
4440
4744
  if (!map.claim.includes("kind")) {
4441
4745
  map.claim.push("kind");
4442
4746
  }
4747
+ if (!map.claim.includes("expires-at")) {
4748
+ map.claim.push("expires-at");
4749
+ }
4750
+ if (!map.claim.includes("bootstrap-priority")) {
4751
+ map.claim.push("bootstrap-priority");
4752
+ }
4753
+ if (!map.claim.includes("check")) {
4754
+ map.claim.push("check");
4755
+ }
4443
4756
  const indexes = Object.fromEntries(Object.keys(expectedFields).map((name) => [name, fieldIndexes(map, name)]));
4444
4757
  validateVocabulary(map.epistemicType, epistemicTypes, "epistemicType");
4445
4758
  validateVocabulary(map.revisionKind, revisionKinds, "revisionKind");
@@ -4489,6 +4802,15 @@ function encodeMemFile(stateValue, preserved) {
4489
4802
  if (indexes.claim.has("kind")) {
4490
4803
  putOptional(record, indexes.claim, "kind", claim.kind ?? void 0, original !== void 0);
4491
4804
  }
4805
+ if (indexes.claim.has("expires-at")) {
4806
+ putOptional(record, indexes.claim, "expires-at", claim.expiresAt, original !== void 0);
4807
+ }
4808
+ if (indexes.claim.has("bootstrap-priority")) {
4809
+ putOptional(record, indexes.claim, "bootstrap-priority", claim.bootstrapPriority, original !== void 0);
4810
+ }
4811
+ if (indexes.claim.has("check")) {
4812
+ putOptional(record, indexes.claim, "check", claim.check, original !== void 0);
4813
+ }
4492
4814
  return original ? record : trimRecord(record);
4493
4815
  }, "encodeClaim");
4494
4816
  const stateRecord = structuredClone(preserved?.data ?? []);
@@ -4557,8 +4879,37 @@ function decodeMemDocument(value) {
4557
4879
  const scope = optionalGet(record, indexes.claim, "scope");
4558
4880
  const sourceProject = optionalGet(record, indexes.claim, "source-project");
4559
4881
  const kindValue = optionalGet(record, indexes.claim, "kind");
4882
+ const expiresAtValue = indexes.claim.has("expires-at") ? optionalGet(record, indexes.claim, "expires-at") : void 0;
4883
+ const bootstrapPriorityValue = indexes.claim.has("bootstrap-priority") ? optionalGet(record, indexes.claim, "bootstrap-priority") : void 0;
4884
+ const checkValue = indexes.claim.has("check") ? optionalGet(record, indexes.claim, "check") : void 0;
4560
4885
  if (epistemicIndex !== void 0 && (!Number.isInteger(epistemicIndex) || epistemicIndex < 0 || epistemicIndex >= epistemic.length)) throw new Error("Invalid .mem epistemic value");
4561
4886
  if (kindIndex !== void 0 && (!Number.isInteger(kindIndex) || kindIndex < 0 || kindIndex >= revisions.length)) throw new Error("Invalid .mem revision value");
4887
+ if (expiresAtValue !== void 0 && (!Number.isInteger(expiresAtValue) || expiresAtValue < 0)) {
4888
+ throw new Error("Invalid .mem expiresAt value");
4889
+ }
4890
+ if (bootstrapPriorityValue !== void 0 && !bootstrapPriorities.includes(bootstrapPriorityValue)) {
4891
+ throw new Error("Invalid .mem bootstrapPriority value");
4892
+ }
4893
+ let check;
4894
+ if (checkValue !== void 0) {
4895
+ if (!checkValue || typeof checkValue !== "object" || Array.isArray(checkValue)) {
4896
+ throw new Error("Invalid .mem check record");
4897
+ }
4898
+ const checkRecord = checkValue;
4899
+ const description = checkRecord.description;
4900
+ if (typeof description !== "undefined" && typeof description !== "string") {
4901
+ throw new Error("Invalid .mem check record");
4902
+ }
4903
+ if (checkRecord.kind !== "regex" || typeof checkRecord.pattern !== "string" || checkRecord.pattern.length === 0 || !checkTargets.includes(checkRecord.on)) {
4904
+ throw new Error("Invalid .mem check record");
4905
+ }
4906
+ check = {
4907
+ kind: "regex",
4908
+ pattern: checkRecord.pattern,
4909
+ on: checkRecord.on,
4910
+ ...typeof description === "string" ? { description } : {}
4911
+ };
4912
+ }
4562
4913
  const understoodEpistemic = typeof epistemicIndex === "number" && epistemicTypes.includes(epistemic[epistemicIndex]) ? epistemic[epistemicIndex] : void 0;
4563
4914
  const understoodRevision = typeof kindIndex === "number" && revisionKinds.includes(revisions[kindIndex]);
4564
4915
  const claim = {
@@ -4583,6 +4934,9 @@ function decodeMemDocument(value) {
4583
4934
  } : {},
4584
4935
  ...scope === void 0 ? {} : { scope },
4585
4936
  ...sourceProject === void 0 ? {} : { sourceProject },
4937
+ ...expiresAtValue === void 0 ? {} : { expiresAt: expiresAtValue },
4938
+ ...bootstrapPriorityValue === void 0 ? {} : { bootstrapPriority: bootstrapPriorityValue },
4939
+ ...check === void 0 ? {} : { check },
4586
4940
  ...claimKinds.includes(kindValue) ? { kind: kindValue } : {}
4587
4941
  };
4588
4942
  return validateClaim(claim);
@@ -4592,7 +4946,7 @@ function decodeMemDocument(value) {
4592
4946
  preserved: { map: structuredClone(map), data: structuredClone(stateRecord) }
4593
4947
  };
4594
4948
  }
4595
- 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;
4949
+ 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;
4596
4950
  var init_mem_codec = __esm({
4597
4951
  "core/knowledge/mem-codec.ts"() {
4598
4952
  init_state();
@@ -4609,7 +4963,9 @@ var init_mem_codec = __esm({
4609
4963
  };
4610
4964
  epistemicTypes = ["observed", "inferred", "human-stated", "verified"];
4611
4965
  revisionKinds = ["refines", "supersedes", "retracts"];
4612
- claimKinds = ["experience", "agent", "relationship", "logic", "note"];
4966
+ claimKinds = ["experience", "agent", "relationship", "logic", "note", "rule"];
4967
+ bootstrapPriorities = ["P1", "P2", "P3", "P4", "P5", "unclassified"];
4968
+ checkTargets = ["staged", "committed", "working-tree"];
4613
4969
  isJsonValue2 = /* @__PURE__ */ __name((value) => {
4614
4970
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
4615
4971
  if (typeof value === "number") return Number.isFinite(value);
@@ -4683,14 +5039,14 @@ async function encodeMemPackage(state2, semantic, preservedPackage) {
4683
5039
  return encodePackage(state2, semantic, preservedPackage);
4684
5040
  }
4685
5041
  async function decodeMemArtifact(input) {
4686
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
5042
+ const bytes = typeof input === "string" ? encoder3.encode(input) : input;
4687
5043
  if (isZip(bytes)) {
4688
5044
  const { parts: _parts, integrity: _integrity, ...artifact } = await decodePackage(bytes);
4689
5045
  return artifact;
4690
5046
  }
4691
5047
  let value;
4692
5048
  try {
4693
- value = JSON.parse(decoder.decode(bytes).replace(/^\uFEFF/, ""));
5049
+ value = JSON.parse(decodeText(bytes));
4694
5050
  } catch (error) {
4695
5051
  throw new MemArtifactError("corrupt", `Unsupported or corrupt MEM artifact: ${error.message}`);
4696
5052
  }
@@ -4703,11 +5059,12 @@ async function decodeMemArtifact(input) {
4703
5059
  throw new MemArtifactError(message.startsWith("Unsupported") ? "unsupported" : "invalid", message);
4704
5060
  }
4705
5061
  }
4706
- 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;
5062
+ 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;
4707
5063
  var init_mem_package = __esm({
4708
5064
  "core/knowledge/mem-package.ts"() {
4709
5065
  init_browser();
4710
5066
  init_mem_codec();
5067
+ init_text_encoding();
4711
5068
  MEM_PACKAGE_FORMAT = "dotmem.package";
4712
5069
  MEM_PACKAGE_FORMAT_LEGACY = "memorio.package";
4713
5070
  MEM_PACKAGE_VERSION = 1;
@@ -4731,8 +5088,7 @@ var init_mem_package = __esm({
4731
5088
  DATA_PATH = "memory/data.json";
4732
5089
  INTEGRITY_PATH = "security/integrity.json";
4733
5090
  requiredParts = [MANIFEST_PATH, MAP_PATH, DATA_PATH];
4734
- encoder2 = new TextEncoder();
4735
- decoder = new TextDecoder("utf-8", { fatal: true });
5091
+ encoder3 = new TextEncoder();
4736
5092
  MemArtifactError = class extends Error {
4737
5093
  constructor(code, message) {
4738
5094
  super(message);
@@ -4751,7 +5107,7 @@ var init_mem_package = __esm({
4751
5107
  }
4752
5108
  return value;
4753
5109
  }, "stableValue");
4754
- jsonBytes = /* @__PURE__ */ __name((value) => encoder2.encode(`${JSON.stringify(stableValue(value), null, 2)}
5110
+ jsonBytes = /* @__PURE__ */ __name((value) => encoder3.encode(`${JSON.stringify(stableValue(value), null, 2)}
4755
5111
  `), "jsonBytes");
4756
5112
  sha256 = /* @__PURE__ */ __name(async (data) => {
4757
5113
  if (!globalThis.crypto?.subtle) throw new MemArtifactError("unsupported", "SHA-256 is unavailable in this runtime");
@@ -4760,7 +5116,7 @@ var init_mem_package = __esm({
4760
5116
  }, "sha256");
4761
5117
  parseJson = /* @__PURE__ */ __name((bytes, path2) => {
4762
5118
  try {
4763
- return JSON.parse(decoder.decode(bytes));
5119
+ return JSON.parse(decodeText(bytes));
4764
5120
  } catch (error) {
4765
5121
  throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path2}: ${error.message}`);
4766
5122
  }
@@ -4930,10 +5286,12 @@ var init_mem_package = __esm({
4930
5286
  });
4931
5287
 
4932
5288
  // core/storage-coordinator/index.ts
4933
- var nodeFs4, withStorageLock, readStorageGeneration, writeStorageGeneration;
5289
+ var nodeFs4, heldLocks, withStorageLock, readStorageGeneration, writeStorageGeneration;
4934
5290
  var init_storage_coordinator = __esm({
4935
5291
  "core/storage-coordinator/index.ts"() {
5292
+ init_text_encoding();
4936
5293
  nodeFs4 = /* @__PURE__ */ __name(async () => import('fs/promises'), "nodeFs");
5294
+ heldLocks = /* @__PURE__ */ new Map();
4937
5295
  withStorageLock = /* @__PURE__ */ __name(async (directoryPath, operationOrOptions, operation, _options = {}) => {
4938
5296
  const opts = typeof operationOrOptions === "function" ? operation ?? {} : operationOrOptions ?? {};
4939
5297
  const op = typeof operationOrOptions === "function" ? operationOrOptions : operation;
@@ -4943,6 +5301,15 @@ var init_storage_coordinator = __esm({
4943
5301
  const lockPath = `${directoryPath}/${lockName}`;
4944
5302
  const fs2 = await nodeFs4();
4945
5303
  const started = Date.now();
5304
+ const heldDepth = heldLocks.get(lockPath) ?? 0;
5305
+ if (heldDepth > 0) {
5306
+ heldLocks.set(lockPath, heldDepth + 1);
5307
+ try {
5308
+ return await op();
5309
+ } finally {
5310
+ heldLocks.set(lockPath, heldDepth);
5311
+ }
5312
+ }
4946
5313
  await fs2.mkdir(directoryPath, { recursive: true });
4947
5314
  while (true) {
4948
5315
  try {
@@ -4956,8 +5323,8 @@ var init_storage_coordinator = __esm({
4956
5323
  let stale = false;
4957
5324
  let processDead = false;
4958
5325
  try {
4959
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
4960
- const parsed = JSON.parse(raw);
5326
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5327
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
4961
5328
  const ageStale = typeof parsed.createdAt === "number" && Date.now() - parsed.createdAt > staleMs;
4962
5329
  if (typeof parsed.pid === "number") {
4963
5330
  try {
@@ -4994,17 +5361,19 @@ var init_storage_coordinator = __esm({
4994
5361
  }
4995
5362
  let token = "";
4996
5363
  try {
4997
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
4998
- token = JSON.parse(raw).token ?? "";
5364
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5365
+ token = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` })).token ?? "";
4999
5366
  } catch {
5000
5367
  token = "";
5001
5368
  }
5002
5369
  try {
5370
+ heldLocks.set(lockPath, 1);
5003
5371
  return await op();
5004
5372
  } finally {
5373
+ heldLocks.delete(lockPath);
5005
5374
  try {
5006
- const raw = await fs2.readFile(`${lockPath}/owner.json`, "utf8");
5007
- const parsed = JSON.parse(raw);
5375
+ const raw = await fs2.readFile(`${lockPath}/owner.json`);
5376
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
5008
5377
  if (parsed.token === token && token) {
5009
5378
  await fs2.rm(lockPath, { recursive: true, force: true });
5010
5379
  }
@@ -5015,8 +5384,8 @@ var init_storage_coordinator = __esm({
5015
5384
  readStorageGeneration = /* @__PURE__ */ __name(async (directoryPath) => {
5016
5385
  const fs2 = await nodeFs4();
5017
5386
  try {
5018
- const raw = await fs2.readFile(`${directoryPath}/.storage.generation`, "utf8");
5019
- const value = Number(raw.trim());
5387
+ const raw = await fs2.readFile(`${directoryPath}/.storage.generation`);
5388
+ const value = Number(decodeText(raw, { source: `${directoryPath}/.storage.generation` }).trim());
5020
5389
  return Number.isFinite(value) && value >= 0 ? value : 0;
5021
5390
  } catch {
5022
5391
  return 0;
@@ -5504,12 +5873,11 @@ function readJsonFile(path2) {
5504
5873
  if (!fs2) return null;
5505
5874
  let raw;
5506
5875
  try {
5507
- raw = fs2.readFileSync(path2, "utf8");
5876
+ raw = decodeText(fs2.readFileSync(path2), { source: path2 });
5508
5877
  } catch {
5509
5878
  return null;
5510
5879
  }
5511
5880
  if (typeof raw !== "string") return null;
5512
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
5513
5881
  try {
5514
5882
  return JSON.parse(raw);
5515
5883
  } catch {
@@ -5633,6 +6001,7 @@ var init_user_language = __esm({
5633
6001
  "core/knowledge/user-language.ts"() {
5634
6002
  init_user_paths();
5635
6003
  init_storage_paths();
6004
+ init_text_encoding();
5636
6005
  USER_LANGUAGE_FILE_NAME = "language.json";
5637
6006
  USER_LANGUAGE_PREFERENCE_FILE_NAME = "user-language.json";
5638
6007
  LANGUAGE_PREFERENCE_FILE_NAME = "language-preference.json";
@@ -9356,10 +9725,13 @@ var init_staging = __esm({
9356
9725
  epistemicType: sanitizedClaim.epistemicType,
9357
9726
  provenance: sanitizedClaim.provenance,
9358
9727
  acquiredAt: sanitizedClaim.acquiredAt,
9728
+ ...sanitizedClaim.expiresAt === void 0 ? {} : { expiresAt: sanitizedClaim.expiresAt },
9729
+ ...sanitizedClaim.bootstrapPriority === void 0 ? {} : { bootstrapPriority: sanitizedClaim.bootstrapPriority },
9359
9730
  revision,
9360
9731
  scope,
9361
9732
  sourceProject,
9362
- kind
9733
+ kind,
9734
+ ...sanitizedClaim.check === void 0 ? {} : { check: sanitizedClaim.check }
9363
9735
  });
9364
9736
  await withStoreQueue(acquisitionStoreKey(kind, scope, sourceProject), async () => {
9365
9737
  const state2 = await target.runtime.select([]);
@@ -9607,7 +9979,14 @@ var init_incidents = __esm({
9607
9979
  }
9608
9980
  });
9609
9981
 
9610
- // core/knowledge/rules-loader.ts
9982
+ // core/knowledge/violations.ts
9983
+ var VIOLATION_FILE_NAME;
9984
+ var init_violations = __esm({
9985
+ "core/knowledge/violations.ts"() {
9986
+ init_user_paths();
9987
+ VIOLATION_FILE_NAME = "violations.json";
9988
+ }
9989
+ });
9611
9990
  function isRuleClaim(claim) {
9612
9991
  const knowledge = claim.knowledge;
9613
9992
  return knowledge?.kind === "rule";
@@ -9615,7 +9994,7 @@ function isRuleClaim(claim) {
9615
9994
  function isIronRule(claim) {
9616
9995
  return claim.epistemicType === "human-stated" && isRuleClaim(claim);
9617
9996
  }
9618
- function extractIronRules(state2) {
9997
+ function extractIronRules(state2, violations = {}) {
9619
9998
  const validated = validateKnowledgeState(state2);
9620
9999
  const claims = activeClaims(validated);
9621
10000
  const rules = [];
@@ -9632,7 +10011,7 @@ function extractIronRules(state2) {
9632
10011
  appliesWhen: String(knowledge.appliesWhen ?? knowledge.when ?? ""),
9633
10012
  violatedOn: Array.isArray(knowledge.violatedOn) ? knowledge.violatedOn : void 0,
9634
10013
  lastViolation: typeof knowledge.lastViolation === "string" ? knowledge.lastViolation : void 0,
9635
- frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : 0
10014
+ frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : violations[claim.id] ?? 0
9636
10015
  });
9637
10016
  }
9638
10017
  return rules;
@@ -9647,28 +10026,69 @@ function sortRulesByViolationFrequency(rules) {
9647
10026
  });
9648
10027
  }
9649
10028
  function loadIronRules(state2) {
9650
- const rules = sortRulesByViolationFrequency(extractIronRules(state2));
10029
+ const rules = sortRulesByViolationFrequency(
10030
+ extractIronRules(state2, readViolationCounts(`${resolveUserDotMemPath()}/${VIOLATION_FILE_NAME}`))
10031
+ );
9651
10032
  return {
9652
10033
  rules,
9653
10034
  count: rules.length,
9654
10035
  sortedBy: "violation-frequency"
9655
10036
  };
9656
10037
  }
10038
+ function formatRulesForSessionStart(rules) {
10039
+ if (rules.length === 0) {
10040
+ return "";
10041
+ }
10042
+ const lines = ["---", "IRON RULES (must always arrive)", "---"];
10043
+ for (const rule of rules) {
10044
+ lines.push(`${rule.id}: ${rule.text}`);
10045
+ }
10046
+ return lines.join("\n");
10047
+ }
10048
+ var readViolationCounts, ruleSetSignature, formatRulesReference;
9657
10049
  var init_rules_loader = __esm({
9658
10050
  "core/knowledge/rules-loader.ts"() {
9659
10051
  init_state();
10052
+ init_user_paths();
10053
+ init_violations();
9660
10054
  __name(isRuleClaim, "isRuleClaim");
9661
10055
  __name(isIronRule, "isIronRule");
9662
10056
  __name(extractIronRules, "extractIronRules");
10057
+ readViolationCounts = /* @__PURE__ */ __name((file) => {
10058
+ try {
10059
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
10060
+ const counts = {};
10061
+ for (const violation of Array.isArray(parsed.violations) ? parsed.violations : []) {
10062
+ const ruleId = typeof violation?.ruleId === "string" ? violation.ruleId : "";
10063
+ if (!ruleId) continue;
10064
+ counts[ruleId] = (counts[ruleId] ?? 0) + 1;
10065
+ }
10066
+ return counts;
10067
+ } catch {
10068
+ return {};
10069
+ }
10070
+ }, "readViolationCounts");
9663
10071
  __name(sortRulesByViolationFrequency, "sortRulesByViolationFrequency");
9664
10072
  __name(loadIronRules, "loadIronRules");
9665
- }
9666
- });
9667
-
9668
- // core/knowledge/violations.ts
9669
- var init_violations = __esm({
9670
- "core/knowledge/violations.ts"() {
9671
- init_user_paths();
10073
+ ruleSetSignature = /* @__PURE__ */ __name((rules) => {
10074
+ const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
10075
+ let hash = 2166136261;
10076
+ for (let index = 0; index < material.length; index += 1) {
10077
+ hash ^= material.charCodeAt(index);
10078
+ hash = Math.imul(hash, 16777619) >>> 0;
10079
+ }
10080
+ return hash.toString(16).padStart(8, "0");
10081
+ }, "ruleSetSignature");
10082
+ formatRulesReference = /* @__PURE__ */ __name((rules) => {
10083
+ if (rules.length === 0) return "DOTMEM_IRON_RULES_V1\ncount=0";
10084
+ return [
10085
+ "DOTMEM_IRON_RULES_V1",
10086
+ `count=${rules.length}`,
10087
+ `signature=${ruleSetSignature(rules)}`,
10088
+ `ids=${rules.map((rule) => rule.id).join(",")}`
10089
+ ].join("\n");
10090
+ }, "formatRulesReference");
10091
+ __name(formatRulesForSessionStart, "formatRulesForSessionStart");
9672
10092
  }
9673
10093
  });
9674
10094
 
@@ -10177,8 +10597,8 @@ function loadBuiltInContext() {
10177
10597
  for (const candidate of candidates) {
10178
10598
  if (!fs.existsSync(candidate)) continue;
10179
10599
  try {
10180
- const raw = fs.readFileSync(candidate, "utf8");
10181
- const parsed = JSON.parse(raw);
10600
+ const raw = fs.readFileSync(candidate);
10601
+ const parsed = JSON.parse(decodeText(raw, { source: candidate }));
10182
10602
  const artifact = validateArtifact(parsed);
10183
10603
  cached = artifact;
10184
10604
  cachedStatus = {
@@ -10235,6 +10655,7 @@ function assertBuiltInContextAvailable() {
10235
10655
  var BUILT_IN_CONTEXT_FORMAT, BUILT_IN_CONTEXT_FORMAT_VERSION, cached, cachedStatus, _artifactPathOverride;
10236
10656
  var init_built_in_context = __esm({
10237
10657
  "core/knowledge/built-in-context.ts"() {
10658
+ init_text_encoding();
10238
10659
  BUILT_IN_CONTEXT_FORMAT = "dotmem.built-in-context";
10239
10660
  BUILT_IN_CONTEXT_FORMAT_VERSION = 1;
10240
10661
  cached = null;
@@ -10294,6 +10715,7 @@ var init_knowledge = __esm({
10294
10715
  init_state();
10295
10716
  init_select();
10296
10717
  init_discover();
10718
+ init_currentness();
10297
10719
  init_project();
10298
10720
  init_applicability();
10299
10721
  init_policy();
@@ -10401,7 +10823,6 @@ function _inferConfidence(claim) {
10401
10823
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, LogicEngine, logic, logic_default;
10402
10824
  var init_logic = __esm({
10403
10825
  "core/logic/index.ts"() {
10404
- init_suppress_idb_warning();
10405
10826
  init_knowledge();
10406
10827
  init_mem_repository();
10407
10828
  init_acquisition_boundary();
@@ -10680,15 +11101,15 @@ __export(note_types_exports, {
10680
11101
  sha256HexOfText: () => sha256HexOfText
10681
11102
  });
10682
11103
  async function sha256HexOfText(text) {
10683
- const encoder3 = new TextEncoder();
10684
- const bytes = encoder3.encode(text);
11104
+ const encoder4 = new TextEncoder();
11105
+ const bytes = encoder4.encode(text);
10685
11106
  const hashArray = await crypto.subtle.digest("SHA-256", bytes);
10686
11107
  return Array.from(new Uint8Array(hashArray)).map((b) => b.toString(16).padStart(2, "0")).join("");
10687
11108
  }
10688
11109
  async function buildNoteKnowledge(title, content, origin, tag) {
10689
11110
  const sha2563 = await sha256HexOfText(content);
10690
- const encoder3 = new TextEncoder();
10691
- const size = encoder3.encode(content).byteLength;
11111
+ const encoder4 = new TextEncoder();
11112
+ const size = encoder4.encode(content).byteLength;
10692
11113
  return {
10693
11114
  title,
10694
11115
  content,
@@ -10765,18 +11186,11 @@ var init_note_types = __esm({
10765
11186
  }
10766
11187
  });
10767
11188
 
10768
- // core/mcp/index.ts
10769
- init_suppress_idb_warning();
10770
-
10771
11189
  // package.json
10772
11190
  var package_default = {
10773
- version: "0.1.7"};
10774
-
10775
- // core/memory/index.ts
10776
- init_suppress_idb_warning();
11191
+ version: "0.1.8"};
10777
11192
 
10778
11193
  // core/memory/journal.ts
10779
- init_suppress_idb_warning();
10780
11194
  init_env();
10781
11195
  var g = globalThis;
10782
11196
  function namespace() {
@@ -10983,7 +11397,6 @@ var journal_default = journal;
10983
11397
  init_brain();
10984
11398
 
10985
11399
  // core/memory/knowledge-runtime.ts
10986
- init_suppress_idb_warning();
10987
11400
  init_knowledge();
10988
11401
  init_project_identity();
10989
11402
  init_user_paths();
@@ -11374,12 +11787,12 @@ var policy = {
11374
11787
  };
11375
11788
 
11376
11789
  // core/memory/entries.ts
11377
- init_suppress_idb_warning();
11378
11790
  init_env();
11379
11791
 
11380
11792
  // core/memory/durable-store.ts
11381
11793
  init_storage_coordinator();
11382
11794
  init_store_queue();
11795
+ init_text_encoding();
11383
11796
  var DurableStorageUnavailableError = class extends Error {
11384
11797
  static {
11385
11798
  __name(this, "DurableStorageUnavailableError");
@@ -11434,11 +11847,11 @@ var DurableMemoryStore = class {
11434
11847
  }
11435
11848
  let parsed;
11436
11849
  try {
11437
- parsed = JSON.parse(new TextDecoder().decode(raw));
11850
+ parsed = JSON.parse(decodeText(raw, { source: this.filePath }));
11438
11851
  } catch {
11439
11852
  try {
11440
11853
  const bakRaw = await fs2.readFile(`${this.filePath}.bak`);
11441
- parsed = JSON.parse(new TextDecoder().decode(bakRaw));
11854
+ parsed = JSON.parse(decodeText(bakRaw, { source: `${this.filePath}.bak` }));
11442
11855
  } catch {
11443
11856
  throw new DurableStorageUnavailableError(
11444
11857
  "Durable memory store is corrupt and no backup is available."
@@ -12246,7 +12659,6 @@ var context = {
12246
12659
  };
12247
12660
 
12248
12661
  // core/memory/acquire.ts
12249
- init_suppress_idb_warning();
12250
12662
  init_env();
12251
12663
  init_built_in_context();
12252
12664
  init_project_identity();
@@ -13520,7 +13932,7 @@ var memory = {
13520
13932
  resetPolicyStoreCache();
13521
13933
  },
13522
13934
  // ----- namespaced surfaces -----
13523
- /** Local operation journal (namespaced). No-op substrate when sqlite/idb unavailable. */
13935
+ /** Local operation journal (namespaced). Persisted on `store`. */
13524
13936
  journal: journal_default,
13525
13937
  /** Configure the optional cloud-sync layer (namespace + provider). Chainable. */
13526
13938
  configure(opts) {
@@ -13656,6 +14068,7 @@ init_profile();
13656
14068
  init_acquisition_limits();
13657
14069
  init_mem_package();
13658
14070
  init_built_in_context();
14071
+ init_project();
13659
14072
  init_policy();
13660
14073
  init_context_constants();
13661
14074
 
@@ -15728,12 +16141,23 @@ var toolError = /* @__PURE__ */ __name((error) => {
15728
16141
  const code = stableErrorCode(error);
15729
16142
  return code ? codedErrorResult(code, isRetryable(error)) : errorResult2(sanitizeMcpError(error));
15730
16143
  }, "toolError");
15731
- async function dotmemContext(situation, dotmem = memory) {
16144
+ async function dotmemContext(situation, dotmem = memory, options = {}) {
16145
+ if (options.claimId) {
16146
+ const state2 = await loadCombinedKnowledgeState();
16147
+ const claim = state2.claims.find((candidate) => candidate.id === options.claimId);
16148
+ if (!claim) {
16149
+ return errorResult2(`No claim with id ${options.claimId} is present in the loaded stores.`);
16150
+ }
16151
+ const text = renderExpandedClaim(claim);
16152
+ return { content: [{ type: "text", text }], structuredContent: { text, claim } };
16153
+ }
15732
16154
  if (typeof situation !== "string") {
15733
16155
  return errorResult2("dotmem context requires a string situation.");
15734
16156
  }
15735
16157
  try {
15736
- const discovery = await dotmem.discover(situation);
16158
+ const discovery = await dotmem.discover(situation, {
16159
+ ...options.cursor ? { cursor: options.cursor } : {}
16160
+ });
15737
16161
  const projection = dotmem.project(
15738
16162
  discovery,
15739
16163
  {
@@ -15906,13 +16330,13 @@ async function dotmemNoteWrite(input) {
15906
16330
  }
15907
16331
  }
15908
16332
  __name(dotmemNoteWrite, "dotmemNoteWrite");
15909
- async function dotmemRules(loadRules) {
16333
+ async function dotmemRules(loadRules, options = {}) {
15910
16334
  try {
15911
16335
  const rules = await loadRules();
15912
- const text = rules.length === 0 ? "No iron rules found." : rules.map((rule) => `[${rule.id}] ${rule.text}`).join("\n");
16336
+ const text = options.expand ? rules.length === 0 ? "No iron rules found." : formatRulesForSessionStart(rules) : formatRulesReference(rules);
15913
16337
  return {
15914
16338
  content: [{ type: "text", text }],
15915
- structuredContent: { count: rules.length, rules }
16339
+ structuredContent: { count: rules.length, signature: ruleSetSignature(rules), rules }
15916
16340
  };
15917
16341
  } catch (error) {
15918
16342
  return toolError(error);
@@ -15948,7 +16372,7 @@ var buildMcpInstructions = /* @__PURE__ */ __name((options) => {
15948
16372
  const signal = buildInstructions(options);
15949
16373
  return [profileGuidance, signal].join("\n\n");
15950
16374
  }, "buildMcpInstructions");
15951
- function createDotMemMcpServer(dotmem = memory, loadRules = defaultLoadRules, hasExperience = false, language2) {
16375
+ function createDotMemMcpServer(dotmem = memory, loadRules = defaultLoadRules, hasExperience = false, language2, orchestrationCoordinator) {
15952
16376
  assertBuiltInContextAvailable();
15953
16377
  const writeEnabled = mcpWriteEnabled();
15954
16378
  const server = new McpServer(
@@ -15968,10 +16392,15 @@ function createDotMemMcpServer(dotmem = memory, loadRules = defaultLoadRules, ha
15968
16392
  situation: z.string().trim().max(
15969
16393
  DOTMEM_CONTEXT_MAX_SITUATION_LENGTH,
15970
16394
  "situation exceeds maximum length"
15971
- ).optional()
16395
+ ).optional(),
16396
+ claimId: z.string().trim().min(1).optional(),
16397
+ cursor: z.object({
16398
+ offset: z.number().int().nonnegative(),
16399
+ knowledgeVersion: z.number().int().nonnegative()
16400
+ }).optional()
15972
16401
  })
15973
16402
  },
15974
- ({ situation }) => dotmemContext(situation ?? "", dotmem)
16403
+ ({ situation, claimId, cursor }) => dotmemContext(situation ?? "", dotmem, { claimId, ...cursor ? { cursor } : {} })
15975
16404
  );
15976
16405
  if (mcpWriteEnabled()) {
15977
16406
  server.registerTool(
@@ -15987,9 +16416,9 @@ function createDotMemMcpServer(dotmem = memory, loadRules = defaultLoadRules, ha
15987
16416
  DOTMEM_RULES_TOOL_NAME,
15988
16417
  {
15989
16418
  description: DOTMEM_RULES_TOOL_DESCRIPTION,
15990
- inputSchema: z.object({})
16419
+ inputSchema: z.object({ expand: z.boolean().optional() })
15991
16420
  },
15992
- () => dotmemRules(loadRules)
16421
+ ({ expand }) => dotmemRules(loadRules, { expand })
15993
16422
  );
15994
16423
  server.registerTool(
15995
16424
  DOTMEM_NOTE_READ_TOOL_NAME,
@@ -16065,6 +16494,179 @@ function createDotMemMcpServer(dotmem = memory, loadRules = defaultLoadRules, ha
16065
16494
  return dotmemContinuity(input, { orchestrator });
16066
16495
  }
16067
16496
  );
16497
+ if (orchestrationCoordinator) {
16498
+ server.registerTool(
16499
+ "dotmem_orchestrate_discover",
16500
+ {
16501
+ description: "Discover agents from all configured provider adapters and return their capabilities and eligibility.",
16502
+ inputSchema: {
16503
+ runId: z.string().trim().min(1).optional()
16504
+ }
16505
+ },
16506
+ async (args) => {
16507
+ const runId = args.runId;
16508
+ const id = runId || `orchestrate-${Date.now()}`;
16509
+ try {
16510
+ const result = await orchestrationCoordinator.discoverAndSnapshot(id, "User-requested discovery");
16511
+ return {
16512
+ content: [{ type: "text", text: JSON.stringify({
16513
+ ok: true,
16514
+ runId: id,
16515
+ agentsDiscovered: result.run.discoverySnapshot.length,
16516
+ agentsEligible: result.eligibleAgents.length,
16517
+ agents: result.eligibleAgents.map((a) => ({
16518
+ compositeId: a.compositeId,
16519
+ providerId: a.providerId,
16520
+ agentId: a.agentId,
16521
+ displayName: a.displayName,
16522
+ capabilities: a.capabilities,
16523
+ authorizationStatus: a.authorizationStatus
16524
+ })),
16525
+ exceptions: result.exceptions.map((e) => ({ category: e.category, reason: e.reason, agentCompositeId: e.agentCompositeId }))
16526
+ }) }]
16527
+ };
16528
+ } catch (err2) {
16529
+ return errorResult2(`Discovery failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
16530
+ }
16531
+ }
16532
+ );
16533
+ server.registerTool(
16534
+ "dotmem_orchestrate_inspect",
16535
+ {
16536
+ description: "Inspect an orchestration run: its task graph, assignments, states, and exceptions.",
16537
+ inputSchema: {
16538
+ runId: z.string().trim().min(1)
16539
+ }
16540
+ },
16541
+ async (args) => {
16542
+ const runId = args.runId;
16543
+ try {
16544
+ const run = await orchestrationCoordinator.getRunStatus(runId);
16545
+ if (!run) return errorResult2(`Run not found: ${runId}`);
16546
+ const tasks = await orchestrationCoordinator.listTasksForRun(runId);
16547
+ const assignments = await orchestrationCoordinator.listAssignmentsForRun(runId);
16548
+ return {
16549
+ content: [{ type: "text", text: JSON.stringify({
16550
+ ok: true,
16551
+ runId,
16552
+ status: run.status,
16553
+ userObjective: run.userObjective,
16554
+ createdAt: run.createdAt,
16555
+ updatedAt: run.updatedAt,
16556
+ tasks: tasks.map((t) => ({
16557
+ taskId: t.taskId,
16558
+ objective: t.objective,
16559
+ state: t.state,
16560
+ assignedAgent: t.assignedAgentCompositeId,
16561
+ accepted: t.accepted
16562
+ })),
16563
+ assignments: assignments.map((a) => ({
16564
+ assignmentId: a.assignmentId,
16565
+ taskId: a.taskId,
16566
+ agentCompositeId: a.agentCompositeId,
16567
+ state: a.state,
16568
+ accepted: a.accepted
16569
+ })),
16570
+ exceptions: run.exceptions.map((e) => ({
16571
+ exceptionId: e.exceptionId,
16572
+ category: e.category,
16573
+ agentCompositeId: e.agentCompositeId,
16574
+ reason: e.reason,
16575
+ resolved: e.resolved
16576
+ }))
16577
+ }) }]
16578
+ };
16579
+ } catch (err2) {
16580
+ return errorResult2(`Inspect failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
16581
+ }
16582
+ }
16583
+ );
16584
+ server.registerTool(
16585
+ "dotmem_orchestrate_report",
16586
+ {
16587
+ description: "Retrieve the final orchestration run report with participation, outcomes, and risks.",
16588
+ inputSchema: {
16589
+ runId: z.string().trim().min(1),
16590
+ userApprovalGranted: z.boolean().optional()
16591
+ }
16592
+ },
16593
+ async (args) => {
16594
+ const runId = args.runId;
16595
+ const userApprovalGranted = args.userApprovalGranted;
16596
+ try {
16597
+ const run = await orchestrationCoordinator.getRunStatus(runId);
16598
+ if (!run) return errorResult2(`Run not found: ${runId}`);
16599
+ const { report } = await orchestrationCoordinator.finalizeRun(runId, !!userApprovalGranted);
16600
+ return {
16601
+ content: [{ type: "text", text: JSON.stringify({ ok: true, report }) }]
16602
+ };
16603
+ } catch (err2) {
16604
+ return errorResult2(`Report failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
16605
+ }
16606
+ }
16607
+ );
16608
+ server.registerTool(
16609
+ "dotmem_orchestrate_start",
16610
+ {
16611
+ description: "Start a new orchestration run from a user objective. Discovers agents, decomposes the objective, and creates distinct assignments.",
16612
+ inputSchema: {
16613
+ objective: z.string().trim().min(1, "objective is required"),
16614
+ scope: z.string().trim().optional(),
16615
+ constraints: z.record(z.string(), z.any()).optional(),
16616
+ correlationKey: z.string().trim().optional()
16617
+ }
16618
+ },
16619
+ async (args) => {
16620
+ const objective = args.objective;
16621
+ const scope = args.scope;
16622
+ args.constraints;
16623
+ const correlationKey = args.correlationKey;
16624
+ const runId = correlationKey || `orchestrate-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
16625
+ try {
16626
+ const discoverResult = await orchestrationCoordinator.discoverAndSnapshot(
16627
+ runId,
16628
+ objective,
16629
+ scope
16630
+ );
16631
+ const decomposeResult = await orchestrationCoordinator.decomposeAndAssign(
16632
+ runId,
16633
+ objective,
16634
+ scope,
16635
+ discoverResult.eligibleAgents
16636
+ );
16637
+ return {
16638
+ content: [{ type: "text", text: JSON.stringify({
16639
+ ok: true,
16640
+ runId,
16641
+ status: "assigned",
16642
+ agentsDiscovered: discoverResult.run.discoverySnapshot.length,
16643
+ agentsEligible: discoverResult.eligibleAgents.length,
16644
+ assignments: decomposeResult.assignments.map((a) => ({
16645
+ taskId: a.task.taskId,
16646
+ agentCompositeId: a.agent.compositeId,
16647
+ providerId: a.agent.providerId,
16648
+ agentId: a.agent.agentId,
16649
+ displayName: a.agent.displayName,
16650
+ taskObjective: a.task.objective,
16651
+ acceptanceCriteria: a.task.acceptanceCriteria.map((c) => c.description),
16652
+ state: a.task.state
16653
+ })),
16654
+ exceptions: [...discoverResult.exceptions, ...decomposeResult.exceptions].map((e) => ({
16655
+ exceptionId: e.exceptionId,
16656
+ category: e.category,
16657
+ reason: e.reason,
16658
+ agentCompositeId: e.agentCompositeId,
16659
+ providerId: e.providerId,
16660
+ taskId: e.taskId
16661
+ }))
16662
+ }) }]
16663
+ };
16664
+ } catch (err2) {
16665
+ return errorResult2(`Start failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
16666
+ }
16667
+ }
16668
+ );
16669
+ }
16068
16670
  return server;
16069
16671
  }
16070
16672
  __name(createDotMemMcpServer, "createDotMemMcpServer");