@agentshouse/mdruntime 0.1.0-alpha.8 → 0.1.0-c009335e08279

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.
Files changed (121) hide show
  1. package/AGENTS.md +208 -0
  2. package/README.md +44 -0
  3. package/dist/adapter.d.ts +215 -25
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/adapter.js +2 -3
  6. package/dist/attachment.d.ts +3 -0
  7. package/dist/attachment.d.ts.map +1 -0
  8. package/dist/attachment.js +8 -0
  9. package/dist/bootstrap.d.ts +6 -7
  10. package/dist/bootstrap.d.ts.map +1 -1
  11. package/dist/bootstrap.js +31 -28
  12. package/dist/change-set.d.ts +33 -0
  13. package/dist/change-set.d.ts.map +1 -0
  14. package/dist/change-set.js +83 -0
  15. package/dist/change.d.ts +9 -0
  16. package/dist/change.d.ts.map +1 -1
  17. package/dist/change.js +6 -5
  18. package/dist/client.d.ts +69 -0
  19. package/dist/client.d.ts.map +1 -0
  20. package/dist/client.js +165 -0
  21. package/dist/collection.d.ts +22 -15
  22. package/dist/collection.d.ts.map +1 -1
  23. package/dist/collection.js +60 -78
  24. package/dist/connection.d.ts +68 -40
  25. package/dist/connection.d.ts.map +1 -1
  26. package/dist/connection.js +1597 -961
  27. package/dist/conversation.d.ts +79 -0
  28. package/dist/conversation.d.ts.map +1 -0
  29. package/dist/conversation.js +557 -0
  30. package/dist/durability.d.ts +8 -3
  31. package/dist/durability.d.ts.map +1 -1
  32. package/dist/durability.js +7 -61
  33. package/dist/file.d.ts +20 -0
  34. package/dist/file.d.ts.map +1 -0
  35. package/dist/file.js +126 -0
  36. package/dist/host.d.ts +13 -0
  37. package/dist/host.d.ts.map +1 -0
  38. package/dist/host.js +175 -0
  39. package/dist/identity.d.ts +1 -0
  40. package/dist/identity.d.ts.map +1 -1
  41. package/dist/identity.js +10 -9
  42. package/dist/index.d.ts +14 -10
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +1 -3
  45. package/dist/log.js +5 -6
  46. package/dist/memory.d.ts +17 -2
  47. package/dist/memory.d.ts.map +1 -1
  48. package/dist/memory.js +268 -113
  49. package/dist/model.d.ts +10 -25
  50. package/dist/model.d.ts.map +1 -1
  51. package/dist/model.js +18 -21
  52. package/dist/observation.d.ts +25 -0
  53. package/dist/observation.d.ts.map +1 -0
  54. package/dist/observation.js +85 -0
  55. package/dist/outcome.d.ts +12 -24
  56. package/dist/outcome.d.ts.map +1 -1
  57. package/dist/outcome.js +1 -13
  58. package/dist/overlay.d.ts +9 -2
  59. package/dist/overlay.d.ts.map +1 -1
  60. package/dist/overlay.js +187 -43
  61. package/dist/paths.d.ts +0 -1
  62. package/dist/paths.d.ts.map +1 -1
  63. package/dist/paths.js +12 -19
  64. package/dist/query.d.ts +210 -9
  65. package/dist/query.d.ts.map +1 -1
  66. package/dist/query.js +420 -15
  67. package/dist/read-side.d.ts +14 -0
  68. package/dist/read-side.d.ts.map +1 -0
  69. package/dist/read-side.js +371 -0
  70. package/dist/refresh.d.ts +4 -5
  71. package/dist/refresh.d.ts.map +1 -1
  72. package/dist/refresh.js +45 -30
  73. package/dist/replica.d.ts +27 -6
  74. package/dist/replica.d.ts.map +1 -1
  75. package/dist/replica.js +233 -30
  76. package/dist/room-draft.d.ts +124 -0
  77. package/dist/room-draft.d.ts.map +1 -0
  78. package/dist/room-draft.js +327 -0
  79. package/dist/rows.d.ts +41 -0
  80. package/dist/rows.d.ts.map +1 -0
  81. package/dist/rows.js +100 -0
  82. package/dist/save.d.ts +10 -6
  83. package/dist/save.d.ts.map +1 -1
  84. package/dist/save.js +266 -333
  85. package/dist/search.d.ts +61 -0
  86. package/dist/search.d.ts.map +1 -0
  87. package/dist/search.js +125 -0
  88. package/dist/status.d.ts +9 -2
  89. package/dist/status.d.ts.map +1 -1
  90. package/dist/status.js +11 -14
  91. package/dist/store.d.ts +75 -18
  92. package/dist/store.d.ts.map +1 -1
  93. package/dist/store.js +358 -97
  94. package/dist/transfer.d.ts +5 -0
  95. package/dist/transfer.d.ts.map +1 -1
  96. package/dist/transfer.js +1 -5
  97. package/dist/wire.d.ts +64 -0
  98. package/dist/wire.d.ts.map +1 -0
  99. package/dist/wire.js +118 -0
  100. package/package.json +15 -13
  101. package/dist/adapter.js.map +0 -1
  102. package/dist/bootstrap.js.map +0 -1
  103. package/dist/change.js.map +0 -1
  104. package/dist/collection.js.map +0 -1
  105. package/dist/connection.js.map +0 -1
  106. package/dist/durability.js.map +0 -1
  107. package/dist/identity.js.map +0 -1
  108. package/dist/index.js.map +0 -1
  109. package/dist/log.js.map +0 -1
  110. package/dist/memory.js.map +0 -1
  111. package/dist/model.js.map +0 -1
  112. package/dist/outcome.js.map +0 -1
  113. package/dist/overlay.js.map +0 -1
  114. package/dist/paths.js.map +0 -1
  115. package/dist/query.js.map +0 -1
  116. package/dist/refresh.js.map +0 -1
  117. package/dist/replica.js.map +0 -1
  118. package/dist/save.js.map +0 -1
  119. package/dist/status.js.map +0 -1
  120. package/dist/store.js.map +0 -1
  121. package/dist/transfer.js.map +0 -1
package/dist/wire.js ADDED
@@ -0,0 +1,118 @@
1
+ export const RUNTIME_WIRE_PROTOCOL = 8;
2
+ export const PROTOCOL_MISMATCH = {
3
+ reason: 'client-host-protocol-mismatch',
4
+ reauthorizationOffered: false,
5
+ refusal: null,
6
+ };
7
+ const MEMBERS = [
8
+ 'rooms',
9
+ 'query',
10
+ 'search',
11
+ 'types',
12
+ 'save',
13
+ 'history',
14
+ 'call',
15
+ 'reached',
16
+ 'log',
17
+ 'persistence',
18
+ 'reauthorize',
19
+ 'roomDraft.list',
20
+ 'roomDraft.read',
21
+ 'roomDraft.write',
22
+ 'roomDraft.discard',
23
+ 'presentation.read',
24
+ 'presentation.write',
25
+ 'conversation.list',
26
+ 'conversation.read',
27
+ 'conversation.create',
28
+ 'conversation.send',
29
+ 'conversation.answer',
30
+ 'conversation.interrupt',
31
+ 'conversation.kill',
32
+ 'conversation.cancel',
33
+ 'conversation.delete',
34
+ 'chatDraft.write',
35
+ 'chatDraft.discard',
36
+ ];
37
+ const TOPICS = [
38
+ 'rooms',
39
+ 'connection-refusal',
40
+ 'storage-loss',
41
+ 'deployment-facts',
42
+ 'sync-status',
43
+ 'service-mode',
44
+ 'query',
45
+ 'queue',
46
+ 'room-drafts',
47
+ 'presentation',
48
+ 'conversation',
49
+ ];
50
+ export const AUTHORIZATION_ENDED = 'the host authorization ended';
51
+ export const PORT_CLOSED = 'the port closed';
52
+ export function envelope(message) {
53
+ return { mdRuntime: RUNTIME_WIRE_PROTOCOL, message };
54
+ }
55
+ export function carried(data) {
56
+ if (typeof data !== 'object' || data === null || !('mdRuntime' in data))
57
+ return null;
58
+ const record = data;
59
+ return { matching: record.mdRuntime === RUNTIME_WIRE_PROTOCOL, message: record.message };
60
+ }
61
+ function body(message) {
62
+ if (typeof message !== 'object' || message === null)
63
+ return null;
64
+ const record = message;
65
+ return { kind: record.kind, id: record.id };
66
+ }
67
+ export function request(message) {
68
+ const shape = body(message);
69
+ if (shape === null)
70
+ return null;
71
+ if (shape.kind === 'hello')
72
+ return { kind: 'hello' };
73
+ if (typeof shape.id !== 'number')
74
+ return null;
75
+ const record = message;
76
+ if (shape.kind === 'stop')
77
+ return { kind: 'stop', id: shape.id };
78
+ if (!Array.isArray(record.input))
79
+ return null;
80
+ if (shape.kind === 'call' && MEMBERS.includes(record.member)) {
81
+ return {
82
+ kind: 'call',
83
+ id: shape.id,
84
+ member: record.member,
85
+ input: record.input,
86
+ };
87
+ }
88
+ if (shape.kind === 'observe' && TOPICS.includes(record.topic)) {
89
+ return {
90
+ kind: 'observe',
91
+ id: shape.id,
92
+ topic: record.topic,
93
+ input: record.input,
94
+ };
95
+ }
96
+ return null;
97
+ }
98
+ export function answer(message) {
99
+ const shape = body(message);
100
+ if (shape === null)
101
+ return null;
102
+ const record = message;
103
+ if (shape.kind === 'refusal') {
104
+ return { kind: 'refusal', refusal: record.refusal };
105
+ }
106
+ if (shape.kind === 'ended')
107
+ return { kind: 'ended' };
108
+ if (typeof shape.id !== 'number')
109
+ return null;
110
+ if (shape.kind === 'result')
111
+ return { kind: 'result', id: shape.id, value: record.value };
112
+ if (shape.kind === 'event')
113
+ return { kind: 'event', id: shape.id, value: record.value };
114
+ if (shape.kind === 'failure' && typeof record.message === 'string') {
115
+ return { kind: 'failure', id: shape.id, message: record.message };
116
+ }
117
+ return null;
118
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentshouse/mdruntime",
3
- "version": "0.1.0-alpha.8",
3
+ "version": "0.1.0-c009335e08279",
4
4
  "description": "The headless core of MD App",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -9,13 +9,21 @@
9
9
  "access": "public"
10
10
  },
11
11
  "engines": {
12
- "node": ">=24.20.0"
12
+ "node": ">=24.21.0"
13
13
  },
14
14
  "exports": {
15
15
  ".": {
16
16
  "types": "./dist/index.d.ts",
17
17
  "import": "./dist/index.js"
18
18
  },
19
+ "./host": {
20
+ "types": "./dist/host.d.ts",
21
+ "import": "./dist/host.js"
22
+ },
23
+ "./client": {
24
+ "types": "./dist/client.d.ts",
25
+ "import": "./dist/client.js"
26
+ },
19
27
  "./memory": {
20
28
  "types": "./dist/memory.d.ts",
21
29
  "import": "./dist/memory.js"
@@ -24,19 +32,13 @@
24
32
  },
25
33
  "files": [
26
34
  "dist",
35
+ "AGENTS.md",
36
+ "README.md",
27
37
  "LICENSE"
28
38
  ],
29
- "repository": {
30
- "type": "git",
31
- "url": "git+https://github.com/agentshouse/mdruntime.git",
32
- "directory": "packages/mdruntime"
33
- },
34
- "homepage": "https://github.com/agentshouse/mdruntime#readme",
35
- "bugs": {
36
- "url": "https://github.com/agentshouse/mdruntime/issues"
37
- },
38
39
  "dependencies": {
39
- "@agentshouse/mdmodel": "0.1.0-alpha.5",
40
- "@agentshouse/query": "0.1.0-alpha.3"
40
+ "@agentshouse/mdmodel": "0.1.0-ce804f6363a19",
41
+ "@tanstack/db": "0.9.2",
42
+ "minisearch": "7.2.0"
41
43
  }
42
44
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/adapter.ts"],"sourcesContent":["import type { ModelIdentity, ModelResult } from './model.js';\nimport type { ChangeBatch } from './change.js';\n\nexport type Authorization = object;\n\nexport const ROOM_CONTRACT_VERSION = 1;\n\nexport const VERSION_1_CAPABILITIES = [\n 'stable-file-ids',\n 'ranked-provider-search',\n 'room-version-notifications',\n 'room-history',\n 'provider-actions',\n] as const;\n\nexport type MdModelIdentity = {\n identity: string;\n version: string;\n};\n\nexport type OperationScopes = {\n read: readonly string[];\n sync: readonly string[];\n write: readonly string[];\n delete: readonly string[];\n};\nexport type ReplicaAdmission = { selection: string; admission: 'admitted' | 'unavailable' };\n\nexport type DiscoveredRoom = {\n collectionRoot: string;\n name: string;\n locator: string;\n roomVersion: string;\n operations: OperationScopes;\n replica: ReplicaAdmission;\n attachedModel: ModelIdentity | null;\n providerOwnedPaths: readonly string[];\n};\n\nexport type Capability = {\n name: string;\n limits?: readonly ProviderLimit[];\n actions?: readonly ActionDeclaration[];\n};\n\nexport type ActionDeclaration = {\n name: string;\n inputShape: unknown;\n resultKind: unknown;\n};\n\nexport type ProviderLimit = {\n name: string;\n value?: number | string;\n};\n\nexport type HistoryRetention =\n | { kind: 'duration'; seconds: number }\n | { kind: 'no-declared-time-bound' };\n\nexport type Retention = {\n history: HistoryRetention;\n outcome: number;\n refreshHorizon: number;\n};\n\nexport type Discovery = {\n kind: 'discovery';\n supportedVersions: readonly number[];\n mdModel: MdModelIdentity;\n rooms: readonly DiscoveredRoom[];\n capabilities: readonly Capability[];\n providerLimits: readonly ProviderLimit[];\n retention: Retention;\n origins: readonly string[];\n};\n\nexport type TransportUncertainty = { kind: 'transport-uncertainty' };\nexport type RoomNotReadable = { kind: 'room-not-readable'; locator: string };\nexport type RevokedAuthorization = { kind: 'revoked-authorization' };\n\nexport type ScopedRefusal = {\n kind: 'scoped-refusal';\n locator: string;\n scope: 'content' | 'sync' | 'model' | 'operation' | 'undisclosed';\n text: string;\n};\nexport type AdapterFailure =\n | TransportUncertainty\n | RoomNotReadable\n | RevokedAuthorization\n | ScopedRefusal;\n\nexport type DiscoverResult =\n | Discovery\n | TransportUncertainty\n | RevokedAuthorization\n | { kind: 'contract-unavailable'; text: string };\n\nexport type PageToken = string;\n\nexport type BootstrapRequest = {\n locator: string;\n selection: string;\n pageToken?: PageToken;\n};\n\nexport type BootstrapPage = {\n kind: 'bootstrap';\n roomVersion: string;\n documents: Readonly<Record<string, string>>;\n revisions: Readonly<Record<string, string>>;\n binaryTargets: readonly string[];\n pageToken?: PageToken;\n};\n\nexport type BootstrapResult = BootstrapPage | AdapterFailure;\n\nexport type RefreshRequest = {\n locator: string;\n selection: string;\n fromRoomVersion: string;\n pageToken?: PageToken;\n};\n\nexport type RefreshPage = {\n kind: 'net-advancement';\n roomVersion: string;\n documents: Readonly<Record<string, string>>;\n revisions: Readonly<Record<string, string>>;\n binaryTargets: readonly string[];\n removals: readonly string[];\n pageToken?: PageToken;\n};\n\nexport type RefreshResult =\n | { kind: 'still-current' }\n | RefreshPage\n | { kind: 'beyond-horizon' }\n | AdapterFailure;\n\nexport type MutationRequest = {\n locator: string;\n changeBatch: ChangeBatch;\n};\n\nexport type MutationResult =\n | {\n kind: 'accepted';\n roomVersion: string;\n documents: Readonly<Record<string, string>>;\n revisions: Readonly<Record<string, string>>;\n removals: readonly string[];\n author: string;\n time: string;\n }\n | {\n kind: 'conflicted';\n roomVersion: string;\n affected: Readonly<Record<string, string>>;\n text: string;\n }\n | {\n kind: 'rejected';\n affected: Readonly<Record<string, string>>;\n text: string;\n }\n | { kind: 'expired' }\n | AdapterFailure;\n\nexport type HistoryRevision = {\n revision: string;\n author: string;\n time: string;\n};\n\nexport type HistoryRequest = {\n locator: string;\n path: string;\n revision?: string;\n pageToken?: PageToken;\n};\n\nexport type HistoryResult =\n | {\n kind: 'history';\n revisions: readonly HistoryRevision[];\n pageToken?: PageToken;\n }\n | {\n kind: 'revision';\n content: string;\n }\n | { kind: 'no-history' }\n | AdapterFailure;\n\nexport type ActionRequest = {\n name: string;\n input: unknown;\n};\n\nexport type ActionResult =\n | { kind: 'action'; result: unknown }\n | { kind: 'rejected'; text: string }\n | AdapterFailure;\n\nexport type Adapter = {\n model(\n authorization: Authorization,\n request: { locator: string; collectionRoot: string; model: ModelIdentity | null },\n ): Promise<ModelResult>;\n authorize(): Promise<Authorization>;\n discover(authorization: Authorization): Promise<DiscoverResult>;\n bootstrap(authorization: Authorization, request: BootstrapRequest): Promise<BootstrapResult>;\n refresh(authorization: Authorization, request: RefreshRequest): Promise<RefreshResult>;\n mutate(authorization: Authorization, request: MutationRequest): Promise<MutationResult>;\n history(authorization: Authorization, request: HistoryRequest): Promise<HistoryResult>;\n action(authorization: Authorization, request: ActionRequest): Promise<ActionResult>;\n};\n"],"names":["ROOM_CONTRACT_VERSION","VERSION_1_CAPABILITIES"],"mappings":"AAKA,OAAO,MAAMA,wBAAwB,EAAE;AAEvC,OAAO,MAAMC,yBAAyB;IACpC;IACA;IACA;IACA;IACA;CACD,CAAU"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/bootstrap.ts"],"sourcesContent":["import type { AttachedModelBinding } from './model.js';\nimport type { ModelState } from './model.js';\nimport type { Adapter, AdapterFailure, Authorization, DiscoveredRoom } from './adapter.js';\nimport { readStaged, type ConfirmedLayer } from './replica.js';\nimport { unconfirmed, type Unconfirmed } from './transfer.js';\n\nexport type BootstrapOutcome =\n | { kind: 'staged'; confirmed: ConfirmedLayer }\n | Unconfirmed\n | AdapterFailure;\n\nexport async function bootstrapRoom(\n adapter: Adapter,\n authorization: Authorization,\n room: DiscoveredRoom,\n model: ModelState,\n binding: AttachedModelBinding | null,\n): Promise<BootstrapOutcome> {\n const first = await adapter.bootstrap(authorization, {\n locator: room.locator,\n selection: room.replica.selection,\n });\n if (first.kind !== 'bootstrap') return first;\n const roomVersion = first.roomVersion;\n const documents: Record<string, string> = { ...first.documents };\n const revisions: Record<string, string> = { ...first.revisions };\n const binaryTargets = new Set(first.binaryTargets);\n let pageToken = first.pageToken;\n while (pageToken !== undefined) {\n const page = await adapter.bootstrap(authorization, {\n locator: room.locator,\n selection: room.replica.selection,\n pageToken,\n });\n if (page.kind !== 'bootstrap') return page;\n if (page.roomVersion !== roomVersion) return unconfirmed;\n Object.assign(documents, page.documents);\n Object.assign(revisions, page.revisions);\n for (const target of page.binaryTargets) binaryTargets.add(target);\n pageToken = page.pageToken;\n }\n const confirmed = readStaged(\n {\n locator: room.locator,\n collectionRoot: room.collectionRoot,\n name: room.name,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n model,\n providerOwnedPaths: room.providerOwnedPaths,\n roomVersion,\n documents,\n binaryTargets: [...binaryTargets].sort(),\n revisions,\n },\n binding,\n );\n return confirmed === null ? unconfirmed : { kind: 'staged', confirmed };\n}\n"],"names":["readStaged","unconfirmed","bootstrapRoom","adapter","authorization","room","model","binding","first","bootstrap","locator","selection","replica","kind","roomVersion","documents","revisions","binaryTargets","Set","pageToken","undefined","page","Object","assign","target","add","confirmed","collectionRoot","name","operations","attachedModel","providerOwnedPaths","sort"],"mappings":"AAGA,SAASA,UAAU,QAA6B,eAAe;AAC/D,SAASC,WAAW,QAA0B,gBAAgB;AAO9D,OAAO,eAAeC,cACpBC,OAAgB,EAChBC,aAA4B,EAC5BC,IAAoB,EACpBC,KAAiB,EACjBC,OAAoC;IAEpC,MAAMC,QAAQ,MAAML,QAAQM,SAAS,CAACL,eAAe;QACnDM,SAASL,KAAKK,OAAO;QACrBC,WAAWN,KAAKO,OAAO,CAACD,SAAS;IACnC;IACA,IAAIH,MAAMK,IAAI,KAAK,aAAa,OAAOL;IACvC,MAAMM,cAAcN,MAAMM,WAAW;IACrC,MAAMC,YAAoC;QAAE,GAAGP,MAAMO,SAAS;IAAC;IAC/D,MAAMC,YAAoC;QAAE,GAAGR,MAAMQ,SAAS;IAAC;IAC/D,MAAMC,gBAAgB,IAAIC,IAAIV,MAAMS,aAAa;IACjD,IAAIE,YAAYX,MAAMW,SAAS;IAC/B,MAAOA,cAAcC,UAAW;QAC9B,MAAMC,OAAO,MAAMlB,QAAQM,SAAS,CAACL,eAAe;YAClDM,SAASL,KAAKK,OAAO;YACrBC,WAAWN,KAAKO,OAAO,CAACD,SAAS;YACjCQ;QACF;QACA,IAAIE,KAAKR,IAAI,KAAK,aAAa,OAAOQ;QACtC,IAAIA,KAAKP,WAAW,KAAKA,aAAa,OAAOb;QAC7CqB,OAAOC,MAAM,CAACR,WAAWM,KAAKN,SAAS;QACvCO,OAAOC,MAAM,CAACP,WAAWK,KAAKL,SAAS;QACvC,KAAK,MAAMQ,UAAUH,KAAKJ,aAAa,CAAEA,cAAcQ,GAAG,CAACD;QAC3DL,YAAYE,KAAKF,SAAS;IAC5B;IACA,MAAMO,YAAY1B,WAChB;QACEU,SAASL,KAAKK,OAAO;QACrBiB,gBAAgBtB,KAAKsB,cAAc;QACnCC,MAAMvB,KAAKuB,IAAI;QACfC,YAAYxB,KAAKwB,UAAU;QAC3BjB,SAASP,KAAKO,OAAO;QACrBkB,eAAezB,KAAKyB,aAAa;QACjCxB;QACAyB,oBAAoB1B,KAAK0B,kBAAkB;QAC3CjB;QACAC;QACAE,eAAe;eAAIA;SAAc,CAACe,IAAI;QACtChB;IACF,GACAT;IAEF,OAAOmB,cAAc,OAAOzB,cAAc;QAAEY,MAAM;QAAUa;IAAU;AACxE"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/change.ts"],"sourcesContent":["export type Change =\n | {\n readonly kind: 'field';\n readonly path: string;\n readonly name: string;\n readonly value: unknown;\n }\n | {\n readonly kind: 'section';\n readonly path: string;\n readonly name: string;\n readonly value: string;\n }\n | { readonly kind: 'preamble'; readonly path: string; readonly value: string }\n | {\n readonly kind: 'create';\n readonly path: string;\n readonly fields: Readonly<Record<string, unknown>>;\n readonly sections: Readonly<Record<string, string>>;\n }\n | { readonly kind: 'replace'; readonly path: string; readonly content: string }\n | { readonly kind: 'move'; readonly path: string; readonly to: string }\n | { readonly kind: 'remove'; readonly path: string };\n\nexport type Precondition =\n | {\n readonly kind: 'field';\n readonly path: string;\n readonly name: string;\n readonly value: unknown;\n }\n | {\n readonly kind: 'section';\n readonly path: string;\n readonly name: string;\n readonly value: string;\n }\n | { readonly kind: 'preamble'; readonly path: string; readonly value: string }\n | { readonly kind: 'revision'; readonly path: string; readonly revision: string }\n | { readonly kind: 'present'; readonly path: string }\n | { readonly kind: 'absent'; readonly path: string };\n\nexport type ChangeBatch = {\n validation?: import('./model.js').ValidationReceipt;\n readonly id: string;\n readonly baseRoomVersion: string;\n readonly changes: readonly Change[];\n readonly preconditions: readonly Precondition[];\n};\n\nfunction frozen<T>(value: T): T {\n if (Array.isArray(value)) return Object.freeze(value.map((item) => frozen(item))) as T;\n if (value === null || typeof value !== 'object') return value;\n const copy: Record<string, unknown> = {};\n for (const [name, item] of Object.entries(value)) copy[name] = frozen(item);\n return Object.freeze(copy) as T;\n}\n\nexport function immutable(batch: ChangeBatch): ChangeBatch {\n return frozen(batch);\n}\n"],"names":["frozen","value","Array","isArray","Object","freeze","map","item","copy","name","entries","immutable","batch"],"mappings":"AAkDA,SAASA,OAAUC,KAAQ;IACzB,IAAIC,MAAMC,OAAO,CAACF,QAAQ,OAAOG,OAAOC,MAAM,CAACJ,MAAMK,GAAG,CAAC,CAACC,OAASP,OAAOO;IAC1E,IAAIN,UAAU,QAAQ,OAAOA,UAAU,UAAU,OAAOA;IACxD,MAAMO,OAAgC,CAAC;IACvC,KAAK,MAAM,CAACC,MAAMF,KAAK,IAAIH,OAAOM,OAAO,CAACT,OAAQO,IAAI,CAACC,KAAK,GAAGT,OAAOO;IACtE,OAAOH,OAAOC,MAAM,CAACG;AACvB;AAEA,OAAO,SAASG,UAAUC,KAAkB;IAC1C,OAAOZ,OAAOY;AAChB"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/collection.ts"],"sourcesContent":["import { parse, validate, VERSION, type Document, type Validation } from '@agentshouse/mdmodel';\nimport type { Selector } from '@agentshouse/query';\nimport { normalize } from './paths.js';\nimport type { AttachedModelBinding, ModelState } from './model.js';\nimport type { MdModelIdentity } from './adapter.js';\n\nexport const MD_MODEL: MdModelIdentity = { identity: '@agentshouse/mdmodel', version: VERSION };\n\nexport const PRESENTED: Selector = { path: { $regex: '\\\\.md$' } };\n\nexport type MdType = {\n name: string;\n path: string;\n fields: Readonly<Record<string, unknown>>;\n sections: Readonly<Record<string, unknown>>;\n};\n\nexport type Collection = {\n documents: Readonly<Record<string, Document>>;\n types: readonly MdType[];\n};\n\nexport function parseCollection(\n text: Readonly<Record<string, string>>,\n model: ModelState,\n): Collection {\n const documents: Record<string, Document> = {};\n for (const path of Object.keys(text).sort()) {\n const parsed = parse(text[path], path);\n if (parsed.ok) documents[path] = parsed.document;\n }\n return { documents, types: model.status === 'unavailable' ? [] : model.types };\n}\n\nexport function readCollection(\n text: Readonly<Record<string, string>>,\n collectionRoot: string,\n model: ModelState,\n): Collection | null {\n if (!validRoot(collectionRoot)) return null;\n const collection = parseCollection(text, model);\n if (Object.keys(collection.documents).length !== Object.keys(text).length) return null;\n if (\n Object.entries(collection.documents).some(\n ([path, document]) =>\n !member(path, collectionRoot) && document.type !== undefined && document.type !== 'any',\n )\n )\n return null;\n return collection;\n}\n\nexport function validRoot(root: unknown): root is string {\n return typeof root === 'string' && normalize(root) === root;\n}\n\nfunction member(path: string, root: string): boolean {\n return root === '' || path.startsWith(`${root}/`);\n}\n\nexport function validateCollection(\n text: Readonly<Record<string, string>>,\n binaryTargets: readonly string[],\n collectionRoot: string,\n model: ModelState,\n binding: AttachedModelBinding | null,\n): Validation & { source?: 'content' | 'model' } {\n const prefix = collectionRoot === '' ? '' : `${collectionRoot}/`;\n const collection: Record<string, string> = {};\n for (const [path, content] of Object.entries(text)) {\n if (member(path, collectionRoot)) {\n collection[path.slice(prefix.length)] = content;\n continue;\n }\n const parsed = parse(content, path);\n if (!parsed.ok) return { verdict: 'refuse', ...parsed.refusal };\n if (Object.hasOwn(parsed.document.fields, 'type') && parsed.document.fields.type !== 'any') {\n return { verdict: 'refuse', rule: 'outside-collection-type', file: path, version: VERSION };\n }\n }\n const targets = binaryTargets\n .filter((path) => member(path, collectionRoot))\n .map((path) => path.slice(prefix.length));\n if (model.status === 'unavailable' || binding === null) {\n const typed = Object.entries(collection).find(([, content]) => {\n const parsed = parse(content);\n return parsed.ok && parsed.document.type !== undefined && parsed.document.type !== 'any';\n });\n if (typed !== undefined)\n return {\n verdict: 'refuse',\n rule: 'model-unavailable',\n file: `${prefix}${typed[0]}`,\n version: VERSION,\n };\n return validate(collection, { binaryTargets: targets });\n }\n const verdict = binding.validate({\n model: model.snapshot,\n documents: collection,\n binaryTargets: targets,\n });\n if (verdict.verdict === 'refuse' && verdict.source === 'model') return verdict;\n if (verdict.verdict === 'accept') return verdict;\n return {\n ...verdict,\n file: `${prefix}${verdict.file}`,\n ...(verdict.referrers === undefined\n ? {}\n : { referrers: verdict.referrers.map((path) => `${prefix}${path}`) }),\n };\n}\n"],"names":["parse","validate","VERSION","normalize","MD_MODEL","identity","version","PRESENTED","path","$regex","parseCollection","text","model","documents","Object","keys","sort","parsed","ok","document","types","status","readCollection","collectionRoot","validRoot","collection","length","entries","some","member","type","undefined","root","startsWith","validateCollection","binaryTargets","binding","prefix","content","slice","verdict","refusal","hasOwn","fields","rule","file","targets","filter","map","typed","find","snapshot","source","referrers"],"mappings":"AAAA,SAASA,KAAK,EAAEC,QAAQ,EAAEC,OAAO,QAAwC,uBAAuB;AAEhG,SAASC,SAAS,QAAQ,aAAa;AAIvC,OAAO,MAAMC,WAA4B;IAAEC,UAAU;IAAwBC,SAASJ;AAAQ,EAAE;AAEhG,OAAO,MAAMK,YAAsB;IAAEC,MAAM;QAAEC,QAAQ;IAAS;AAAE,EAAE;AAclE,OAAO,SAASC,gBACdC,IAAs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,QAAQA,OAAO,KAAK,YAAYA,QAAQY,MAAM,KAAK,SAAS,OAAOZ;IACvE,IAAIA,QAAQA,OAAO,KAAK,UAAU,OAAOA;IACzC,OAAO;QACL,GAAGA,OAAO;QACVK,MAAM,GAAGR,SAASG,QAAQK,IAAI,EAAE;QAChC,GAAIL,QAAQa,SAAS,KAAKtB,YACtB,CAAC,IACD;YAAEsB,WAAWb,QAAQa,SAAS,CAACL,GAAG,CAAC,CAACxC,OAAS,GAAG6B,SAAS7B,MAAM;QAAE,CAAC;IACxE;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/connection.ts"],"sourcesContent":["import { rawQuery, type QueryBinding, type QueryInput } from './query.js';\nimport {\n cached,\n modelTypes,\n NO_MODEL,\n sameModel,\n type AttachedModelBinding,\n type ModelState,\n type TypesResult,\n} from './model.js';\nimport {\n query as evaluate,\n type QueryOptions,\n type QueryResult,\n type QueryRoom,\n} from '@agentshouse/query';\nimport {\n ROOM_CONTRACT_VERSION,\n VERSION_1_CAPABILITIES,\n type ActionResult,\n type Adapter,\n type AdapterFailure,\n type Authorization,\n type Capability,\n type DiscoveredRoom,\n type HistoryResult,\n type MutationResult,\n type ProviderLimit,\n} from './adapter.js';\nimport { bootstrapRoom } from './bootstrap.js';\nimport type { Change, ChangeBatch } from './change.js';\nimport { MD_MODEL, PRESENTED, validRoot, type MdType } from './collection.js';\nimport { createLog } from './log.js';\nimport {\n queuedOutcome,\n refused,\n type QueueEntry,\n type QueueOutcome,\n type SubmissionOutcome,\n} from './outcome.js';\nimport { refreshRoom } from './refresh.js';\nimport { buildBatch, type SaveRefusal } from './save.js';\nimport {\n applyReturned,\n readConfirmed,\n replicaOf,\n type ConfirmedLayer,\n type Replica,\n} from './replica.js';\nimport {\n settled,\n same,\n saving,\n STARTING,\n transferring,\n type CycleProgress,\n type SyncStatus,\n} from './status.js';\nimport { detectStorageLoss, nextGeneration } from './durability.js';\nimport { openReplicaStore, type ReplicaStore } from './store.js';\nimport { unconfirmed, type Unconfirmed } from './transfer.js';\n\nconst DEFAULT_DISCOVERY_INTERVAL_MS = 60_000;\n\nconst knownCapabilities = new Set<string>(VERSION_1_CAPABILITIES);\n\nexport type AppRoom = {\n collectionRoot: string;\n name: string;\n locator: string;\n operations: import('./adapter.js').OperationScopes;\n replica: import('./adapter.js').ReplicaAdmission;\n attachedModel: import('./model.js').ModelIdentity | null;\n model: TypesResult;\n providerOwnedPaths: readonly string[];\n roomVersion: string | null;\n synchronizationAvailable: boolean;\n};\n\nexport type ConnectionRefusalReason =\n | 'no-matching-version'\n | 'missing-required-guarantee'\n | 'md-model-version-mismatch'\n | 'revoked-authorization';\n\nexport type ConnectionRefusal = {\n reason: ConnectionRefusalReason;\n reauthorizationOffered: boolean;\n};\n\nexport type MdRuntimeOptions = {\n adapter: Adapter;\n modelBinding: AttachedModelBinding | null;\n queryBinding: QueryBinding | null;\n requiredGuarantees: readonly string[];\n authorization?: Authorization;\n discoveryIntervalMs?: number;\n signal?: AbortSignal;\n};\n\nexport type SaveResult = { outcome: 'saved'; id: string } | ({ outcome: 'refused' } & SaveRefusal);\n\nexport type DraftEntry = {\n readonly locator: string;\n readonly path: string;\n readonly content: unknown;\n};\n\nexport type DraftSurface = {\n list(): Promise<readonly DraftEntry[]>;\n read(locator: string, path: string): unknown;\n replace(locator: string, path: string, content: unknown): Promise<void>;\n discard(locator: string, path: string): Promise<void>;\n};\n\nexport type QueueSurface = {\n discard(locator: string, identifier: string): Promise<void>;\n};\n\nexport type HistoryQuery = {\n revision?: string;\n pageToken?: string;\n};\n\nexport type CallResult = ActionResult | { kind: 'undeclared' };\n\nexport type MdRuntime = {\n rooms(): readonly AppRoom[];\n query(options?: QueryOptions): QueryResult;\n types(locator: string): TypesResult;\n syncStatus(): SyncStatus;\n draft: DraftSurface;\n save(locator: string, changes: readonly Change[], replacing?: string): Promise<SaveResult>;\n outcome(identifier: string): SubmissionOutcome | null;\n queue: QueueSurface;\n history(locator: string, path: string, query?: HistoryQuery): Promise<HistoryResult>;\n call(name: string, input: unknown): Promise<CallResult>;\n log(): string;\n storageLoss(): string | null;\n observe: {\n (topic: 'rooms', listener: (rooms: readonly AppRoom[]) => void): () => void;\n (\n topic: 'connection-refusal',\n listener: (refusal: ConnectionRefusal | null) => void,\n ): () => void;\n (topic: 'storage-loss', listener: (statement: string | null) => void): () => void;\n (topic: 'sync-status', listener: (status: SyncStatus) => void): () => void;\n (topic: 'query', query: QueryOptions, listener: (result: QueryResult) => void): () => void;\n (\n topic: 'queue',\n locator: string,\n listener: (entries: readonly QueueEntry[]) => void,\n ): () => void;\n (topic: 'drafts', listener: (drafts: readonly DraftEntry[]) => void): () => void;\n };\n reauthorize(): Promise<void>;\n};\n\ntype QuerySubscription = {\n query: QueryOptions;\n notify: (result: QueryResult) => void;\n};\n\ntype QueueSubscription = {\n locator: string;\n notify: (entries: readonly QueueEntry[]) => void;\n};\n\ntype DraftSubscription = {\n notify: (drafts: readonly DraftEntry[]) => void;\n ready: boolean;\n};\n\ntype Withheld = AdapterFailure | Unconfirmed;\n\nexport function createMdRuntime(options: MdRuntimeOptions): MdRuntime {\n const period = options.discoveryIntervalMs ?? DEFAULT_DISCOVERY_INTERVAL_MS;\n let authorization: Authorization | undefined = options.authorization;\n let opening: Promise<ReplicaStore> | undefined;\n let store: ReplicaStore | undefined;\n const replicas = new Map<string, Replica>();\n const drafts = new Map<string, Map<string, unknown>>();\n const outcomes = new Map<string, SubmissionOutcome>();\n let limits: readonly ProviderLimit[] = [];\n let capabilities: readonly Capability[] = [];\n const rooms = new Map<string, AppRoom>();\n const unreadable = new Set<string>();\n const models = new Map<string, ModelState>();\n const liveModels = new Map<string, string>();\n const invalidModels = new Set<string>();\n const modelEpoch = new Map<string, number>();\n function modelOf(locator: string): ModelState {\n return models.get(locator) ?? NO_MODEL;\n }\n\n const mismatchedRoots = new Set<string>();\n let refusal: ConnectionRefusal | null = null;\n let storageLoss: string | null = null;\n let status: SyncStatus = STARTING;\n let discoveryPaused = false;\n let timer: ReturnType<typeof setInterval> | undefined;\n let closed = false;\n let chain: Promise<void> = Promise.resolve();\n let mutations: Promise<unknown> = Promise.resolve();\n let inflight = false;\n let queued = false;\n const roomListeners = new Set<(rooms: readonly AppRoom[]) => void>();\n const refusalListeners = new Set<(refusal: ConnectionRefusal | null) => void>();\n const storageLossListeners = new Set<(statement: string | null) => void>();\n const statusListeners = new Set<(status: SyncStatus) => void>();\n const querySubscriptions = new Set<QuerySubscription>();\n const queueSubscriptions = new Set<QueueSubscription>();\n const draftListeners = new Set<DraftSubscription>();\n const journal = createLog();\n let notifyReady = () => {};\n const ready = new Promise<void>((resolve) => {\n notifyReady = resolve;\n });\n let leader = typeof window === 'undefined';\n let applyingRemote = false;\n let releaseLeadership = () => {};\n const channel = typeof window !== 'undefined' ? new BroadcastChannel('mdruntime') : undefined;\n\n function draftContent(locator: string, path: string) {\n return drafts.get(locator)?.get(path);\n }\n\n function rememberDraft(locator: string, path: string, content: unknown) {\n const room = drafts.get(locator) ?? new Map<string, unknown>();\n room.set(path, content);\n drafts.set(locator, room);\n }\n\n function forgetDraft(locator: string, path: string) {\n const room = drafts.get(locator);\n if (room === undefined) return;\n room.delete(path);\n if (room.size === 0) drafts.delete(locator);\n }\n\n function snapshotDrafts(): readonly DraftEntry[] {\n const entries: DraftEntry[] = [];\n for (const [locator, room] of drafts) {\n for (const [path, content] of room) {\n entries.push({ locator, path, content: structuredClone(content) });\n }\n }\n entries.sort((left, right) => {\n if (left.locator !== right.locator) return left.locator < right.locator ? -1 : 1;\n if (left.path !== right.path) return left.path < right.path ? -1 : 1;\n return 0;\n });\n return entries;\n }\n\n async function readDrafts(opened: ReplicaStore) {\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(opened);\n });\n return snapshotDrafts();\n }\n\n function publishDrafts(waitingOnly: boolean) {\n if (closed) return;\n const value = snapshotDrafts();\n for (const listener of draftListeners) {\n if (waitingOnly && listener.ready) continue;\n listener.ready = true;\n listener.notify(value);\n }\n }\n\n function emitDrafts() {\n publishDrafts(false);\n }\n\n function releaseWaitingDrafts() {\n publishDrafts(true);\n }\n\n function commitDraft(work: (local: ReplicaStore) => Promise<void>) {\n return exclusive(async () => {\n const local = await openLocal();\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n await work(local);\n });\n }).then(() => {\n emitDrafts();\n announce();\n });\n }\n\n function pending() {\n return [...replicas.values()].some((replica) => replica.queue.length > 0);\n }\n\n function attention() {\n return [...replicas.values()].some((replica) => {\n const head = replica.queue[0];\n return head !== undefined && refused(outcomes.get(head.id));\n });\n }\n\n function storedOutcomes(batches: readonly ChangeBatch[]) {\n const stored: Record<string, QueueOutcome> = {};\n for (const batch of batches) {\n const outcome = queuedOutcome(outcomes.get(batch.id));\n if (outcome.kind !== 'pending') stored[batch.id] = outcome;\n }\n return stored;\n }\n\n async function persistQueue(\n local: ReplicaStore,\n locator: string,\n batches: readonly ChangeBatch[],\n ) {\n await local.writeQueue({\n locator,\n batches,\n outcomes: storedOutcomes(batches),\n });\n announce();\n }\n\n function listed(): readonly AppRoom[] {\n return structuredClone([...rooms.values()]);\n }\n\n function queryRooms(): readonly QueryInput[] {\n return [...replicas.values()].map((replica) => ({\n room: replica.confirmed.record.locator,\n roomVersion: replica.confirmed.record.roomVersion,\n documents: replica.visible.collection.documents,\n model: modelTypes(modelOf(replica.confirmed.record.locator)),\n }));\n }\n\n function emitRooms() {\n const value = listed();\n for (const listener of roomListeners) listener(value);\n }\n\n function emitRefusal() {\n for (const listener of refusalListeners) listener(refusal);\n }\n\n function emitStorageLoss() {\n for (const listener of storageLossListeners) listener(storageLoss);\n }\n\n function announce(type: 'changed' | 'enqueue' | 'hello' = 'changed') {\n if (applyingRemote || channel === undefined) return;\n if (type === 'hello') {\n channel.postMessage({ type: 'hello' });\n return;\n }\n channel.postMessage({ type, status });\n }\n\n function adopt(next: SyncStatus) {\n if (closed || same(status, next)) return;\n status = next;\n for (const listener of statusListeners) listener(status);\n }\n\n function moveTo(next: SyncStatus) {\n if (closed || same(status, next)) return;\n adopt(next);\n announce();\n }\n\n function visible(request: QueryOptions): QueryResult {\n if (options.queryBinding === null) {\n if (Object.keys(request).length > 0) throw new Error('query-binding-unavailable');\n return rawQuery(queryRooms());\n }\n return options.queryBinding(queryRooms(), {\n ...request,\n selector: { $and: [PRESENTED, request.selector ?? {}] },\n });\n }\n\n function emitVisible() {\n for (const subscription of querySubscriptions) {\n subscription.notify(visible(subscription.query));\n }\n }\n\n function entriesOf(locator: string): readonly QueueEntry[] {\n const replica = replicas.get(locator);\n if (replica === undefined) return [];\n return replica.queue.map((batch) =>\n Object.freeze({\n batch,\n outcome: queuedOutcome(outcomes.get(batch.id)),\n }),\n );\n }\n\n function emitQueue(locator: string) {\n const entries = entriesOf(locator);\n for (const subscription of queueSubscriptions) {\n if (subscription.locator === locator) subscription.notify(entries);\n }\n }\n\n function stopTimer() {\n if (timer === undefined) return;\n clearInterval(timer);\n timer = undefined;\n }\n\n function startTimer() {\n if (timer !== undefined) return;\n timer = setInterval(() => {\n void enqueue();\n }, period);\n }\n\n function refuse(reason: ConnectionRefusalReason) {\n if (reason === 'revoked-authorization') {\n const revoked: ModelState = { status: 'unavailable', reason: 'revoked' };\n for (const locator of new Set([...models.keys(), ...rooms.keys()])) {\n invalidModels.add(locator);\n modelEpoch.set(locator, (modelEpoch.get(locator) ?? 0) + 1);\n models.set(locator, revoked);\n liveModels.delete(locator);\n }\n for (const [locator, room] of rooms)\n rooms.set(locator, { ...room, model: modelTypes(revoked) });\n emitRooms();\n void exclusive(async () => {\n const local = await openLocal();\n await acrossTabs('mdruntime-replica', async () => {\n for (const record of await local.all())\n await local.publish({ ...record, model: revoked });\n });\n announce();\n }).catch(() => {\n journal.record('model invalidation durable-write failure');\n });\n }\n stopTimer();\n discoveryPaused = true;\n refusal = {\n reason,\n reauthorizationOffered: reason === 'revoked-authorization',\n };\n journal.record(`connection refused ${reason}`);\n emitRefusal();\n }\n\n function list(room: Omit<DiscoveredRoom, 'roomVersion'>, synchronizationAvailable: boolean) {\n rooms.set(room.locator, {\n name: room.name,\n collectionRoot: room.collectionRoot,\n locator: room.locator,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n model: modelTypes(modelOf(room.locator)),\n providerOwnedPaths: room.providerOwnedPaths,\n roomVersion: replicas.get(room.locator)?.confirmed.record.roomVersion ?? null,\n synchronizationAvailable,\n });\n }\n\n function applyDiscovery(discovered: readonly DiscoveredRoom[]): ReadonlySet<string> {\n const listedLocators = new Set(discovered.map((room) => room.locator));\n for (const room of discovered) {\n const held = replicas.get(room.locator)?.confirmed.record;\n if (held !== undefined && held.replica.selection !== room.replica.selection) {\n list(held, false);\n continue;\n }\n list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));\n }\n for (const [locator, room] of rooms) {\n if (listedLocators.has(locator)) continue;\n rooms.set(locator, { ...room, synchronizationAvailable: false });\n }\n emitRooms();\n return listedLocators;\n }\n\n async function hydrate(opened: ReplicaStore): Promise<{\n lastCompleted: string | null;\n locators: Set<string>;\n }> {\n const [records, queues, kept, lastCompleted, declared] = await Promise.all([\n opened.all(),\n opened.queues(),\n opened.drafts(),\n opened.lastCompleted(),\n opened.providerLimits(),\n ]);\n limits = declared;\n drafts.clear();\n for (const draft of kept) rememberDraft(draft.locator, draft.path, draft.content);\n const queuedBatches = new Map(queues.map((queue) => [queue.locator, queue.batches]));\n outcomes.clear();\n for (const queue of queues) {\n for (const [id, outcome] of Object.entries(queue.outcomes)) {\n outcomes.set(id, outcome);\n }\n }\n replicas.clear();\n for (const record of records) {\n const persisted = record.model;\n const priorModel = models.get(record.locator);\n if (\n priorModel !== undefined &&\n priorModel.status !== 'unavailable' &&\n (persisted.status === 'unavailable' || !sameModel(priorModel.snapshot, persisted.snapshot))\n ) {\n modelEpoch.set(record.locator, (modelEpoch.get(record.locator) ?? 0) + 1);\n invalidModels.add(record.locator);\n }\n const model =\n persisted.status === 'unavailable' ||\n liveModels.get(record.locator) === JSON.stringify(persisted.snapshot)\n ? persisted\n : cached(persisted);\n models.set(record.locator, model);\n if (model.status === 'unavailable') {\n liveModels.delete(record.locator);\n invalidModels.delete(record.locator);\n }\n const confirmed = readConfirmed({ ...record, model });\n if (confirmed === null) continue;\n replicas.set(record.locator, replicaOf(confirmed, queuedBatches.get(record.locator) ?? []));\n const existing = rooms.get(record.locator);\n if (existing === undefined) list(record, false);\n else {\n rooms.set(record.locator, {\n ...existing,\n roomVersion: record.roomVersion,\n operations: record.operations,\n replica: record.replica,\n attachedModel: record.attachedModel,\n model: modelTypes(model),\n });\n }\n }\n return {\n lastCompleted,\n locators: new Set([...queuedBatches.keys(), ...replicas.keys()]),\n };\n }\n\n async function readState(opened: ReplicaStore): Promise<string | null> {\n const { lastCompleted, locators } = await hydrate(opened);\n if (replicas.size > 0) {\n emitRooms();\n emitVisible();\n }\n for (const locator of locators) emitQueue(locator);\n emitDrafts();\n return lastCompleted;\n }\n\n async function applyRemote(message: { type?: unknown; status?: SyncStatus }) {\n if (closed) return;\n if (message.type === 'hello') {\n if (leader) announce();\n return;\n }\n applyingRemote = true;\n try {\n const local = await openLocal();\n const lastCompleted = await readState(local);\n if (message.status !== undefined) adopt(message.status);\n else {\n adopt({\n ...status,\n lastCompleted,\n attentionRequired: attention(),\n state: pending() ? 'pending' : status.state,\n });\n }\n } finally {\n applyingRemote = false;\n }\n if (message.type === 'enqueue' && leader) void enqueue();\n }\n\n async function open(): Promise<ReplicaStore> {\n const opened = await openReplicaStore();\n store = opened;\n await acrossTabs('mdruntime-generation', async () => {\n const storedGeneration = await opened.generation();\n const loss = detectStorageLoss(storedGeneration);\n const generation = nextGeneration(storedGeneration);\n if (generation !== storedGeneration) await opened.rememberGeneration(generation);\n if (loss !== null) {\n storageLoss = loss;\n emitStorageLoss();\n }\n });\n const lastCompleted = await readState(opened);\n adopt({ ...status, lastCompleted, attentionRequired: attention() });\n if (!leader) announce('hello');\n return opened;\n }\n\n function openLocal(): Promise<ReplicaStore> {\n opening ??= open().catch((error: unknown) => {\n opening = undefined;\n throw error;\n });\n return opening;\n }\n\n function exclusive<T>(work: () => Promise<T>): Promise<T> {\n const next = mutations.then(work, work);\n mutations = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n\n function acrossTabs<T>(name: string, work: () => Promise<T>): Promise<T> {\n if (typeof window === 'undefined') return work();\n return window.navigator.locks.request(name, work);\n }\n\n function publish(local: ReplicaStore, room: DiscoveredRoom, confirmed: ConfirmedLayer) {\n return exclusive(async () => {\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const retained = readConfirmed({ ...confirmed.record, model: modelOf(room.locator) });\n if (retained === null) return;\n await local.publish(retained.record);\n unreadable.delete(room.locator);\n replicas.set(room.locator, replicaOf(retained, replicas.get(room.locator)?.queue ?? []));\n });\n list(room, true);\n emitRooms();\n emitVisible();\n announce();\n });\n }\n\n async function write(\n locator: string,\n changes: readonly Change[],\n replacing?: string,\n ): Promise<SaveResult> {\n const local = await openLocal();\n const result = await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const replica = replicas.get(locator);\n const room = rooms.get(locator);\n if (replica === undefined || room === undefined) {\n throw new Error(`No Local Replica for ${locator}`);\n }\n if (mismatchedRoots.has(locator))\n return { outcome: 'refused' as const, rule: 'collection-root-mismatch' };\n const built = buildBatch({\n baseRoomVersion: replica.confirmed.record.roomVersion,\n collectionRoot: replica.confirmed.record.collectionRoot,\n operations: room.operations,\n model: invalidModels.has(locator)\n ? { status: 'unavailable', reason: 'revoked' }\n : modelOf(locator),\n binding: options.modelBinding,\n providerOwnedPaths: room.providerOwnedPaths,\n providerLimits: limits,\n visible: replica.visible,\n changes,\n });\n if (built.kind === 'refused') return { outcome: 'refused' as const, ...built.refusal };\n const head = replica.queue[0];\n if (replacing !== undefined) {\n if (head === undefined || head.id !== replacing || !refused(outcomes.get(head.id))) {\n return { outcome: 'refused' as const, rule: 'no-refused-head' };\n }\n }\n const batches =\n replacing === undefined\n ? [...replica.queue, built.batch]\n : [built.batch, ...replica.queue.slice(1)];\n const consumed = [...new Set(changes.map((change) => change.path))];\n try {\n await local.append({ locator, batches, outcomes: storedOutcomes(batches) }, consumed);\n } catch {\n return { outcome: 'refused' as const, rule: 'durable-write' };\n }\n if (replacing !== undefined) outcomes.delete(replacing);\n for (const path of consumed) forgetDraft(locator, path);\n replicas.set(locator, replicaOf(replica.confirmed, batches));\n emitQueue(locator);\n emitVisible();\n emitDrafts();\n moveTo({ ...saving(status), attentionRequired: attention() });\n return { outcome: 'saved' as const, id: built.batch.id };\n });\n if (result.outcome === 'saved') void enqueue();\n return result;\n }\n\n async function discardHead(locator: string, identifier: string): Promise<void> {\n const local = await openLocal();\n const changed = await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const replica = replicas.get(locator);\n const head = replica?.queue[0];\n if (\n replica === undefined ||\n head === undefined ||\n head.id !== identifier ||\n !refused(outcomes.get(head.id))\n ) {\n return false;\n }\n const batches = replica.queue.slice(1);\n outcomes.delete(identifier);\n await persistQueue(local, locator, batches);\n replicas.set(locator, replicaOf(replica.confirmed, batches));\n emitQueue(locator);\n emitVisible();\n moveTo({\n ...status,\n state: pending() ? 'pending' : status.state,\n attentionRequired: attention(),\n });\n return true;\n });\n if (changed) void enqueue();\n }\n\n async function readHistory(\n locator: string,\n path: string,\n query: HistoryQuery = {},\n ): Promise<HistoryResult> {\n if (closed || refusal !== null) return { kind: 'transport-uncertainty' };\n try {\n await ensureAuthorization();\n } catch {\n return { kind: 'transport-uncertainty' };\n }\n if (closed || authorization === undefined || refusal !== null) {\n return { kind: 'transport-uncertainty' };\n }\n const transfer = ['transfer', 'history', locator, path];\n if (query.revision !== undefined) transfer.push(query.revision);\n if (query.pageToken !== undefined) transfer.push(query.pageToken);\n journal.record(transfer.join(' '));\n try {\n const result = await options.adapter.history(authorization, {\n locator,\n path,\n ...(query.revision === undefined ? {} : { revision: query.revision }),\n ...(query.pageToken === undefined ? {} : { pageToken: query.pageToken }),\n });\n journal.record(`outcome history ${result.kind}`);\n if (result.kind === 'scoped-refusal') {\n const room = replicas.get(result.locator)?.confirmed.record;\n if (room !== undefined) await scoped(result, room, await openLocal());\n }\n if (result.kind === 'revoked-authorization') refuse('revoked-authorization');\n return result;\n } catch {\n journal.record('outcome history transport-uncertainty');\n return { kind: 'transport-uncertainty' };\n }\n }\n\n function declaredAction(name: string) {\n for (const capability of capabilities) {\n for (const action of capability.actions ?? []) {\n if (action.name === name) return action;\n }\n }\n return undefined;\n }\n\n async function invokeAction(name: string, input: unknown): Promise<CallResult> {\n await ready;\n if (closed || refusal !== null) return { kind: 'transport-uncertainty' };\n if (declaredAction(name) === undefined) return { kind: 'undeclared' };\n try {\n await ensureAuthorization();\n } catch {\n return { kind: 'transport-uncertainty' };\n }\n if (closed || authorization === undefined || refusal !== null) {\n return { kind: 'transport-uncertainty' };\n }\n journal.record(`transfer action ${name}`);\n try {\n const result = await options.adapter.action(authorization, { name, input });\n if (result.kind === 'scoped-refusal') {\n const room = replicas.get(result.locator)?.confirmed.record;\n if (room !== undefined) await scoped(result, room, await openLocal());\n }\n if (result.kind === 'revoked-authorization') refuse('revoked-authorization');\n journal.record(`outcome action ${result.kind}`);\n if (result.kind === 'rejected') journal.record(`refusal rejected ${result.text}`);\n return result;\n } catch {\n journal.record('outcome action transport-uncertainty');\n return { kind: 'transport-uncertainty' };\n }\n }\n\n async function pullRefresh(authorized: Authorization, confirmed: ConfirmedLayer) {\n try {\n const result = await refreshRoom(\n options.adapter,\n authorized,\n confirmed,\n options.modelBinding,\n );\n const detail = result.kind === 'advanced' ? result.confirmed.record.roomVersion : result.kind;\n journal.record(`transfer refresh ${confirmed.record.locator} ${detail}`);\n return result;\n } catch (error) {\n journal.record(`transfer refresh ${confirmed.record.locator} transport-uncertainty`);\n throw error;\n }\n }\n\n async function pullBootstrap(authorized: Authorization, room: DiscoveredRoom) {\n try {\n const result = await bootstrapRoom(\n options.adapter,\n authorized,\n room,\n modelOf(room.locator),\n options.modelBinding,\n );\n const detail = result.kind === 'staged' ? result.confirmed.record.roomVersion : result.kind;\n journal.record(`transfer bootstrap ${room.locator} ${detail}`);\n return result;\n } catch (error) {\n journal.record(`transfer bootstrap ${room.locator} transport-uncertainty`);\n throw error;\n }\n }\n\n async function advance(\n room: DiscoveredRoom,\n local: ReplicaStore,\n authorized: Authorization,\n ): Promise<Withheld | null> {\n const held = replicas.get(room.locator);\n if (held !== undefined) {\n const refreshed = await pullRefresh(authorized, held.confirmed);\n if (refreshed.kind === 'still-current') {\n if (unreadable.delete(room.locator)) {\n list(room, true);\n emitRooms();\n }\n return null;\n }\n if (refreshed.kind === 'advanced') {\n if (closed) return unconfirmed;\n await publish(local, room, refreshed.confirmed);\n return null;\n }\n if (refreshed.kind !== 'beyond-horizon') return refreshed;\n }\n const bootstrapped = await pullBootstrap(authorized, room);\n if (bootstrapped.kind !== 'staged') return bootstrapped;\n if (closed) return unconfirmed;\n await publish(local, room, bootstrapped.confirmed);\n return null;\n }\n\n function recordRefusal(\n result: Extract<MutationResult, { kind: 'conflicted' | 'rejected' | 'expired' }>,\n ): QueueOutcome {\n if (result.kind === 'expired') return { kind: 'expired' };\n if (result.kind === 'conflicted') {\n return {\n kind: 'conflicted',\n roomVersion: result.roomVersion,\n affected: result.affected,\n text: result.text,\n };\n }\n return { kind: 'rejected', affected: result.affected, text: result.text };\n }\n\n async function commitAccept(\n room: DiscoveredRoom,\n local: ReplicaStore,\n submitted: ChangeBatch,\n accepted: Extract<MutationResult, { kind: 'accepted' }>,\n base: ConfirmedLayer,\n overlay: boolean,\n ): Promise<boolean> {\n return acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const current = replicas.get(room.locator);\n if (current === undefined || !current.queue.some((batch) => batch.id === submitted.id)) {\n return true;\n }\n const remaining = current.queue.filter((batch) => batch.id !== submitted.id);\n const retainedBase = readConfirmed({ ...base.record, model: modelOf(room.locator) });\n if (retainedBase === null) return false;\n const applied = overlay\n ? applyReturned(\n retainedBase,\n accepted.documents,\n accepted.revisions,\n accepted.removals,\n accepted.roomVersion,\n options.modelBinding,\n )\n : retainedBase;\n if (applied === null) return false;\n await local.publish(applied.record);\n await persistQueue(local, room.locator, remaining);\n outcomes.set(submitted.id, {\n kind: 'accepted',\n roomVersion: accepted.roomVersion,\n author: accepted.author,\n time: accepted.time,\n });\n unreadable.delete(room.locator);\n replicas.set(room.locator, replicaOf(applied, remaining));\n list(room, true);\n emitRooms();\n emitQueue(room.locator);\n emitVisible();\n journal.record(`outcome ${room.locator} ${submitted.id} accepted`);\n return true;\n });\n }\n\n async function submitRoom(\n room: DiscoveredRoom,\n local: ReplicaStore,\n authorized: Authorization,\n progress: CycleProgress,\n ): Promise<'stop' | null> {\n while (!closed && authorization !== undefined) {\n const replica = replicas.get(room.locator);\n const head = replica?.queue[0];\n if (replica === undefined || head === undefined || refused(outcomes.get(head.id))) {\n return null;\n }\n let result: MutationResult;\n journal.record(`submission ${room.locator} ${head.id}`);\n try {\n result = await options.adapter.mutate(authorized, {\n locator: room.locator,\n changeBatch: head,\n });\n } catch {\n progress.complete = false;\n progress.reachable = false;\n return null;\n }\n if (closed) return null;\n if (result.kind === 'transport-uncertainty') {\n progress.complete = false;\n progress.reachable = false;\n return null;\n }\n if (result.kind === 'room-not-readable') {\n progress.complete = false;\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n return null;\n }\n if (result.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return 'stop';\n }\n if (result.kind === 'scoped-refusal') {\n await scoped(result, room, local);\n progress.complete = false;\n return null;\n }\n if (result.kind === 'conflicted' || result.kind === 'rejected' || result.kind === 'expired') {\n journal.record(`outcome ${room.locator} ${head.id} ${result.kind}`);\n if (result.kind !== 'expired') journal.record(`refusal ${result.kind} ${result.text}`);\n await exclusive(async () => {\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const current = replicas.get(room.locator);\n if (current === undefined || !current.queue.some((batch) => batch.id === head.id)) {\n return;\n }\n outcomes.set(head.id, recordRefusal(result));\n await persistQueue(local, room.locator, current.queue);\n emitQueue(room.locator);\n moveTo({ ...status, attentionRequired: true });\n });\n });\n return null;\n }\n const from = replicas.get(room.locator)?.confirmed;\n if (from === undefined) return null;\n const pulled = await pullRefresh(authorized, from);\n if (pulled.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return 'stop';\n }\n if (pulled.kind === 'scoped-refusal') {\n await scoped(pulled, room, local);\n progress.complete = false;\n return null;\n }\n if (pulled.kind === 'still-current') {\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, from, true),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n if (pulled.kind === 'advanced') {\n const overlay = pulled.confirmed.record.roomVersion === result.roomVersion;\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, pulled.confirmed, overlay),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n if (pulled.kind === 'beyond-horizon') {\n const bootstrapped = await pullBootstrap(authorized, room);\n if (bootstrapped.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return 'stop';\n }\n if (bootstrapped.kind === 'scoped-refusal') {\n await scoped(bootstrapped, room, local);\n progress.complete = false;\n return null;\n }\n if (bootstrapped.kind === 'staged') {\n const overlay = bootstrapped.confirmed.record.roomVersion === result.roomVersion;\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, bootstrapped.confirmed, overlay),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n progress.complete = false;\n if (bootstrapped.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (bootstrapped.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n }\n return null;\n }\n progress.complete = false;\n if (pulled.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (pulled.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n }\n return null;\n }\n return null;\n }\n\n async function retainModel(\n local: ReplicaStore,\n room: Omit<DiscoveredRoom, 'roomVersion'>,\n next: ModelState,\n ) {\n if (next.status === 'unavailable')\n modelEpoch.set(room.locator, (modelEpoch.get(room.locator) ?? 0) + 1);\n const epoch = modelEpoch.get(room.locator) ?? 0;\n const previous = modelOf(room.locator);\n const heldBefore = replicas.get(room.locator)?.confirmed.record;\n if (\n JSON.stringify(previous) === JSON.stringify(next) &&\n (heldBefore === undefined ||\n (JSON.stringify(heldBefore.operations) === JSON.stringify(room.operations) &&\n JSON.stringify(heldBefore.replica) === JSON.stringify(room.replica) &&\n JSON.stringify(heldBefore.attachedModel) === JSON.stringify(room.attachedModel)))\n )\n return;\n const queryChanged =\n previous.status === 'unavailable' || next.status === 'unavailable'\n ? previous.status !== next.status\n : JSON.stringify(previous.types) !== JSON.stringify(next.types);\n if (next.status === 'unavailable') {\n invalidModels.add(room.locator);\n liveModels.delete(room.locator);\n }\n await exclusive(async () =>\n acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n if (next.status !== 'unavailable' && epoch !== (modelEpoch.get(room.locator) ?? 0)) return;\n const held = replicas.get(room.locator);\n if (held !== undefined) {\n const record = {\n ...held.confirmed.record,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n model: next,\n };\n await local.publish(record);\n const confirmed = readConfirmed(record);\n if (confirmed !== null) replicas.set(room.locator, replicaOf(confirmed, held.queue));\n }\n models.set(room.locator, next);\n if (next.status === 'current') {\n liveModels.set(room.locator, JSON.stringify(next.snapshot));\n invalidModels.delete(room.locator);\n }\n list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));\n emitRooms();\n if (queryChanged && held !== undefined) emitVisible();\n announce();\n }),\n );\n }\n\n async function acquireModel(\n local: ReplicaStore,\n room: DiscoveredRoom,\n authorized: Authorization,\n ) {\n let previous = modelOf(room.locator);\n if (\n previous.status !== 'unavailable' &&\n (room.attachedModel === null || !sameModel(previous.snapshot, room.attachedModel))\n ) {\n previous = { status: 'unavailable', reason: 'version-changed' };\n await retainModel(local, room, previous);\n }\n const epoch = modelEpoch.get(room.locator) ?? 0;\n let answer;\n try {\n answer = await options.adapter.model(authorized, {\n locator: room.locator,\n collectionRoot: room.collectionRoot,\n model: room.attachedModel,\n });\n } catch {\n answer = { kind: 'transport-uncertainty' as const };\n }\n if (epoch !== (modelEpoch.get(room.locator) ?? 0)) return;\n if (answer.kind === 'revoked-authorization') {\n await retainModel(local, room, { status: 'unavailable', reason: 'revoked' });\n refuse('revoked-authorization');\n return;\n }\n if (answer.kind === 'transport-uncertainty') {\n await retainModel(local, room, cached(previous));\n return;\n }\n if (answer.kind === 'model-unavailable') {\n await retainModel(local, room, { status: 'unavailable', reason: answer.reason });\n return;\n }\n if (room.attachedModel === null || !sameModel(answer.snapshot, room.attachedModel)) {\n await retainModel(local, room, { status: 'unavailable', reason: 'version-changed' });\n return;\n }\n if (\n previous.status !== 'unavailable' &&\n sameModel(previous.snapshot, answer.snapshot) &&\n JSON.stringify(Object.entries(previous.snapshot.definitions).sort()) !==\n JSON.stringify(Object.entries(answer.snapshot.definitions).sort())\n ) {\n await retainModel(local, room, { status: 'unavailable', reason: 'invalid' });\n return;\n }\n const verified = options.modelBinding?.verify(answer.snapshot);\n await retainModel(\n local,\n room,\n verified?.kind === 'verified'\n ? {\n status: 'current',\n snapshot: structuredClone(answer.snapshot),\n verifiedWith: MD_MODEL,\n types: verified.types,\n }\n : {\n status: 'unavailable',\n reason: verified === undefined ? 'binding-unavailable' : 'invalid',\n },\n );\n }\n\n async function scoped(\n result: import('./adapter.js').ScopedRefusal,\n room: DiscoveredRoom,\n local: ReplicaStore,\n ) {\n if (result.scope === 'model')\n await retainModel(local, room, { status: 'unavailable', reason: 'not-readable' });\n else if (result.scope !== 'operation') {\n unreadable.add(room.locator);\n const unavailable: DiscoveredRoom = {\n ...room,\n replica: { ...room.replica, admission: 'unavailable' },\n operations: {\n ...room.operations,\n ...(result.scope === 'content' ? { read: [] } : {}),\n ...(result.scope === 'sync' ? { sync: [] } : {}),\n },\n };\n await retainModel(local, unavailable, modelOf(room.locator));\n list(unavailable, false);\n emitRooms();\n }\n journal.record(`scoped refusal ${room.locator} ${result.scope} ${result.text}`);\n }\n\n async function synchronize(\n discovered: readonly DiscoveredRoom[],\n local: ReplicaStore,\n progress: CycleProgress,\n ) {\n for (const room of discovered) {\n if (closed || authorization === undefined) {\n progress.complete = false;\n return;\n }\n const prior = replicas.get(room.locator)?.confirmed.record;\n if (prior !== undefined && prior.replica.selection !== room.replica.selection) {\n list(prior, false);\n emitRooms();\n journal.record(`selection changed ${room.locator}`);\n progress.complete = false;\n continue;\n }\n await acquireModel(local, room, authorization);\n if (discoveryPaused) return;\n if (room.replica.admission !== 'admitted') {\n progress.complete = false;\n continue;\n }\n const held = replicas.get(room.locator);\n if (\n held !== undefined &&\n held.confirmed.record.replica.selection !== room.replica.selection\n ) {\n progress.complete = false;\n continue;\n }\n const withheld = await advance(room, local, authorization);\n if (withheld !== null) {\n progress.complete = false;\n if (withheld.kind === 'scoped-refusal') {\n await scoped(withheld, room, local);\n continue;\n }\n if (withheld.kind === 'transport-uncertainty') {\n progress.reachable = false;\n continue;\n }\n if (withheld.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n continue;\n }\n if (withheld.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return;\n }\n continue;\n }\n if ((await submitRoom(room, local, authorization, progress)) === 'stop') return;\n }\n }\n\n async function cycle(local: ReplicaStore, progress: CycleProgress) {\n if (closed || authorization === undefined) {\n notifyReady();\n return;\n }\n moveTo(transferring(status));\n let result;\n try {\n result = await options.adapter.discover(authorization);\n } catch {\n result = { kind: 'transport-uncertainty' as const };\n }\n if (closed) {\n notifyReady();\n return;\n }\n journal.record(`connection discover ${result.kind}`);\n if (result.kind === 'transport-uncertainty') {\n for (const room of rooms.values())\n await retainModel(local, room, cached(modelOf(room.locator)));\n progress.reachable = false;\n notifyReady();\n return;\n }\n if (result.kind === 'contract-unavailable') {\n journal.record(`connection contract unavailable ${result.text}`);\n refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n if (result.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n notifyReady();\n return;\n }\n if (!result.supportedVersions.includes(ROOM_CONTRACT_VERSION)) {\n refuse('no-matching-version');\n notifyReady();\n return;\n }\n if (\n result.mdModel.identity !== MD_MODEL.identity ||\n result.mdModel.version !== MD_MODEL.version\n ) {\n refuse('md-model-version-mismatch');\n notifyReady();\n return;\n }\n mismatchedRoots.clear();\n for (const room of result.rooms) {\n const held = replicas.get(room.locator)?.confirmed.record;\n const malformed = !validRoot(room.collectionRoot);\n if (\n room.operations === undefined ||\n !['read', 'sync', 'write', 'delete'].every(\n (operation) =>\n Array.isArray(room.operations[operation as keyof typeof room.operations]) &&\n room.operations[operation as keyof typeof room.operations].every(\n (scope) => typeof scope === 'string',\n ),\n ) ||\n room.replica === undefined ||\n typeof room.replica.selection !== 'string' ||\n room.replica.selection.length === 0 ||\n !['admitted', 'unavailable'].includes(room.replica.admission) ||\n room.attachedModel === undefined ||\n (room.attachedModel !== null &&\n (typeof room.attachedModel.identity !== 'string' ||\n !room.attachedModel.identity ||\n typeof room.attachedModel.version !== 'string' ||\n !room.attachedModel.version))\n ) {\n journal.record(`invalid model or replica declaration ${room.locator}`);\n refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n if (malformed || (held !== undefined && held.collectionRoot !== room.collectionRoot)) {\n mismatchedRoots.add(room.locator);\n journal.record(`collection root ${malformed ? 'invalid' : 'changed'} ${room.locator}`);\n }\n }\n if (mismatchedRoots.size > 0) {\n refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n const declared = new Set(result.capabilities.map((capability) => capability.name));\n for (const required of options.requiredGuarantees) {\n if (!knownCapabilities.has(required) || !declared.has(required)) {\n refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n }\n if (refusal !== null) {\n refusal = null;\n emitRefusal();\n }\n capabilities = result.capabilities;\n notifyReady();\n if (JSON.stringify(result.providerLimits) !== JSON.stringify(limits)) {\n limits = result.providerLimits;\n await local.declare(limits);\n }\n const listedLocators = applyDiscovery(result.rooms);\n progress.complete = [...replicas.keys()].every((locator) => listedLocators.has(locator));\n await synchronize(result.rooms, local, progress);\n }\n\n async function ensureAuthorization() {\n if (authorization !== undefined) return;\n try {\n authorization = await options.adapter.authorize();\n journal.record('connection authorize');\n } catch (error) {\n journal.record('connection authorize transport-uncertainty');\n throw error;\n }\n }\n\n async function connect() {\n if (closed || discoveryPaused) {\n notifyReady();\n return;\n }\n startTimer();\n const progress: CycleProgress = { complete: false, reachable: true };\n let completedAt = new Date().toISOString();\n try {\n const local = await openLocal();\n if (closed) return;\n await ensureAuthorization();\n if (closed) return;\n await cycle(local, progress);\n if (closed) return;\n if (progress.complete) {\n completedAt = new Date().toISOString();\n await local.complete(completedAt);\n }\n } catch {\n progress.complete = false;\n notifyReady();\n return;\n } finally {\n notifyReady();\n moveTo(settled(status, progress, completedAt, pending(), attention()));\n }\n }\n\n async function run() {\n try {\n await connect();\n } finally {\n inflight = false;\n if (queued && !closed) {\n queued = false;\n void enqueue();\n }\n }\n }\n\n function enqueue() {\n if (!leader) {\n announce('enqueue');\n return chain;\n }\n if (inflight) {\n queued = true;\n return chain;\n }\n inflight = true;\n chain = chain.then(run, run);\n return chain;\n }\n\n function startProcessing() {\n if (leader) {\n void enqueue();\n return;\n }\n void window.navigator.locks\n .request('mdruntime-sync', { signal: options.signal }, async () => {\n if (closed) return;\n leader = true;\n announce();\n void enqueue();\n await new Promise<void>((resolve) => {\n releaseLeadership = () => {\n leader = false;\n resolve();\n };\n });\n })\n .catch(() => {});\n }\n\n function close() {\n closed = true;\n stopTimer();\n releaseLeadership();\n channel?.close();\n store?.close();\n roomListeners.clear();\n refusalListeners.clear();\n storageLossListeners.clear();\n statusListeners.clear();\n querySubscriptions.clear();\n queueSubscriptions.clear();\n draftListeners.clear();\n }\n\n channel?.addEventListener('message', (event) => {\n const data = event.data;\n if (data === null || typeof data !== 'object') return;\n void exclusive(() => applyRemote(data as { type?: unknown; status?: SyncStatus }));\n });\n\n options.signal?.addEventListener('abort', close, { once: true });\n if (options.signal?.aborted) close();\n\n void openLocal().then(\n () => {\n if (!leader) notifyReady();\n },\n () => {\n notifyReady();\n },\n );\n startProcessing();\n\n return {\n rooms() {\n return listed();\n },\n query(request: QueryOptions = {}) {\n return visible(request);\n },\n types(locator: string) {\n return modelTypes(modelOf(locator));\n },\n syncStatus() {\n return status;\n },\n draft: {\n list() {\n return exclusive(async () => {\n const local = await openLocal();\n return readDrafts(local);\n }).then((entries) => {\n releaseWaitingDrafts();\n return entries;\n });\n },\n read(locator: string, path: string) {\n const content = draftContent(locator, path);\n return content === undefined ? null : structuredClone(content);\n },\n replace(locator: string, path: string, content: unknown) {\n return commitDraft(async (local) => {\n const stored = structuredClone(content);\n await local.keep({ locator, path, content: stored });\n rememberDraft(locator, path, stored);\n });\n },\n discard(locator: string, path: string) {\n return commitDraft(async (local) => {\n await local.discard(locator, path);\n forgetDraft(locator, path);\n });\n },\n },\n save(locator: string, changes: readonly Change[], replacing?: string): Promise<SaveResult> {\n return exclusive(() => write(locator, changes, replacing));\n },\n outcome(identifier: string): SubmissionOutcome | null {\n const recorded = outcomes.get(identifier);\n if (recorded !== undefined) return recorded;\n for (const replica of replicas.values()) {\n if (replica.queue.some((batch) => batch.id === identifier)) return { kind: 'pending' };\n }\n return null;\n },\n queue: {\n discard(locator: string, identifier: string) {\n return exclusive(() => discardHead(locator, identifier));\n },\n },\n history(locator: string, path: string, query?: HistoryQuery) {\n return readHistory(locator, path, query);\n },\n call(name: string, input: unknown) {\n return invokeAction(name, input);\n },\n log() {\n return journal.export();\n },\n storageLoss() {\n return storageLoss;\n },\n observe(\n topic:\n | 'rooms'\n | 'connection-refusal'\n | 'storage-loss'\n | 'sync-status'\n | 'query'\n | 'queue'\n | 'drafts',\n second: QueryOptions | string | ((value: never) => void),\n third?: (value: never) => void,\n ) {\n if (topic === 'drafts') {\n const notify = second as (value: readonly DraftEntry[]) => void;\n const listener: DraftSubscription = { notify, ready: false };\n draftListeners.add(listener);\n void exclusive(async () => {\n const local = await openLocal();\n await readDrafts(local);\n if (closed || !draftListeners.has(listener)) return;\n listener.ready = true;\n }).then(\n () => {\n if (closed || !listener.ready || !draftListeners.has(listener)) return;\n listener.notify(snapshotDrafts());\n },\n () => {},\n );\n return () => {\n draftListeners.delete(listener);\n };\n }\n if (topic === 'rooms') {\n const notify = second as (value: readonly AppRoom[]) => void;\n roomListeners.add(notify);\n notify(listed());\n return () => {\n roomListeners.delete(notify);\n };\n }\n if (topic === 'connection-refusal') {\n const notify = second as (value: ConnectionRefusal | null) => void;\n refusalListeners.add(notify);\n notify(refusal);\n return () => {\n refusalListeners.delete(notify);\n };\n }\n if (topic === 'storage-loss') {\n const notify = second as (value: string | null) => void;\n storageLossListeners.add(notify);\n notify(storageLoss);\n return () => {\n storageLossListeners.delete(notify);\n };\n }\n if (topic === 'sync-status') {\n const notify = second as (value: SyncStatus) => void;\n statusListeners.add(notify);\n notify(status);\n return () => {\n statusListeners.delete(notify);\n };\n }\n if (topic === 'queue') {\n const queue: QueueSubscription = {\n locator: second as string,\n notify: third as (entries: readonly QueueEntry[]) => void,\n };\n queueSubscriptions.add(queue);\n queue.notify(entriesOf(queue.locator));\n return () => {\n queueSubscriptions.delete(queue);\n };\n }\n const subscription: QuerySubscription = {\n query: second as QueryOptions,\n notify: third as (result: QueryResult) => void,\n };\n const first = visible(subscription.query);\n querySubscriptions.add(subscription);\n subscription.notify(first);\n return () => {\n querySubscriptions.delete(subscription);\n };\n },\n async reauthorize() {\n if (refusal === null || !refusal.reauthorizationOffered) return;\n journal.record('connection reauthorize');\n authorization = undefined;\n discoveryPaused = false;\n await enqueue();\n },\n };\n}\n"],"names":["rawQuery","cached","modelTypes","NO_MODEL","sameModel","ROOM_CONTRACT_VERSION","VERSION_1_CAPABILITIES","bootstrapRoom","MD_MODEL","PRESENTED","validRoot","createLog","queuedOutcome","refused","refreshRoom","buildBatch","applyReturned","readConfirmed","replicaOf","settled","same","saving","STARTING","transferring","detectStorageLoss","nextGeneration","openReplicaStore","unconfirmed","DEFAULT_DISCOVERY_INTERVAL_MS","knownCapabilities","Set","createMdRuntime","options","period","discoveryIntervalMs","authorization","opening","store","replicas","Map","drafts","outcomes","limits","capabilities","rooms","unreadable","models","liveModels","invalidModels","modelEpoch","modelOf","locator","get","mismatchedRoots","refusal","storageLoss","status","discoveryPaused","timer","closed","chain","Promise","resolve","mutations","inflight","queued","roomListeners","refusalListeners","storageLossListeners","statusListeners","querySubscriptions","queueSubscriptions","draftListeners","journal","notifyReady","ready","leader","window","applyingRemote","releaseLeadership","channel","BroadcastChannel","undefined","draftContent","path","rememberDraft","content","room","set","forgetDraft","delete","size","snapshotDrafts","entries","push","structuredClone","sort","left","right","readDrafts","opened","acrossTabs","hydrate","publishDrafts","waitingOnly","value","listener","notify","emitDrafts","releaseWaitingDrafts","commitDraft","work","exclusive","local","openLocal","then","announce","pending","values","some","replica","queue","length","attention","head","id","storedOutcomes","batches","stored","batch","outcome","kind","persistQueue","writeQueue","listed","queryRooms","map","confirmed","record","roomVersion","documents","visible","collection","model","emitRooms","emitRefusal","emitStorageLoss","type","postMessage","adopt","next","moveTo","request","queryBinding","Object","keys","Error","selector","$and","emitVisible","subscription","query","entriesOf","freeze","emitQueue","stopTimer","clearInterval","startTimer","setInterval","enqueue","refuse","reason","revoked","add","all","publish","catch","reauthorizationOffered","list","synchronizationAvailable","name","collectionRoot","operations","attachedModel","providerOwnedPaths","applyDiscovery","discovered","listedLocators","held","selection","admission","has","records","queues","kept","lastCompleted","declared","providerLimits","clear","draft","queuedBatches","persisted","priorModel","snapshot","JSON","stringify","existing","locators","readState","applyRemote","message","attentionRequired","state","open","storedGeneration","generation","loss","rememberGeneration","error","navigator","locks","retained","write","changes","replacing","result","rule","built","baseRoomVersion","binding","modelBinding","slice","consumed","change","append","discardHead","identifier","changed","readHistory","ensureAuthorization","transfer","revision","pageToken","join","adapter","history","scoped","declaredAction","capability","action","actions","invokeAction","input","text","pullRefresh","authorized","detail","pullBootstrap","advance","refreshed","bootstrapped","recordRefusal","affected","commitAccept","submitted","accepted","base","overlay","current","remaining","filter","retainedBase","applied","revisions","removals","author","time","submitRoom","progress","mutate","changeBatch","complete","reachable","from","pulled","committed","retainModel","epoch","previous","heldBefore","queryChanged","types","acquireModel","answer","definitions","verified","verify","verifiedWith","scope","unavailable","read","sync","synchronize","prior","withheld","cycle","discover","supportedVersions","includes","mdModel","identity","version","malformed","every","operation","Array","isArray","required","requiredGuarantees","declare","authorize","connect","completedAt","Date","toISOString","run","startProcessing","signal","close","addEventListener","event","data","once","aborted","syncStatus","replace","keep","discard","save","recorded","call","log","export","observe","topic","second","third","first","reauthorize"],"mappings":"AAAA,SAASA,QAAQ,QAA4C,aAAa;AAC1E,SACEC,MAAM,EACNC,UAAU,EACVC,QAAQ,EACRC,SAAS,QAIJ,aAAa;AAOpB,SACEC,qBAAqB,EACrBC,sBAAsB,QAUjB,eAAe;AACtB,SAASC,aAAa,QAAQ,iBAAiB;AAE/C,SAASC,QAAQ,EAAEC,SAAS,EAAEC,SAAS,QAAqB,kBAAkB;AAC9E,SAASC,SAAS,QAAQ,WAAW;AACrC,SACEC,aAAa,EACbC,OAAO,QAIF,eAAe;AACtB,SAASC,WAAW,QAAQ,eAAe;AAC3C,SAASC,UAAU,QAA0B,YAAY;AACzD,SACEC,aAAa,EACbC,aAAa,EACbC,SAAS,QAGJ,eAAe;AACtB,SACEC,OAAO,EACPC,IAAI,EACJC,MAAM,EACNC,QAAQ,EACRC,YAAY,QAGP,cAAc;AACrB,SAASC,iBAAiB,EAAEC,cAAc,QAAQ,kBAAkB;AACpE,SAASC,gBAAgB,QAA2B,aAAa;AACjE,SAASC,WAAW,QAA0B,gBAAgB;AAE9D,MAAMC,gCAAgC;AAEtC,MAAMC,oBAAoB,IAAIC,IAAYxB;AA+G1C,OAAO,SAASyB,gBAAgBC,OAAyB;IACvD,MAAMC,SAASD,QAAQE,mBAAmB,IAAIN;IAC9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gBACzBA,OAAOpD;gBACP,OAAO;oBACLa,qBAAqBsB,MAAM,CAACiB;gBAC9B;YACF;YACA,IAAI6O,UAAU,eAAe;gBAC3B,MAAM7O,SAAS8O;gBACfpR,gBAAgBwG,GAAG,CAAClE;gBACpBA,OAAOnD;gBACP,OAAO;oBACLa,gBAAgBqB,MAAM,CAACiB;gBACzB;YACF;YACA,IAAI6O,UAAU,SAAS;gBACrB,MAAM/N,QAA2B;oBAC/BtE,SAASsS;oBACT9O,QAAQ+O;gBACV;gBACAnR,mBAAmBsG,GAAG,CAACpD;gBACvBA,MAAMd,MAAM,CAACuD,UAAUzC,MAAMtE,OAAO;gBACpC,OAAO;oBACLoB,mBAAmBmB,MAAM,CAAC+B;gBAC5B;YACF;YACA,MAAMuC,eAAkC;gBACtCC,OAAOwL;gBACP9O,QAAQ+O;YACV;YACA,MAAMC,QAAQ9M,QAAQmB,aAAaC,KAAK;YACxC3F,mBAAmBuG,GAAG,CAACb;YACvBA,aAAarD,MAAM,CAACgP;YACpB,OAAO;gBACLrR,mBAAmBoB,MAAM,CAACsE;YAC5B;QACF;QACA,MAAM4L;YACJ,IAAItS,YAAY,QAAQ,CAACA,QAAQ2H,sBAAsB,EAAE;YACzDxG,QAAQiE,MAAM,CAAC;YACfvG,gBAAgB+C;YAChBzB,kBAAkB;YAClB,MAAMgH;QACR;IACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/durability.ts"],"sourcesContent":["const ASKED = 'mdruntime:persistent-storage';\nconst GENERATION = 'mdruntime:generation';\n\nconst STORAGE_LOSS_STATEMENT = 'Unsynchronized Drafts and Pending Changes were lost.';\n\nfunction remembered(): string | null {\n try {\n return window.localStorage.getItem(ASKED);\n } catch {\n return null;\n }\n}\n\nfunction remember(): void {\n try {\n window.localStorage.setItem(ASKED, '1');\n } catch {\n return;\n }\n}\n\nasync function ask(): Promise<void> {\n if (remembered() !== null) return;\n const persist = window.navigator.storage?.persist;\n if (typeof persist !== 'function') return;\n remember();\n try {\n await persist.call(window.navigator.storage);\n } catch {\n return;\n }\n}\n\nexport async function requestPersistentStorage(): Promise<void> {\n if (typeof window === 'undefined') return;\n await window.navigator.locks.request('mdruntime-persist', ask);\n}\n\nfunction readGeneration(): string | null {\n if (typeof window === 'undefined') return null;\n try {\n return window.localStorage.getItem(GENERATION);\n } catch {\n return null;\n }\n}\n\nfunction writeGeneration(value: string): void {\n if (typeof window === 'undefined') return;\n try {\n window.localStorage.setItem(GENERATION, value);\n } catch {\n return;\n }\n}\n\nexport function detectStorageLoss(stored: string | null): string | null {\n const remembered = readGeneration();\n if (remembered === null || remembered === stored) return null;\n return STORAGE_LOSS_STATEMENT;\n}\n\nexport function nextGeneration(stored: string | null): string {\n const remembered = readGeneration();\n if (stored !== null && (remembered === null || remembered === stored)) {\n writeGeneration(stored);\n return stored;\n }\n const next = crypto.randomUUID();\n writeGeneration(next);\n return next;\n}\n"],"names":["ASKED","GENERATION","STORAGE_LOSS_STATEMENT","remembered","window","localStorage","getItem","remember","setItem","ask","persist","navigator","storage","call","requestPersistentStorage","locks","request","readGeneration","writeGeneration","value","detectStorageLoss","stored","nextGeneration","next","crypto","randomUUID"],"mappings":"AAAA,MAAMA,QAAQ;AACd,MAAMC,aAAa;AAEnB,MAAMC,yBAAyB;AAE/B,SAASC;IACP,IAAI;QACF,OAAOC,OAAOC,YAAY,CAACC,OAAO,CAACN;IACrC,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA,SAASO;IACP,IAAI;QACFH,OAAOC,YAAY,CAACG,OAAO,CAACR,OAAO;IACrC,EAAE,OAAM;QACN;IACF;AACF;AAEA,eAAeS;IACb,IAAIN,iBAAiB,MAAM;IAC3B,MAAMO,UAAUN,OAAOO,SAAS,CAACC,OAAO,EAAEF;IAC1C,IAAI,OAAOA,YAAY,YAAY;IACnCH;IACA,IAAI;QACF,MAAMG,QAAQG,IAAI,CAACT,OAAOO,SAAS,CAACC,OAAO;IAC7C,EAAE,OAAM;QACN;IACF;AACF;AAEA,OAAO,eAAeE;IACpB,IAAI,OAAOV,WAAW,aAAa;IACnC,MAAMA,OAAOO,SAAS,CAACI,KAAK,CAACC,OAAO,CAAC,qBAAqBP;AAC5D;AAEA,SAASQ;IACP,IAAI,OAAOb,WAAW,aAAa,OAAO;IAC1C,IAAI;QACF,OAAOA,OAAOC,YAAY,CAACC,OAAO,CAACL;IACrC,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA,SAASiB,gBAAgBC,KAAa;IACpC,IAAI,OAAOf,WAAW,aAAa;IACnC,IAAI;QACFA,OAAOC,YAAY,CAACG,OAAO,CAACP,YAAYkB;IAC1C,EAAE,OAAM;QACN;IACF;AACF;AAEA,OAAO,SAASC,kBAAkBC,MAAqB;IACrD,MAAMlB,aAAac;IACnB,IAAId,eAAe,QAAQA,eAAekB,QAAQ,OAAO;IACzD,OAAOnB;AACT;AAEA,OAAO,SAASoB,eAAeD,MAAqB;IAClD,MAAMlB,aAAac;IACnB,IAAII,WAAW,QAASlB,CAAAA,eAAe,QAAQA,eAAekB,MAAK,GAAI;QACrEH,gBAAgBG;QAChB,OAAOA;IACT;IACA,MAAME,OAAOC,OAAOC,UAAU;IAC9BP,gBAAgBK;IAChB,OAAOA;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/identity.ts"],"sourcesContent":["export function changeBatchIdentity(at: number = Date.now()): string {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n const time = BigInt(at);\n for (let index = 0; index < 6; index += 1) {\n bytes[index] = Number((time >> BigInt(8 * (5 - index))) & 0xffn);\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x70;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n"],"names":["changeBatchIdentity","at","Date","now","bytes","Uint8Array","crypto","getRandomValues","time","BigInt","index","Number","hex","map","byte","toString","padStart","join","slice"],"mappings":"AAAA,OAAO,SAASA,oBAAoBC,KAAaC,KAAKC,GAAG,EAAE;IACzD,MAAMC,QAAQ,IAAIC,WAAW;IAC7BC,OAAOC,eAAe,CAACH;IACvB,MAAMI,OAAOC,OAAOR;IACpB,IAAK,IAAIS,QAAQ,GAAGA,QAAQ,GAAGA,SAAS,EAAG;QACzCN,KAAK,CAACM,MAAM,GAAGC,OAAO,AAACH,QAAQC,OAAO,IAAK,CAAA,IAAIC,KAAI,KAAO,KAAK;IACjE;IACAN,KAAK,CAAC,EAAE,GAAG,AAACA,KAAK,CAAC,EAAE,GAAG,OAAQ;IAC/BA,KAAK,CAAC,EAAE,GAAG,AAACA,KAAK,CAAC,EAAE,GAAG,OAAQ;IAC/B,MAAMQ,MAAM;WAAIR;KAAM,CAACS,GAAG,CAAC,CAACC,OAASA,KAAKC,QAAQ,CAAC,IAAIC,QAAQ,CAAC,GAAG,MAAMC,IAAI,CAAC;IAC9E,OAAO,GAAGL,IAAIM,KAAK,CAAC,GAAG,GAAG,CAAC,EAAEN,IAAIM,KAAK,CAAC,GAAG,IAAI,CAAC,EAAEN,IAAIM,KAAK,CAAC,IAAI,IAAI,CAAC,EAAEN,IAAIM,KAAK,CAAC,IAAI,IAAI,CAAC,EAAEN,IAAIM,KAAK,CAAC,KAAK;AAC5G"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/index.ts"],"sourcesContent":["export type {\n ActionDeclaration,\n ActionRequest,\n ActionResult,\n Adapter,\n AdapterFailure,\n Authorization,\n BootstrapPage,\n BootstrapRequest,\n BootstrapResult,\n Capability,\n DiscoverResult,\n DiscoveredRoom,\n Discovery,\n HistoryRequest,\n HistoryResult,\n HistoryRetention,\n HistoryRevision,\n MdModelIdentity,\n MutationRequest,\n MutationResult,\n PageToken,\n ProviderLimit,\n RefreshPage,\n RefreshRequest,\n RefreshResult,\n Retention,\n RevokedAuthorization,\n RoomNotReadable,\n TransportUncertainty,\n} from './adapter.js';\nexport type { Change, ChangeBatch, Precondition } from './change.js';\nexport type { MdType } from './collection.js';\nexport type {\n AppRoom,\n CallResult,\n ConnectionRefusal,\n ConnectionRefusalReason,\n DraftEntry,\n DraftSurface,\n HistoryQuery,\n MdRuntime,\n MdRuntimeOptions,\n QueueSurface,\n SaveResult,\n} from './connection.js';\nexport type {\n AcceptedOutcome,\n AffectedState,\n QueueEntry,\n QueueOutcome,\n SubmissionOutcome,\n} from './outcome.js';\nexport type { SaveRefusal } from './save.js';\nexport { createMdRuntime } from './connection.js';\nexport type { SyncStatus } from './status.js';\nexport type {\n Backlink,\n QueryDocument,\n QueryGroup,\n QueryOptions,\n QueryResult,\n Selector,\n} from '@agentshouse/query';\n\nexport type {\n AttachedModelBinding,\n ModelIdentity,\n ModelSnapshot,\n ModelState,\n ModelResult,\n ModelValidation,\n TypesResult,\n ValidationReceipt,\n} from './model.js';\nexport type { OperationScopes, ReplicaAdmission, ScopedRefusal } from './adapter.js';\nexport type { QueryBinding, QueryInput } from './query.js';\n"],"names":["createMdRuntime"],"mappings":"AAsDA,SAASA,eAAe,QAAQ,kBAAkB"}
package/dist/log.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/log.ts"],"sourcesContent":["const BOUND = 256;\n\nexport function createLog() {\n const events: string[] = [];\n return {\n record(event: string) {\n events.push(event);\n if (events.length > BOUND) events.splice(0, events.length - BOUND);\n },\n export() {\n return events.join('\\n');\n },\n };\n}\n"],"names":["BOUND","createLog","events","record","event","push","length","splice","export","join"],"mappings":"AAAA,MAAMA,QAAQ;AAEd,OAAO,SAASC;IACd,MAAMC,SAAmB,EAAE;IAC3B,OAAO;QACLC,QAAOC,KAAa;YAClBF,OAAOG,IAAI,CAACD;YACZ,IAAIF,OAAOI,MAAM,GAAGN,OAAOE,OAAOK,MAAM,CAAC,GAAGL,OAAOI,MAAM,GAAGN;QAC9D;QACAQ;YACE,OAAON,OAAOO,IAAI,CAAC;QACrB;IACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/memory.ts"],"sourcesContent":["import type { ModelResult } from './model.js';\nimport {\n ROOM_CONTRACT_VERSION,\n type ActionRequest,\n type ActionResult,\n type Adapter,\n type Authorization,\n type BootstrapRequest,\n type BootstrapResult,\n type Capability,\n type DiscoverResult,\n type DiscoveredRoom,\n type HistoryRequest,\n type HistoryResult,\n type MdModelIdentity,\n type MutationRequest,\n type MutationResult,\n type ProviderLimit,\n type RefreshRequest,\n type RefreshResult,\n type Retention,\n} from './adapter.js';\nimport { MD_MODEL } from './collection.js';\n\nconst FIXTURE_RETENTION: Retention = {\n history: { kind: 'duration', seconds: 1 },\n outcome: 1,\n refreshHorizon: 1,\n};\n\nfunction declaredRetention(value: Retention | undefined): Retention {\n const retention = value ?? FIXTURE_RETENTION;\n if (retention.history.kind === 'no-declared-time-bound') return retention;\n if (Number.isFinite(retention.history.seconds) && retention.history.seconds > 0) {\n return retention;\n }\n throw new Error('history retention duration must be a finite positive number of seconds');\n}\n\nexport type MemoryRoom = DiscoveredRoom & {\n model?: ModelResult;\n documents?: Readonly<Record<string, string>>;\n revisions?: Readonly<Record<string, string>>;\n binaryTargets?: readonly string[];\n};\n\nexport type MemoryAdapterOptions = {\n rooms?: readonly MemoryRoom[];\n pageSize?: number;\n mdModel?: MdModelIdentity;\n supportedVersions?: readonly number[];\n capabilities?: readonly Capability[];\n providerLimits?: readonly ProviderLimit[];\n retention?: Retention;\n origins?: readonly string[];\n};\n\nexport type MemoryAdapter = Adapter & {\n setRooms(rooms: readonly MemoryRoom[]): void;\n script(operation: keyof Adapter, answer: unknown): void;\n};\n\ntype Script<T, R> = T | ((request: R) => T | Promise<T>);\n\ntype RefreshContinuation = {\n room: MemoryRoom;\n from: MemoryRoom;\n at: number;\n};\n\nfunction named(\n source: Readonly<Record<string, string>>,\n paths: readonly string[],\n): Readonly<Record<string, string>> {\n const taken: Record<string, string> = {};\n for (const path of paths) {\n const value = source[path];\n if (value !== undefined) taken[path] = value;\n }\n return taken;\n}\n\nasync function resolveScript<T, R>(\n answer: Script<T, R> | undefined,\n fallback: () => T | Promise<T>,\n request: R,\n) {\n if (answer === undefined) return fallback();\n return typeof answer === 'function' ? (answer as (value: R) => T | Promise<T>)(request) : answer;\n}\n\nexport function createMemoryAdapter(options: MemoryAdapterOptions = {}): MemoryAdapter {\n let rooms = options.rooms === undefined ? [] : [...options.rooms];\n const mdModel = options.mdModel ?? MD_MODEL;\n const supportedVersions = options.supportedVersions ?? [ROOM_CONTRACT_VERSION];\n const capabilities = options.capabilities ?? [];\n const providerLimits = options.providerLimits ?? [];\n const retention = declaredRetention(options.retention);\n const origins = options.origins ?? ['https://origin.example'];\n const pageSize = options.pageSize;\n const scripts: Partial<Record<keyof Adapter, unknown>> = {};\n const served = new Map<string, Map<string, MemoryRoom>>();\n const refreshPages = new Map<string, RefreshContinuation>();\n\n function retain(entries: readonly MemoryRoom[]) {\n for (const room of entries) {\n const versions = served.get(room.locator) ?? new Map<string, MemoryRoom>();\n versions.set(room.roomVersion, room);\n served.set(room.locator, versions);\n }\n }\n\n retain(rooms);\n\n function declared(room: MemoryRoom): DiscoveredRoom {\n return {\n name: room.name,\n locator: room.locator,\n collectionRoot: room.collectionRoot,\n roomVersion: room.roomVersion,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n providerOwnedPaths: room.providerOwnedPaths,\n };\n }\n\n function page(room: MemoryRoom, from: number): BootstrapResult {\n const paths = Object.keys(room.documents ?? {}).sort();\n const size = pageSize ?? paths.length;\n const taken = paths.slice(from, from + size);\n const next = from + taken.length;\n return {\n kind: 'bootstrap',\n roomVersion: room.roomVersion,\n documents: named(room.documents ?? {}, taken),\n revisions: named(room.revisions ?? {}, taken),\n binaryTargets: from === 0 ? (room.binaryTargets ?? []) : [],\n ...(next < paths.length ? { pageToken: String(next) } : {}),\n };\n }\n\n function advancement(room: MemoryRoom, from: MemoryRoom, at: number): RefreshResult {\n const current = room.documents ?? {};\n const previous = from.documents ?? {};\n const currentTargets = new Set(room.binaryTargets ?? []);\n const previousTargets = new Set(from.binaryTargets ?? []);\n const changed = Object.keys(current)\n .filter((path) => current[path] !== previous[path])\n .sort();\n const size = pageSize ?? changed.length;\n const taken = changed.slice(at, at + size);\n const next = at + taken.length;\n const opening = at === 0;\n const pageToken = next < changed.length ? `refresh-${refreshPages.size}` : undefined;\n if (pageToken !== undefined) refreshPages.set(pageToken, { room, from, at: next });\n return {\n kind: 'net-advancement',\n roomVersion: room.roomVersion,\n documents: named(current, taken),\n revisions: named(room.revisions ?? {}, taken),\n binaryTargets: opening\n ? [...currentTargets].filter((target) => !previousTargets.has(target))\n : [],\n removals: opening\n ? [\n ...Object.keys(previous).filter(\n (path) => !(path in current) && !currentTargets.has(path),\n ),\n ...[...previousTargets].filter(\n (target) => !currentTargets.has(target) && !(target in current),\n ),\n ].sort()\n : [],\n ...(pageToken === undefined ? {} : { pageToken }),\n };\n }\n\n function discovery(): DiscoverResult {\n return {\n kind: 'discovery',\n supportedVersions,\n mdModel,\n rooms: rooms.map(declared),\n capabilities,\n providerLimits,\n retention,\n origins,\n };\n }\n\n return {\n setRooms(next) {\n rooms = [...next];\n retain(rooms);\n },\n script(operation, answer) {\n if (answer === undefined) delete scripts[operation];\n else scripts[operation] = answer;\n },\n async model(_authorization, request) {\n return resolveScript(\n scripts.model as Script<ModelResult, typeof request> | undefined,\n () =>\n rooms.find((room) => room.locator === request.locator)?.model ?? {\n kind: 'model-unavailable',\n reason: 'not-readable',\n },\n request,\n );\n },\n async authorize() {\n return resolveScript<Authorization, void>(\n scripts.authorize as Script<Authorization, void> | undefined,\n () => ({}),\n undefined,\n );\n },\n async discover(_authorization: Authorization) {\n return resolveScript<DiscoverResult, void>(\n scripts.discover as Script<DiscoverResult, void> | undefined,\n discovery,\n undefined,\n );\n },\n async bootstrap(_authorization: Authorization, request: BootstrapRequest) {\n return resolveScript<BootstrapResult, BootstrapRequest>(\n scripts.bootstrap as Script<BootstrapResult, BootstrapRequest> | undefined,\n () => {\n const room = rooms.find((entry) => entry.locator === request.locator);\n if (room === undefined) {\n return { kind: 'room-not-readable', locator: request.locator };\n }\n return page(room, request.pageToken === undefined ? 0 : Number(request.pageToken));\n },\n request,\n );\n },\n async refresh(_authorization: Authorization, request: RefreshRequest) {\n return resolveScript<RefreshResult, RefreshRequest>(\n scripts.refresh as Script<RefreshResult, RefreshRequest> | undefined,\n () => {\n const room = rooms.find((entry) => entry.locator === request.locator);\n if (room === undefined) {\n return { kind: 'room-not-readable', locator: request.locator };\n }\n if (request.pageToken !== undefined) {\n const continuation = refreshPages.get(request.pageToken);\n if (\n continuation === undefined ||\n continuation.room.locator !== request.locator ||\n continuation.from.roomVersion !== request.fromRoomVersion\n ) {\n throw new Error('Invalid Refresh Page Token');\n }\n return advancement(continuation.room, continuation.from, continuation.at);\n }\n if (request.fromRoomVersion === room.roomVersion) {\n return { kind: 'still-current' };\n }\n const from = served.get(room.locator)?.get(request.fromRoomVersion);\n if (from === undefined) return { kind: 'beyond-horizon' };\n return advancement(room, from, 0);\n },\n request,\n );\n },\n async mutate(_authorization: Authorization, request: MutationRequest) {\n return resolveScript<MutationResult, MutationRequest>(\n scripts.mutate as Script<MutationResult, MutationRequest> | undefined,\n () => {\n const room = rooms.find((entry) => entry.locator === request.locator);\n if (room === undefined) {\n return { kind: 'room-not-readable', locator: request.locator };\n }\n return { kind: 'rejected', text: '', affected: {} };\n },\n request,\n );\n },\n async history(_authorization: Authorization, request: HistoryRequest) {\n return resolveScript<HistoryResult, HistoryRequest>(\n scripts.history as Script<HistoryResult, HistoryRequest> | undefined,\n () => {\n const room = rooms.find((entry) => entry.locator === request.locator);\n if (room === undefined) {\n return { kind: 'room-not-readable', locator: request.locator };\n }\n return {\n kind: 'history',\n revisions: [],\n };\n },\n request,\n );\n },\n async action(_authorization: Authorization, request: ActionRequest) {\n return resolveScript<ActionResult, ActionRequest>(\n scripts.action as Script<ActionResult, ActionRequest> | undefined,\n () => ({\n kind: 'rejected',\n text: '',\n }),\n request,\n );\n },\n };\n}\n"],"names":["ROOM_CONTRACT_VERSION","MD_MODEL","FIXTURE_RETENTION","history","kind","seconds","outcome","refreshHorizon","declaredRetention","value","retention","Number","isFinite","Error","named","source","paths","taken","path","undefined","resolveScript","answer","fallback","request","createMemoryAdapter","options","rooms","mdModel","supportedVersions","capabilities","providerLimits","origins","pageSize","scripts","served","Map","refreshPages","retain","entries","room","versions","get","locator","set","roomVersion","declared","name","collectionRoot","operations","replica","attachedModel","providerOwnedPaths","page","from","Object","keys","documents","sort","size","length","slice","next","revisions","binaryTargets","pageToken","String","advancement","at","current","previous","currentTargets","Set","previousTargets","changed","filter","opening","target","has","removals","discovery","map","setRooms","script","operation","model","_authorization","find","reason","authorize","discover","bootstrap","entry","refresh","continuation","fromRoomVersion","mutate","text","affected","action"],"mappings":"AACA,SACEA,qBAAqB,QAmBhB,eAAe;AACtB,SAASC,QAAQ,QAAQ,kBAAkB;AAE3C,MAAMC,oBAA+B;IACnCC,SAAS;QAAEC,MAAM;QAAYC,SAAS;IAAE;IACxCC,SAAS;IACTC,gBAAgB;AAClB;AAEA,SAASC,kBAAkBC,KAA4B;IACrD,MAAMC,YAAYD,SAASP;IAC3B,IAAIQ,UAAUP,OAAO,CAACC,IAAI,KAAK,0BAA0B,OAAOM;IAChE,IAAIC,OAAOC,QAAQ,CAACF,UAAUP,OAAO,CAACE,OAAO,KAAKK,UAAUP,OAAO,CAACE,OAAO,GAAG,GAAG;QAC/E,OAAOK;IACT;IACA,MAAM,IAAIG,MAAM;AAClB;AAiCA,SAASC,MACPC,MAAwC,EACxCC,KAAwB;IAExB,MAAMC,QAAgC,CAAC;IACvC,KAAK,MAAMC,QAAQF,MAAO;QACxB,MAAMP,QAAQM,MAAM,CAACG,KAAK;QAC1B,IAAIT,UAAUU,WAA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,EACd,IAAO,CAAA;oBACL9F,MAAM;oBACN4F,MAAM;gBACR,CAAA,GACAzE;QAEJ;IACF;AACF"}
package/dist/model.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/model.ts"],"sourcesContent":["import type { Validation } from '@agentshouse/mdmodel';\nimport type { MdType } from './collection.js';\n\nexport type ModelIdentity = { identity: string; version: string };\nexport type ModelSnapshot = ModelIdentity & { definitions: Readonly<Record<string, string>> };\nexport type ModelUnavailableReason =\n | 'not-readable'\n | 'revoked'\n | 'not-acquired'\n | 'version-changed'\n | 'invalid'\n | 'binding-unavailable';\nexport type ModelResult =\n | { kind: 'model'; snapshot: ModelSnapshot }\n | { kind: 'model-unavailable'; reason: ModelUnavailableReason }\n | { kind: 'transport-uncertainty' }\n | { kind: 'revoked-authorization' };\nexport type ModelState =\n | { status: 'unavailable'; reason: ModelUnavailableReason }\n | {\n status: 'current' | 'cached';\n snapshot: ModelSnapshot;\n verifiedWith: ModelIdentity;\n types: readonly MdType[];\n };\nexport type TypesResult =\n | { status: 'unavailable'; reason: ModelUnavailableReason }\n | {\n status: 'current' | 'cached';\n identity: string;\n version: string;\n verifiedWith: ModelIdentity;\n types: readonly MdType[];\n };\nexport type ModelValidation =\n | { verdict: 'accept' }\n | (Extract<Validation, { verdict: 'refuse' }> & { source: 'content' | 'model' });\nexport type AttachedModelBinding = {\n verify(\n snapshot: ModelSnapshot,\n ): { kind: 'verified'; types: readonly MdType[] } | { kind: 'invalid' };\n validate(input: {\n model: ModelSnapshot;\n documents: Readonly<Record<string, string>>;\n binaryTargets: readonly string[];\n }): ModelValidation;\n};\nexport type ValidationReceipt = { identity: string; version: string; source: 'current' | 'cached' };\nexport const NO_MODEL: ModelState = { status: 'unavailable', reason: 'not-acquired' };\nexport function modelTypes(state: ModelState): TypesResult {\n return state.status === 'unavailable'\n ? { ...state }\n : {\n status: state.status,\n identity: state.snapshot.identity,\n version: state.snapshot.version,\n verifiedWith: { ...state.verifiedWith },\n types: structuredClone(state.types),\n };\n}\nexport function cached(state: ModelState): ModelState {\n return state.status === 'unavailable' ? state : { ...state, status: 'cached' };\n}\nexport function sameModel(left: ModelIdentity, right: ModelIdentity): boolean {\n return left.identity === right.identity && left.version === right.version;\n}\n"],"names":["NO_MODEL","status","reason","modelTypes","state","identity","snapshot","version","verifiedWith","types","structuredClone","cached","sameModel","left","right"],"mappings":"AAgDA,OAAO,MAAMA,WAAuB;IAAEC,QAAQ;IAAeC,QAAQ;AAAe,EAAE;AACtF,OAAO,SAASC,WAAWC,KAAiB;IAC1C,OAAOA,MAAMH,MAAM,KAAK,gBACpB;QAAE,GAAGG,KAAK;IAAC,IACX;QACEH,QAAQG,MAAMH,MAAM;QACpBI,UAAUD,MAAME,QAAQ,CAACD,QAAQ;QACjCE,SAASH,MAAME,QAAQ,CAACC,OAAO;QAC/BC,cAAc;YAAE,GAAGJ,MAAMI,YAAY;QAAC;QACtCC,OAAOC,gBAAgBN,MAAMK,KAAK;IACpC;AACN;AACA,OAAO,SAASE,OAAOP,KAAiB;IACtC,OAAOA,MAAMH,MAAM,KAAK,gBAAgBG,QAAQ;QAAE,GAAGA,KAAK;QAAEH,QAAQ;IAAS;AAC/E;AACA,OAAO,SAASW,UAAUC,IAAmB,EAAEC,KAAoB;IACjE,OAAOD,KAAKR,QAAQ,KAAKS,MAAMT,QAAQ,IAAIQ,KAAKN,OAAO,KAAKO,MAAMP,OAAO;AAC3E"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/outcome.ts"],"sourcesContent":["import type { ChangeBatch } from './change.js';\n\nexport type AffectedState = Readonly<Record<string, string>>;\n\nexport type QueueOutcome =\n | { kind: 'pending' }\n | {\n kind: 'conflicted';\n roomVersion: string;\n affected: AffectedState;\n text: string;\n }\n | {\n kind: 'rejected';\n affected: AffectedState;\n text: string;\n }\n | { kind: 'expired' };\n\nexport type AcceptedOutcome = {\n kind: 'accepted';\n roomVersion: string;\n author: string;\n time: string;\n};\n\nexport type SubmissionOutcome = QueueOutcome | AcceptedOutcome;\n\nexport type QueueEntry = {\n readonly batch: ChangeBatch;\n readonly outcome: QueueOutcome;\n};\n\nexport function refused(outcome: SubmissionOutcome | undefined): boolean {\n return (\n outcome?.kind === 'conflicted' || outcome?.kind === 'rejected' || outcome?.kind === 'expired'\n );\n}\n\nexport function queuedOutcome(outcome: SubmissionOutcome | undefined): QueueOutcome {\n if (outcome === undefined || outcome.kind === 'accepted' || outcome.kind === 'pending') {\n return { kind: 'pending' };\n }\n return outcome;\n}\n"],"names":["refused","outcome","kind","queuedOutcome","undefined"],"mappings":"AAiCA,OAAO,SAASA,QAAQC,OAAsC;IAC5D,OACEA,SAASC,SAAS,gBAAgBD,SAASC,SAAS,cAAcD,SAASC,SAAS;AAExF;AAEA,OAAO,SAASC,cAAcF,OAAsC;IAClE,IAAIA,YAAYG,aAAaH,QAAQC,IAAI,KAAK,cAAcD,QAAQC,IAAI,KAAK,WAAW;QACtF,OAAO;YAAEA,MAAM;QAAU;IAC3B;IACA,OAAOD;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/overlay.ts"],"sourcesContent":["import { apply, parse, serialize, type Document } from '@agentshouse/mdmodel';\nimport type { Change, ChangeBatch, Precondition } from './change.js';\n\nexport type Layer = {\n documents: Readonly<Record<string, string>>;\n binaryTargets: readonly string[];\n revisions: Readonly<Record<string, string>>;\n};\n\ntype Staged = {\n documents: Record<string, string>;\n binaryTargets: Set<string>;\n revisions: Record<string, string>;\n};\n\ntype Priors = {\n field(path: string, name: string): unknown;\n section(path: string, name: string): string;\n preamble(path: string): string;\n};\n\nconst EMPTY_FRONTMATTER = '---\\n---\\n';\n\nfunction at(path: string, name: string) {\n return `${path} ${name}`;\n}\n\nfunction priorsOf(preconditions: readonly Precondition[]): Priors {\n const fields = new Map<string, unknown>();\n const sections = new Map<string, string>();\n const preambles = new Map<string, string>();\n for (const precondition of preconditions) {\n if (precondition.kind === 'field') {\n fields.set(at(precondition.path, precondition.name), precondition.value);\n }\n if (precondition.kind === 'section') {\n sections.set(at(precondition.path, precondition.name), precondition.value);\n }\n if (precondition.kind === 'preamble') {\n preambles.set(precondition.path, precondition.value);\n }\n }\n return {\n field: (path, name) => fields.get(at(path, name)),\n section: (path, name) => sections.get(at(path, name)) ?? '',\n preamble: (path) => preambles.get(path) ?? '',\n };\n}\n\nfunction compose(\n fields: Readonly<Record<string, unknown>>,\n sections: Readonly<Record<string, string>>,\n): string {\n const body = Object.entries(sections)\n .map(([name, value]) => `\\n## ${name}\\n${value}`)\n .join('');\n const skeleton = `${EMPTY_FRONTMATTER}${body}`;\n const opened = parse(skeleton);\n if (!opened.ok) return skeleton;\n let document: Document = opened.document;\n for (const [name, value] of Object.entries(fields)) {\n const next = apply(document, { kind: 'field', name, value, prior: undefined });\n if (next.outcome === 'applied') document = next.document;\n }\n return serialize(document);\n}\n\nfunction edited(document: Document, change: Change, priors: Priors) {\n if (change.kind === 'field') {\n return apply(document, {\n kind: 'field',\n name: change.name,\n value: change.value,\n prior: priors.field(change.path, change.name),\n });\n }\n if (change.kind === 'preamble') {\n return apply(document, {\n kind: 'preamble',\n value: change.value,\n prior: priors.preamble(change.path),\n });\n }\n if (change.kind !== 'section') return null;\n return apply(document, {\n kind: 'section',\n name: change.name,\n value: change.value,\n prior: priors.section(change.path, change.name),\n });\n}\n\nfunction edit(staged: Staged, change: Change, priors: Priors) {\n const text = staged.documents[change.path];\n if (text === undefined) return;\n const parsed = parse(text, change.path);\n if (!parsed.ok) return;\n const next = edited(parsed.document, change, priors);\n if (next?.outcome === 'applied') staged.documents[change.path] = serialize(next.document);\n}\n\nfunction relocate(staged: Staged, from: string, to: string) {\n const text = staged.documents[from];\n if (text !== undefined) {\n delete staged.documents[from];\n staged.documents[to] = text;\n } else if (staged.binaryTargets.delete(from)) {\n staged.binaryTargets.add(to);\n } else {\n return;\n }\n const revision = staged.revisions[from];\n if (revision === undefined) return;\n delete staged.revisions[from];\n staged.revisions[to] = revision;\n}\n\nfunction erase(staged: Staged, path: string) {\n delete staged.documents[path];\n delete staged.revisions[path];\n staged.binaryTargets.delete(path);\n}\n\nfunction stage(staged: Staged, change: Change, priors: Priors) {\n if (change.kind === 'field' || change.kind === 'section' || change.kind === 'preamble') {\n edit(staged, change, priors);\n return;\n }\n if (change.kind === 'create') {\n staged.documents[change.path] = compose(change.fields, change.sections);\n return;\n }\n if (change.kind === 'replace') {\n if (staged.documents[change.path] === undefined) return;\n staged.documents[change.path] = change.content;\n return;\n }\n if (change.kind === 'move') {\n relocate(staged, change.path, change.to);\n return;\n }\n erase(staged, change.path);\n}\n\nexport function overlay(base: Layer, queue: readonly ChangeBatch[]): Layer {\n const staged: Staged = {\n documents: { ...base.documents },\n binaryTargets: new Set(base.binaryTargets),\n revisions: { ...base.revisions },\n };\n for (const batch of queue) {\n const priors = priorsOf(batch.preconditions);\n for (const change of batch.changes) stage(staged, change, priors);\n }\n return {\n documents: staged.documents,\n binaryTargets: [...staged.binaryTargets].sort(),\n revisions: staged.revisions,\n };\n}\n"],"names":["apply","parse","serialize","EMPTY_FRONTMATTER","at","path","name","priorsOf","preconditions","fields","Map","sections","preambles","precondition","kind","set","value","field","get","section","preamble","compose","body","Object","entries","map","join","skeleton","opened","ok","document","next","prior","undefined","outcome","edited","change","priors","edit","staged","text","documents","parsed","relocate","from","to","binaryTargets","delete","add","revision","revisions","erase","stage","content","overlay","base","queue","Set","batch","changes","sort"],"mappings":"AAAA,SAASA,KAAK,EAAEC,KAAK,EAAEC,SAAS,QAAuB,uBAAuB;AAqB9E,MAAMC,oBAAoB;AAE1B,SAASC,GAAGC,IAAY,EAAEC,IAAY;IACpC,OAAO,GAAGD,KAAK,CAAC,EAAEC,MAAM;AAC1B;AAEA,SAASC,SAASC,aAAsC;IACtD,MAAMC,SAAS,IAAIC;IACnB,MAAMC,WAAW,IAAID;IACrB,MAAME,YAAY,IAAIF;IACtB,KAAK,MAAMG,gBAAgBL,cAA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iB;QACrBE,WAAW;YAAE,GAAGc,KAAKd,SAAS;QAAC;QAC/BK,eAAe,IAAIW,IAAIF,KAAKT,aAAa;QACzCI,WAAW;YAAE,GAAGK,KAAKL,SAAS;QAAC;IACjC;IACA,KAAK,MAAMQ,SAASF,MAAO;QACzB,MAAMnB,SAAS9B,SAASmD,MAAMlD,aAAa;QAC3C,KAAK,MAAM4B,UAAUsB,MAAMC,OAAO,CAAEP,MAAMb,QAAQH,QAAQC;IAC5D;IACA,OAAO;QACLI,WAAWF,OAAOE,SAAS;QAC3BK,eAAe;eAAIP,OAAOO,aAAa;SAAC,CAACc,IAAI;QAC7CV,WAAWX,OAAOW,SAAS;IAC7B;AACF"}
package/dist/paths.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/paths.ts"],"sourcesContent":["function dirname(path: string): string {\n const index = path.lastIndexOf('/');\n return index === -1 ? '' : path.slice(0, index);\n}\n\nexport function normalize(path: string): string | null {\n const parts: string[] = [];\n for (const part of path.split('/')) {\n if (part === '' || part === '.') continue;\n if (part === '..') {\n if (parts.length === 0) return null;\n parts.pop();\n continue;\n }\n parts.push(part);\n }\n return parts.join('/');\n}\n\nexport function resolve(from: string, reference: string): string | null {\n const base = dirname(from);\n return normalize(base === '' ? reference : `${base}/${reference}`);\n}\n\nexport function relative(from: string, target: string): string {\n const base = dirname(from)\n .split('/')\n .filter((part) => part !== '');\n const parts = target.split('/');\n let shared = 0;\n while (shared < base.length && shared + 1 < parts.length && base[shared] === parts[shared]) {\n shared += 1;\n }\n const up = Array.from({ length: base.length - shared }, () => '..');\n return [...up, ...parts.slice(shared)].join('/');\n}\n\nexport function beneath(prefix: string, path: string): boolean {\n return path === prefix || path.startsWith(`${prefix}/`);\n}\n\nexport function covered(prefixes: readonly string[], path: string): boolean {\n return prefixes.some((prefix) => {\n const normalized = normalize(prefix);\n return normalized !== null && (normalized === '' || beneath(normalized, path));\n });\n}\n"],"names":["dirname","path","index","lastIndexOf","slice","normalize","parts","part","split","length","pop","push","join","resolve","from","reference","base","relative","target","filter","shared","up","Array","beneath","prefix","startsWith","covered","prefixes","some","normalized"],"mappings":"AAAA,SAASA,QAAQC,IAAY;IAC3B,MAAMC,QAAQD,KAAKE,WAAW,CAAC;IAC/B,OAAOD,UAAU,CAAC,IAAI,KAAKD,KAAKG,KAAK,CAAC,GAAGF;AAC3C;AAEA,OAAO,SAASG,UAAUJ,IAAY;IACpC,MAAMK,QAAkB,EAAE;IAC1B,KAAK,MAAMC,QAAQN,KAAKO,KAAK,CAAC,KAAM;QAClC,IAAID,SAAS,MAAMA,SAAS,KAAK;QACjC,IAAIA,SAAS,MAAM;YACjB,IAAID,MAAMG,MAAM,KAAK,GAAG,OAAO;YAC/BH,MAAMI,GAAG;YACT;QACF;QACAJ,MAAMK,IAAI,CAACJ;IACb;IACA,OAAOD,MAAMM,IAAI,CAAC;AACpB;AAEA,OAAO,SAASC,QAAQC,IAAY,EAAEC,SAAiB;IACrD,MAAMC,OAAOhB,QAAQc;IACrB,OAAOT,UAAUW,SAAS,KAAKD,YAAY,GAAGC,KAAK,CAAC,EAAED,WAAW;AACnE;AAEA,OAAO,SAASE,SAASH,IAAY,EAAEI,MAAc;IACnD,MAAMF,OAAOhB,QAAQc,MAClBN,KAAK,CAAC,KACNW,MAAM,CAAC,CAACZ,OAASA,SAAS;IAC7B,MAAMD,QAAQY,OAAOV,KAAK,CAAC;IAC3B,IAAIY,SAAS;IACb,MAAOA,SAASJ,KAAKP,MAAM,IAAIW,SAAS,IAAId,MAAMG,MAAM,IAAIO,IAAI,CAACI,OAAO,KAAKd,KAAK,CAACc,OAAO,CAAE;QAC1FA,UAAU;IACZ;IACA,MAAMC,KAAKC,MAAMR,IAAI,CAAC;QAAEL,QAAQO,KAAKP,MAAM,GAAGW;IAAO,GAAG,IAAM;IAC9D,OAAO;WAAIC;WAAOf,MAAMF,KAAK,CAACgB;KAAQ,CAACR,IAAI,CAAC;AAC9C;AAEA,OAAO,SA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