mcard-studio 0.0.1 → 0.0.3

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 (212) hide show
  1. package/README.md +3 -0
  2. package/astro.config.mjs +46 -2
  3. package/bin/mcard-studio.mjs +1 -1
  4. package/cli/lib/runtimeContext.mjs +6 -3
  5. package/dist/client/_astro/{ChartAnalyticsViewlet.Cevj0EOs.js → ChartAnalyticsViewlet.CBW-JyA3.js} +1 -1
  6. package/dist/client/_astro/ClmPcardViewlet.cvKsR2ng.js +3 -0
  7. package/dist/client/_astro/D3GraphViewlet.8YEIrCGL.js +2 -0
  8. package/dist/client/_astro/DockviewSpatialWorkbench.BTd66LPl.js +12 -0
  9. package/dist/client/_astro/DocumentViewlets.KY1HcNka.js +2 -0
  10. package/dist/client/_astro/DxfViewlet.B3N5zpZR.js +1 -0
  11. package/dist/client/_astro/ExcalidrawWhiteboardViewlet.CMJGCQN4.js +1 -0
  12. package/dist/client/_astro/{FaroVCardSpanInstrumenter.BIk2NhJY.js → FaroVCardSpanInstrumenter.ClIqZujq.js} +1 -1
  13. package/dist/client/_astro/{FontSpecimenViewlet.CpONhJh0.js → FontSpecimenViewlet.ChIyr0B8.js} +1 -1
  14. package/dist/client/_astro/HeadMeta.astro_astro_type_script_index_0_lang.D3FSc061.js +1 -0
  15. package/dist/client/_astro/{ImageViewlet.CHeNvX6L.js → ImageViewlet.Cs-u7-wt.js} +1 -1
  16. package/dist/client/_astro/{KatexFormulaViewlet.Cy_InWOK.js → KatexFormulaViewlet.0nOzV_qD.js} +1 -1
  17. package/dist/client/_astro/KoishiChatViewlet.DLsMmwdb.js +16 -0
  18. package/dist/client/_astro/MCardLibraryHarness.WBT9W10S.js +2 -0
  19. package/dist/client/_astro/{MarkdownViewlet.qoPlM-TZ.js → MarkdownViewlet.BIolkNXf.js} +25 -25
  20. package/dist/client/_astro/{MermaidDiagramViewlet.RnwDfQl6.js → MermaidDiagramViewlet.CkRk7QsS.js} +1 -1
  21. package/dist/client/_astro/PCardRendererBridge.DhaRSprd.js +1 -0
  22. package/dist/client/_astro/RendererPCardRegistry.brM2KiQs.js +1 -0
  23. package/dist/client/_astro/{SchemaYamlViewlet.D6HVdmrq.js → SchemaYamlViewlet.Bc7nkK4M.js} +1 -1
  24. package/dist/client/_astro/{ShellContainer.astro_astro_type_script_index_0_lang.2oi8fhQo.js → ShellContainer.astro_astro_type_script_index_0_lang.5q1gCLvf.js} +1 -1
  25. package/dist/client/_astro/{Spatial3dViewlet.CCYBSSib.js → Spatial3dViewlet.C-jjhr0A.js} +1 -1
  26. package/dist/client/_astro/{StudioLayout.CBgiVbeb.css → StudioLayout.CX8XGtZV.css} +1 -1
  27. package/dist/client/_astro/StudioWorkbench.B1QwGHWM.js +7 -0
  28. package/dist/client/_astro/{SvgViewlet.BxlWQ-JX.js → SvgViewlet.uGxvb06H.js} +1 -1
  29. package/dist/client/_astro/{TerminalView.DWZR-hUa.js → TerminalView.DP7G7E1m.js} +4 -4
  30. package/dist/client/_astro/{ThemeSettingsViewlet.Cb1r8fWw.js → ThemeSettingsViewlet.UaTHcGnF.js} +1 -1
  31. package/dist/client/_astro/{TikzDiagramViewlet.CqY7VTeP.js → TikzDiagramViewlet.O8MJyXfT.js} +1 -1
  32. package/dist/client/_astro/VideoPlayerViewlet.-ycmo3kY.js +1 -0
  33. package/dist/client/_astro/WebappZenViewlet.PNce4u2T.js +1 -0
  34. package/dist/client/_astro/{WelcomeViewport.LwKTA6h7.js → WelcomeViewport.CZ6RxGSw.js} +1 -1
  35. package/dist/client/_astro/{agentIdentityCredentialService.BtKVsl2C.js → agentIdentityCredentialService.BEtZzBlO.js} +5 -5
  36. package/dist/client/_astro/cardTypeDetector.C2HH5RnU.js +1 -0
  37. package/dist/client/_astro/disposable.BmlxZrDf.js +1 -0
  38. package/dist/client/_astro/{markdownService.D-tM2RYx.js → markdownService.CpuKl0vp.js} +1 -1
  39. package/dist/client/_astro/{mcardStore.BiAvqM-D.js → mcardStore.nSWnzeLg.js} +2 -2
  40. package/dist/client/_astro/mcardVfs.BSdys1Y7.js +3 -0
  41. package/dist/client/_astro/pathsConfig.CSBBSzwH.js +2 -0
  42. package/dist/client/_astro/polyfills.Bi7kO8cu.js +1 -0
  43. package/dist/client/_astro/rendererEventBus.DirFDmGw.js +1 -0
  44. package/dist/client/_astro/themeStore.BajxvCga.js +1 -0
  45. package/dist/client/_astro/{tikzCompiler.DFojjdxR.js → tikzCompiler.-fXMNQpz.js} +1 -1
  46. package/dist/client/_astro/{useMCardHydration.Co47OH3D.js → useMCardHydration.Bjj_N5Gv.js} +1 -1
  47. package/dist/client/_astro/vendor-ai.D6NcJ6lu.js +69 -0
  48. package/dist/client/_astro/vendor-clm-kernel.B0kxq3g4.js +108 -0
  49. package/dist/client/_astro/vfsHandles.D4Pq18pW.js +1 -0
  50. package/dist/client/_astro/vfsPersistence.DVrd1BZj.js +1 -0
  51. package/dist/client/_astro/vfsTransactions.DBNtFuRz.js +1 -0
  52. package/dist/client/_astro/{workspaceStore.CXakha4Y.js → workspaceStore.DUHW2YBc.js} +1 -1
  53. package/dist/client/js/buffer-polyfill.js +14 -0
  54. package/dist/server/chunks/{StudioLayout_D163irJ0.mjs → StudioLayout_taayQJ5b.mjs} +2 -2
  55. package/dist/server/chunks/{_.._ZXsz792-.mjs → _.._CoQKwo62.mjs} +137 -91
  56. package/dist/server/chunks/{_handle__D_cIJYrU.mjs → _handle__D8dKQPUS.mjs} +3 -3
  57. package/dist/server/chunks/{cardTypeDetector_CyW1Xnmy.mjs → cardTypeDetector_C55M_HWS.mjs} +9 -0
  58. package/dist/server/chunks/{cards_B89BvF6W.mjs → cards_rVOc8K6H.mjs} +2 -2
  59. package/dist/server/chunks/cas_DTxlZ4Le.mjs +68 -0
  60. package/dist/server/chunks/{dispatch_DOwSKukU.mjs → dispatch_BTW4E_BJ.mjs} +8 -7
  61. package/dist/server/chunks/{dispatch_CxWKiHpn.mjs → dispatch_MbkljUxD.mjs} +8 -8
  62. package/dist/server/chunks/{export_DRouradA.mjs → export_DkEwDE2T.mjs} +3 -3
  63. package/dist/server/chunks/{health_Dfa5I0-X.mjs → health_cRt0M0yu.mjs} +1 -1
  64. package/dist/server/chunks/{mcard-library_DvPPUs9_.mjs → mcard-library_CLHvyslV.mjs} +1 -1
  65. package/dist/server/chunks/{mcardVfs_CeezzRvt.mjs → mcardVfs_DvNburKb.mjs} +5 -30
  66. package/dist/server/chunks/{move__RFvIDkq.mjs → move_DYcaXBLV.mjs} +6 -6
  67. package/dist/server/chunks/{pathsConfig_CgNYYLVm.mjs → pathsConfig_Dack-p2f.mjs} +13 -3
  68. package/dist/server/chunks/{proxy_CrWJQIBe.mjs → proxy_CMbbdBPW.mjs} +2 -2
  69. package/dist/server/chunks/{raw_DzNDaDVP.mjs → raw_C97sJWhg.mjs} +59 -26
  70. package/dist/server/chunks/{serverBootstrap_XKo2s6Ha.mjs → serverBootstrap_BDdSRIu5.mjs} +2 -2
  71. package/dist/server/chunks/tree_BwmO-pTe.mjs +186 -0
  72. package/dist/server/chunks/vfsCore_DIKpk-pk.mjs +98 -0
  73. package/dist/server/chunks/{vfsTreeScan_CKp7kMt9.mjs → vfsTreeScan_CRoCluPB.mjs} +18 -10
  74. package/dist/server/chunks/workspaceRoot_CRx3taID.mjs +157 -0
  75. package/dist/server/chunks/{write_popiFsO7.mjs → write_BLsmsTIx.mjs} +6 -5
  76. package/dist/server/chunks/{ws-server-init_CkcgcI5V.mjs → ws-server-init_Cfft7U5u.mjs} +343 -298
  77. package/dist/server/entry.mjs +8 -4
  78. package/dist/server/entry2.mjs +67 -28
  79. package/dist/server/virtual_astro_middleware.mjs +2 -2
  80. package/package.json +2 -2
  81. package/public/js/buffer-polyfill.js +14 -0
  82. package/src/components/studio/views/cardViewlets/ClmRegistryComponentViewlet.tsx +133 -0
  83. package/src/components/studio/views/cardViewlets/DxfViewlet.tsx +230 -0
  84. package/src/components/studio/views/cardViewlets/VideoPlayerViewlet.tsx +4 -4
  85. package/src/components/studio/views/cardViewlets/coreViewletDefs.ts +2 -2
  86. package/src/components/studio/views/cardViewlets/documents/AudioPlayerViewlet.tsx +15 -3
  87. package/src/components/studio/views/cardViewlets/documents/PdfViewlet.tsx +25 -7
  88. package/src/components/studio/views/cardViewlets/markdown/stages/wikilinkStage.ts +2 -1
  89. package/src/components/studio/views/cardViewlets/mediaViewletDefs.ts +21 -1
  90. package/src/components/studio/views/cardViewlets/webapp/WebappCanvas.tsx +40 -15
  91. package/src/components/studio/views/cardViewlets/webapp/WebappDevicePresetBar.tsx +108 -0
  92. package/src/components/studio/views/cardViewlets/webapp/WebappZenViewlet.tsx +23 -30
  93. package/src/components/studio/views/fileTree/MCardFileTree.tsx +71 -54
  94. package/src/components/studio/views/fileTree/hooks/useFileTreeSync.ts +0 -1
  95. package/src/components/studio/views/fileTree/hooks/usePartitionedTrees.ts +68 -23
  96. package/src/components/studio/views/fileTree/hooks/useSectionAccordion.ts +21 -11
  97. package/src/components/studio/views/functions/UnifiedFunctionExplorerViewlet.tsx +168 -0
  98. package/src/components/studio/views/history/HistoryPanel.tsx +110 -0
  99. package/src/components/studio/views/lineage/LineagePanel.tsx +152 -0
  100. package/src/components/studio/views/navigation/HandleLineageDrawer.tsx +89 -0
  101. package/src/components/studio/views/navigation/MultiCardCollectionBrowser.tsx +154 -0
  102. package/src/components/studio/views/pills/HashPill.tsx +101 -0
  103. package/src/components/studio/views/residency/ResidencyIndicator.tsx +82 -0
  104. package/src/config/app_config.json +3 -3
  105. package/src/core/projection/catalog.ts +105 -0
  106. package/src/core/projection/collection.ts +148 -0
  107. package/src/core/projection/handleSubscription.ts +132 -0
  108. package/src/core/projection/index.ts +4 -0
  109. package/src/core/projection/selectors.ts +29 -0
  110. package/src/core/projection/views.ts +242 -0
  111. package/src/core/refinement/designMetrics.ts +104 -0
  112. package/src/core/refinement/fibrationProjector.ts +142 -0
  113. package/src/core/refinement/lagrangianEngine.ts +137 -0
  114. package/src/core/refinement/refinementCommands.ts +82 -0
  115. package/src/core/viewport/deviceArchetypeRegistry.ts +177 -0
  116. package/src/core/viewport/viewportAudit.ts +150 -0
  117. package/src/edge/storeFilter.d.ts +4 -0
  118. package/src/edge/storeFilter.js +54 -0
  119. package/src/edge/storeFilter.ts +52 -0
  120. package/src/layouts/StudioLayout.astro +1 -0
  121. package/src/lib/cryptoPolyfill.js +77 -1
  122. package/src/lib/fsPolyfill.js +65 -0
  123. package/src/lib/urlPolyfill.js +21 -0
  124. package/src/lib/zlibPolyfill.js +35 -0
  125. package/src/packages/mcard-studio/package.json +2 -2
  126. package/src/packages/mcard-studio/type/legacyMapping.ts +5 -0
  127. package/src/packages/mcard-studio/viewlets/manifests.ts +2 -0
  128. package/src/packages/mcard-studio/viewlets/moduleMap.ts +12 -0
  129. package/src/packages/mcard-studio/viewlets/refinementManifests.ts +114 -0
  130. package/src/pages/api/dispatch.ts +3 -2
  131. package/src/pages/api/vfs/cas.ts +114 -0
  132. package/src/pages/api/vfs/move.ts +5 -5
  133. package/src/pages/api/vfs/raw.ts +72 -27
  134. package/src/pages/api/vfs/tree.ts +130 -11
  135. package/src/pages/api/vfs/write.ts +5 -4
  136. package/src/pages/index.astro +75 -0
  137. package/src/server/api/kernelDispatch.ts +8 -8
  138. package/src/server/artifactCollectionService.ts +4 -7
  139. package/src/server/artifactRepository.ts +4 -3
  140. package/src/server/clmRunner.mjs +1 -1
  141. package/src/server/collectionOwner.mjs +5 -5
  142. package/src/server/effects/executionPersistenceService.mjs +11 -11
  143. package/src/server/effects/resultSealingService.mjs +2 -2
  144. package/src/server/fileIngestService.mjs +21 -9
  145. package/src/server/fileWatcherService.mjs +4 -1
  146. package/src/server/handlers/fileChangeHandler.mjs +18 -10
  147. package/src/server/handlers/saveExecutionLogHandler.mjs +6 -6
  148. package/src/server/notificationService.mjs +14 -1
  149. package/src/server/scripts/buildSeedingMemory.mjs +3 -3
  150. package/src/server/serverMemoryRepository.ts +41 -59
  151. package/src/server/vfsTreeScan.ts +16 -10
  152. package/src/server/workspaceRoot.ts +143 -5
  153. package/src/services/cardTypeDetector.ts +4 -0
  154. package/src/services/databaseSyncService.ts +30 -46
  155. package/src/services/inBrowserLlm/engines/litertEngine.ts +1 -1
  156. package/src/services/namespaceProtocolClient.ts +221 -0
  157. package/src/services/renderers/pcard/RendererPCardRegistry.ts +4 -66
  158. package/src/services/renderers/pcard/modalitySpecs.ts +125 -0
  159. package/src/services/renderers/pcard/types.ts +7 -1
  160. package/src/services/renderers/rendererEventBus.ts +5 -3
  161. package/src/services/unifiedFunctionExecutionService.ts +145 -0
  162. package/src/services/vfs/vfsCore.ts +12 -1
  163. package/src/services/vfs/vfsMigration.ts +95 -0
  164. package/src/services/vfs/vfsMutations.ts +17 -35
  165. package/src/services/vfs/vfsPersistence.ts +19 -24
  166. package/src/services/vfs/vfsSync.ts +55 -17
  167. package/src/services/vfs/vfsVersions.ts +23 -34
  168. package/src/services/workbenchExecutionPolicy.ts +183 -0
  169. package/src/stores/mcardCollectionStore.ts +2 -0
  170. package/src/styles/dockview.css +34 -0
  171. package/src/ui/viewlets/FibrationRefinementViewlet.tsx +155 -0
  172. package/src/ui/viewlets/PetriConformanceViewlet.tsx +166 -0
  173. package/src/ui/viewlets/ResponsiveViewportLabViewlet.tsx +175 -0
  174. package/src/ui/viewlets/SprintGovernanceViewlet.tsx +176 -0
  175. package/src/ui/viewlets/viewletFocus.ts +35 -0
  176. package/src/ui/viewlets/viewportLabParts.tsx +190 -0
  177. package/dist/client/_astro/ClmPcardViewlet.DW5Yft0E.js +0 -3
  178. package/dist/client/_astro/D3GraphViewlet.DAjPz1DP.js +0 -2
  179. package/dist/client/_astro/DockviewSpatialWorkbench.DyQjSoHd.js +0 -12
  180. package/dist/client/_astro/DocumentViewlets.Dm_GL3AL.js +0 -2
  181. package/dist/client/_astro/ExcalidrawWhiteboardViewlet.DrlW7B6G.js +0 -1
  182. package/dist/client/_astro/HeadMeta.astro_astro_type_script_index_0_lang.DGXU-3Lu.js +0 -1
  183. package/dist/client/_astro/KoishiChatViewlet.B0eDEMnT.js +0 -16
  184. package/dist/client/_astro/MCardLibraryHarness.CUJLJFBt.js +0 -2
  185. package/dist/client/_astro/PCardRendererBridge.BnyaE05I.js +0 -1
  186. package/dist/client/_astro/RendererPCardRegistry.CLr4j1Ub.js +0 -1
  187. package/dist/client/_astro/StudioWorkbench.CF0SOYwy.js +0 -7
  188. package/dist/client/_astro/VideoPlayerViewlet.DoSYmmoQ.js +0 -1
  189. package/dist/client/_astro/WebappZenViewlet.CQW50OhX.js +0 -1
  190. package/dist/client/_astro/cardTypeDetector.C9kGObMh.js +0 -1
  191. package/dist/client/_astro/disposable.66apX1Q2.js +0 -1
  192. package/dist/client/_astro/empty.DOwCrGXH.js +0 -1
  193. package/dist/client/_astro/mcardVfs.Bj-RA0p7.js +0 -2
  194. package/dist/client/_astro/path.CR60mj9W.js +0 -1
  195. package/dist/client/_astro/pathsConfig.D0hV34p7.js +0 -2
  196. package/dist/client/_astro/polyfills.DcBkS56X.js +0 -1
  197. package/dist/client/_astro/rendererEventBus.CyFnSRLk.js +0 -1
  198. package/dist/client/_astro/themeStore.zUMFLo3Q.js +0 -1
  199. package/dist/client/_astro/vendor-ai.CZe7UVVK.js +0 -69
  200. package/dist/client/_astro/vfsHandles.B-nczBRy.js +0 -1
  201. package/dist/client/_astro/vfsPersistence.D6zRzVML.js +0 -1
  202. package/dist/client/_astro/vfsTransactions.04mkEHxD.js +0 -1
  203. package/dist/server/chunks/cryptoPolyfill_99rxUwYC.mjs +0 -180
  204. package/dist/server/chunks/kernelHash_DRaj51hY.mjs +0 -5
  205. package/dist/server/chunks/tree_CE2BhvyJ.mjs +0 -76
  206. package/dist/server/chunks/vfsCore_B6nCiBl5.mjs +0 -21
  207. package/dist/server/chunks/workspaceRoot_DVSUbYkd.mjs +0 -71
  208. package/src/server/kernelHash.ts +0 -22
  209. package/src/server/storage/cardCollection.ts +0 -94
  210. package/src/server/storage/index.ts +0 -3
  211. package/src/server/storage/mcard.ts +0 -99
  212. package/src/server/storage/sqliteNodeEngine.ts +0 -121
@@ -1,5 +1,5 @@
1
1
  import { WS_MESSAGE_TYPES } from '../../shared/wsProtocol.js';
2
- import { MCard } from '../storage/index.ts';
2
+ import { createRecord } from 'clm-kernel';
3
3
  import { isExecutionLogPayload } from '../../domain/executionSchema.js';
4
4
 
5
5
  /**
@@ -24,9 +24,9 @@ export function createSaveExecutionLogHandler({ logsCollectionOwner, clients })
24
24
  ...payload
25
25
  };
26
26
 
27
- const vCard = await MCard.create(JSON.stringify(logData, null, 2));
28
- await logsColl.add(vCard);
29
- console.log(`[WS] Execution log saved as MCard: ${vCard.hash}`);
27
+ const record = createRecord(JSON.stringify(logData, null, 2));
28
+ await logsColl.add(record);
29
+ console.log(`[WS] Execution log saved as MCard: ${record.hash}`);
30
30
 
31
31
  // --- Broadcast governance telemetry to all connected clients ---
32
32
  if (payload.governance_telemetry && clients) {
@@ -34,7 +34,7 @@ export function createSaveExecutionLogHandler({ logsCollectionOwner, clients })
34
34
  const telemetryUpdate = JSON.stringify({
35
35
  type: WS_MESSAGE_TYPES.TELEMETRY_UPDATE,
36
36
  data: {
37
- id: vCard.hash,
37
+ id: record.hash,
38
38
  timestamp: Date.now(),
39
39
  possibilityMagnitude: gt.M ?? 0,
40
40
  governanceNarrowing: gt.N ?? 0,
@@ -57,7 +57,7 @@ export function createSaveExecutionLogHandler({ logsCollectionOwner, clients })
57
57
  return {
58
58
  type: WS_MESSAGE_TYPES.EXECUTION_LOG_SAVED,
59
59
  success: true,
60
- hash: vCard.hash
60
+ hash: record.hash
61
61
  };
62
62
  };
63
63
  }
@@ -137,6 +137,18 @@ export function createNotificationService({ clients, pushSubscriptions, pendingN
137
137
  return results;
138
138
  }
139
139
 
140
+ function broadcastRaw(rawMessage) {
141
+ for (const [clientId, client] of clients) {
142
+ if (client && client.ws && client.ws.readyState === 1 /* OPEN */) {
143
+ try {
144
+ client.ws.send(rawMessage);
145
+ } catch (e) {
146
+ console.error('[Notify] broadcastRaw error:', e);
147
+ }
148
+ }
149
+ }
150
+ }
151
+
140
152
  return {
141
153
  NotificationPriority,
142
154
  sendNotification,
@@ -144,6 +156,7 @@ export function createNotificationService({ clients, pushSubscriptions, pendingN
144
156
  storePendingNotification,
145
157
  deliverPendingNotifications,
146
158
  broadcastToAll,
147
- broadcastToChannel
159
+ broadcastToChannel,
160
+ broadcastRaw,
148
161
  };
149
162
  }
@@ -2,7 +2,7 @@ import fs from 'fs/promises';
2
2
  import path from 'path';
3
3
  import { createCollectionOwner } from '../collectionOwner.mjs';
4
4
  import { resolveServerConfig } from '../serverConfig.js';
5
- import { MCard } from '../storage/index.ts';
5
+ import { createRecord } from 'clm-kernel';
6
6
 
7
7
  const config = resolveServerConfig(process.env);
8
8
  const SEEDING_DB_PATH = config.seedingMemoryDbPath;
@@ -34,13 +34,13 @@ async function buildSeedingMemory() {
34
34
  const contentStr = await fs.readFile(filePath, 'utf-8');
35
35
  const contentBytes = new TextEncoder().encode(contentStr);
36
36
 
37
- const card = await MCard.create(contentBytes);
37
+ const record = createRecord(contentBytes);
38
38
  // The handle format in MCard Studio is typically local/dir/file
39
39
  // Wait, what should be the handle? In loadArtifactIndex it's 'local/clm/chapter_01_arithmetic/addition_js.yaml'
40
40
  // For browsermemory, the handle is just `local/clm/chapter_01_arithmetic/addition_js.yaml` (when fetched lazily)
41
41
  const handle = `local/${relativeDir}/${file}`;
42
42
 
43
- await collection.addWithHandle(card, handle);
43
+ await collection.addWithHandle(record, handle);
44
44
  addedCount++;
45
45
  console.log(`[buildSeedingMemory] Added ${handle}`);
46
46
  }
@@ -1,6 +1,6 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
- import { CardCollection, MCard, SqliteNodeEngine } from './storage/index';
3
+ import { MCardCollection, NodeSqliteBackend, createRecord, qualify } from 'clm-kernel';
4
4
  import type { ArtifactMeta } from '../domain/artifacts';
5
5
  import { inferArtifactType } from '../domain/artifactClassification';
6
6
  import { artifactFetchPathFromHandle, artifactPathFromHandle, SERVER_COL_PREFIX_SLASH, SERVER_FS_PREFIX } from '../utils/artifactHandles';
@@ -101,16 +101,16 @@ function buildArtifactMeta(
101
101
  */
102
102
  export class ServerMemoryArtifactRepository implements ArtifactRepository {
103
103
 
104
- private collection!: CardCollection;
104
+ private collection!: MCardCollection;
105
105
  private readonly dbPath: string;
106
106
  /** Cached artifact metadata — avoids re-fetching cards just for listing. */
107
107
  private cachedMeta: ArtifactMeta[] | null = null;
108
108
  /** Seeding lock — ensures only one concurrent caller actually seeds. */
109
109
  private seedingPromise: Promise<void> | null = null;
110
110
  /** Optional injected engine (used in tests to avoid hitting disk). */
111
- private readonly injectedEngine: SqliteNodeEngine | null;
111
+ private readonly injectedEngine: NodeSqliteBackend | null;
112
112
  /** Cached engine instance — created lazily, reused across all calls. */
113
- private _engine: SqliteNodeEngine | null = null;
113
+ private _engine: NodeSqliteBackend | null = null;
114
114
 
115
115
  /**
116
116
  * Per-instance lookup table mapping normalized handles to their seed record.
@@ -125,8 +125,7 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
125
125
 
126
126
  constructor(
127
127
  dbPath: string = SERVER_MEMORY_DB_PATH,
128
-
129
- injectedEngine: SqliteNodeEngine | null = null
128
+ injectedEngine: NodeSqliteBackend | null = null
130
129
  ) {
131
130
  this.dbPath = dbPath;
132
131
  this.injectedEngine = injectedEngine;
@@ -136,7 +135,7 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
136
135
  // Defer engine construction — init happens lazily on first access
137
136
  }
138
137
 
139
- private async getOrCreateEngine(): Promise<SqliteNodeEngine> {
138
+ private async getOrCreateEngine(): Promise<NodeSqliteBackend> {
140
139
  if (this._engine) return this._engine;
141
140
  if (!this.injectedEngine) {
142
141
  const dir = path.dirname(this.dbPath);
@@ -144,12 +143,12 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
144
143
  fs.mkdirSync(dir, { recursive: true });
145
144
  }
146
145
  }
147
- this._engine = this.injectedEngine ?? await SqliteNodeEngine.create(this.dbPath);
146
+ this._engine = this.injectedEngine ?? new NodeSqliteBackend(this.dbPath);
148
147
  return this._engine;
149
148
  }
150
149
 
151
150
  private async initEngine(): Promise<void> {
152
- this.collection = new CardCollection(await this.getOrCreateEngine());
151
+ this.collection = new MCardCollection(await this.getOrCreateEngine());
153
152
  }
154
153
 
155
154
  private async ensureEngine(): Promise<void> {
@@ -158,15 +157,6 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
158
157
  }
159
158
  }
160
159
 
161
- /**
162
- * Drop and recreate the database when the existing one has incompatible
163
- * data (e.g. legacy g_time timestamps from the old raw-SQL code path).
164
- */
165
- private async recreateDatabase(): Promise<void> {
166
- try { fs.unlinkSync(this.dbPath); } catch { /* already gone */ }
167
- await this.initEngine();
168
- }
169
-
170
160
  /**
171
161
  * Ensures the database is seeded exactly once, even under concurrent
172
162
  * requests. The first caller creates the seeding promise; subsequent
@@ -192,16 +182,8 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
192
182
  try {
193
183
  const count = await this.collection.count();
194
184
  needsSeed = count === 0;
195
- } catch (err) {
196
- const msg = err instanceof Error ? err.message : '';
197
- if (msg.includes('Invalid GTime format')) {
198
- console.warn('[ServerMemory] Detected legacy g_time format — recreating database');
199
-
200
- this.recreateDatabase();
201
- needsSeed = true;
202
- } else {
203
- throw err;
204
- }
185
+ } catch {
186
+ needsSeed = false;
205
187
  }
206
188
 
207
189
  if (needsSeed) {
@@ -213,8 +195,9 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
213
195
  const existing = await this.collection.resolveHandle(handle);
214
196
  if (!existing) {
215
197
  const content = readSeedPayload(record);
216
- const card = await MCard.create(content);
217
- await this.collection.addWithHandle(card, handle);
198
+ const rec = createRecord(content);
199
+ await this.collection.putRecord(rec);
200
+ await this.collection.addWithHandle(rec, handle);
218
201
  }
219
202
  }
220
203
  }
@@ -266,7 +249,7 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
266
249
 
267
250
  for (const row of allHandlesRaw) {
268
251
  const handle = normalizeHandle(row.handle);
269
- const history = await engine.getHandleHistory(handle).catch(() => []);
252
+ const history = await Promise.resolve(engine.getHandleHistory(handle)).catch(() => []);
270
253
  const timestamp = history.length > 0 ? history[0].changedAt : undefined;
271
254
  const meta = buildArtifactMeta(handle, 0, row.hash, timestamp); // Default size placeholder
272
255
 
@@ -336,20 +319,17 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
336
319
  await this.ensureEngine();
337
320
  const normalizedHandle = normalizeHandle(handle);
338
321
 
339
- const card = await MCard.create(content);
340
- const existing = await this.collection.resolveHandle(normalizedHandle);
341
- if (existing) {
342
- await this.collection.updateHandle(normalizedHandle, card);
343
- } else {
344
- await this.collection.addWithHandle(card, normalizedHandle);
345
- }
322
+ const record = createRecord(content);
323
+ const qualifiedHash = qualify(record).asPrefixed();
324
+ await this.collection.putRecord(record);
325
+ await this.collection.updateHandle(normalizedHandle, qualifiedHash);
346
326
 
347
327
  this.seedLookup.set(normalizedHandle, {
348
328
  handle: normalizedHandle,
349
329
  payload: { kind: 'buffer', value: content }
350
330
  });
351
331
 
352
- const history = await this.collection.getHandleHistory(normalizedHandle).catch(() => []);
332
+ const history = await Promise.resolve(this.collection.getHandleHistory(normalizedHandle)).catch(() => []);
353
333
  const timestamp = history.length > 0 ? history[0].changedAt : new Date().toISOString();
354
334
 
355
335
  // Preserve ipfsCid and minioUrl from existing metadata if available
@@ -357,7 +337,7 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
357
337
  const newMeta = buildArtifactMeta(
358
338
  normalizedHandle,
359
339
  content.length,
360
- card.hash,
340
+ qualifiedHash,
361
341
  timestamp,
362
342
  existingMeta?.ipfsCid,
363
343
  existingMeta?.minioUrl
@@ -381,8 +361,11 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
381
361
  async getArtifactContentByHash(hash: string): Promise<Uint8Array | null> {
382
362
  await this.seedIfEmpty();
383
363
  await this.ensureEngine();
384
- const card = await this.collection.get(hash);
385
- return card ? card.content : null;
364
+ const record = this.collection.getRecord(hash);
365
+ if (record) {
366
+ return record.content instanceof Uint8Array ? record.content : Buffer.from(record.content);
367
+ }
368
+ return null;
386
369
  }
387
370
 
388
371
  async deleteArtifact(handle: string): Promise<void> {
@@ -421,20 +404,24 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
421
404
  }
422
405
 
423
406
  /**
424
- * Delete a single history entry by handle + previousHash.
425
- * This removes one version from the history without deleting the artifact itself.
407
+ * Total number of records in CAS backing storage.
426
408
  */
427
- async deleteHistoryEntry(handle: string, previousHash: string): Promise<void> {
428
- await this.seedIfEmpty();
429
- await this.ensureEngine();
430
- const normalizedHandle = normalizeHandle(handle);
409
+ count(): number {
410
+ if (!this.collection) return 0;
411
+ return (this.collection as any).storageBackend?.count?.() ?? 0;
412
+ }
431
413
 
432
- const engine = await this.getOrCreateEngine();
433
- await engine.deleteHistoryEntry(normalizedHandle, previousHash);
414
+ /**
415
+ * Expose internal MCardCollection.
416
+ */
417
+ getCollection(): MCardCollection {
418
+ return this.collection;
434
419
  }
435
420
 
436
421
  /**
437
- * Revert the handle to its previous version by popping the latest history entry.
422
+ * Revert the handle to its previous version by pointing the head back at the previous hash.
423
+ * In the G-Set append-only model (CAS-02), this records a new transition pointing to the
424
+ * previous object — history grows by one and past versions are never deleted or rewritten.
438
425
  * Returns the hash that the handle was rolled back to, or null if no history.
439
426
  */
440
427
  async revertLatestVersion(handle: string): Promise<string | null> {
@@ -448,15 +435,10 @@ export class ServerMemoryArtifactRepository implements ArtifactRepository {
448
435
 
449
436
  const latest = history[0]; // newest first
450
437
  const previousHash = latest.previousHash;
438
+ if (!previousHash) return null;
451
439
 
452
- // Delete the latest history entry (stitches the chain)
453
- const engine = await this.getOrCreateEngine();
454
- await engine.deleteHistoryEntry(normalizedHandle, previousHash);
455
-
456
- // Roll back the handle pointer to the previous hash (without creating new history)
457
- // removeHandle + re-register approach
458
- await engine.removeHandle(normalizedHandle);
459
- await engine.registerHandle(normalizedHandle, previousHash);
440
+ // In G-Set model, pointing head back at previous version appends an UPDATE to history
441
+ await this.collection.updateHandle(normalizedHandle, previousHash);
460
442
 
461
443
  // Invalidate cached metadata so next listing picks up the change
462
444
  this.cachedMeta = null;
@@ -14,8 +14,7 @@
14
14
 
15
15
  import { readdirSync, statSync, existsSync, readFileSync } from 'node:fs';
16
16
  import { join, relative } from 'node:path';
17
- import { createHash } from 'node:crypto';
18
- import { detectEpistemicStatus } from 'clm-kernel';
17
+ import { createRecord, qualify, detectEpistemicStatus } from 'clm-kernel';
19
18
  import { PATHS, resolveEpistemicStatus as resolveEpistemicPathHint } from '../config/pathsConfig.js';
20
19
  import type { PathsConfig } from '../config/pathsConfig.js';
21
20
  import { sniffMimeType, detectCardType } from '../services/cardTypeDetector';
@@ -28,7 +27,8 @@ export interface VfsScanEntry {
28
27
  name: string;
29
28
  size: number;
30
29
  mtime: number;
31
- hash: string;
30
+ hash?: string;
31
+ hashDeferred?: boolean;
32
32
  content?: string;
33
33
  }
34
34
 
@@ -40,9 +40,11 @@ export interface ScanRoot {
40
40
  /** Unified ignore semantics: `ingest.ignore.patterns` + `vfs.extra_ignore_paths` (INV-PC-03). */
41
41
  export function shouldIgnorePath(relPath: string, name: string, config: PathsConfig = PATHS): boolean {
42
42
  if (config.ingest.ignore.skip_dotfiles && name.startsWith('.')) return true;
43
+ if (name.endsWith('-wal') || name.endsWith('-shm') || name.endsWith('-journal')) return true;
44
+ if (config.stores && Object.values(config.stores).includes(name)) return true;
43
45
  const ignored = [...config.ingest.ignore.patterns, ...config.vfs.extra_ignore_paths];
44
46
  for (const ign of ignored) {
45
- if (relPath === ign || relPath.startsWith(ign + '/') || name === ign) return true;
47
+ if (relPath === ign || relPath.startsWith(ign + '/') || name === ign || name.includes(ign)) return true;
46
48
  }
47
49
  return false;
48
50
  }
@@ -63,12 +65,14 @@ export function scanDir(dir: string, baseDir: string, config: PathsConfig = PATH
63
65
  } else if (f.isFile()) {
64
66
  try {
65
67
  const stat = statSync(fullPath);
66
- let hash: string;
68
+ let hash: string | undefined = undefined;
69
+ let hashDeferred: boolean | undefined = undefined;
67
70
  let content: string | undefined;
68
71
  if (stat.size <= config.vfs.hash_max_bytes) {
69
72
  try {
70
73
  const buf = readFileSync(fullPath);
71
- hash = createHash('sha256').update(buf).digest('hex');
74
+ const record = createRecord(buf);
75
+ hash = qualify(record).asPrefixed();
72
76
  const ext = '.' + (f.name.split('.').pop() || '').toLowerCase();
73
77
  const isTextExt = textExts.has(ext) || f.name.toLowerCase().endsWith('.tikz-cd');
74
78
  const mime = sniffMimeType(relPath);
@@ -76,12 +80,13 @@ export function scanDir(dir: string, baseDir: string, config: PathsConfig = PATH
76
80
  content = buf.toString('utf8');
77
81
  }
78
82
  } catch {
79
- hash = createHash('sha256').update(`${relPath}:${stat.size}:${stat.mtimeMs}`).digest('hex');
83
+ hash = undefined;
80
84
  }
81
85
  } else {
82
- hash = createHash('sha256').update(`${relPath}:${stat.size}:${stat.mtimeMs}`).digest('hex');
86
+ hash = undefined;
87
+ hashDeferred = true;
83
88
  }
84
- entries.push({ path: relPath, name: f.name, size: stat.size, mtime: stat.mtimeMs, hash, content });
89
+ entries.push({ path: relPath, name: f.name, size: stat.size, mtime: stat.mtimeMs, hash, hashDeferred, content });
85
90
  } catch {
86
91
  // Guard stat errors
87
92
  }
@@ -131,7 +136,8 @@ export function toTreeFiles(entries: readonly VfsScanEntry[], config: PathsConfi
131
136
  const typeInfo = detectCardType({ path: entry.path, mimeType: mime, content: entry.content });
132
137
  return {
133
138
  handle: entry.path.replace(/\//g, separator),
134
- hash: entry.hash,
139
+ hash: entry.hash ?? '',
140
+ hashDeferred: entry.hashDeferred,
135
141
  path: entry.path,
136
142
  name: entry.name,
137
143
  mimeType: mime,
@@ -1,6 +1,7 @@
1
- import { resolve, join, dirname } from 'node:path';
1
+ import { resolve, join, dirname, basename } from 'node:path';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { PATHS, type PathsConfig } from '../config/pathsConfig.js';
4
+ import { parseMcardUri } from 'clm-kernel';
4
5
 
5
6
  /**
6
7
  * Installed-package root, when the CLI provides one (Program NP · INV-NP-05).
@@ -26,14 +27,26 @@ export function installedPackageRoot(config: PathsConfig = PATHS): string | null
26
27
  export function repoRoot(config: PathsConfig = PATHS): string {
27
28
  const installed = installedPackageRoot(config);
28
29
  if (installed) return installed;
30
+ const envRepo = process.env.MCARD_REPO_ROOT;
31
+ if (envRepo && existsSync(resolve(envRepo))) return resolve(envRepo);
32
+
29
33
  const sentinelParts = config.paths.repo_root_sentinel.split('/').filter(Boolean);
30
34
  let cur = process.cwd();
31
35
  while (cur !== '/' && dirname(cur) !== cur) {
32
36
  if (existsSync(join(cur, 'package.json')) && existsSync(join(cur, ...sentinelParts))) {
33
37
  return cur;
34
38
  }
39
+ if (
40
+ existsSync(join(cur, 'mcard-studio', 'package.json')) &&
41
+ existsSync(join(cur, 'mcard-studio', ...sentinelParts))
42
+ ) {
43
+ return join(cur, 'mcard-studio');
44
+ }
35
45
  cur = dirname(cur);
36
46
  }
47
+ if (existsSync(join(process.cwd(), 'mcard-studio', ...sentinelParts))) {
48
+ return join(process.cwd(), 'mcard-studio');
49
+ }
37
50
  return process.cwd();
38
51
  }
39
52
 
@@ -57,6 +70,109 @@ export function workspaceRoot(config: PathsConfig = PATHS): string {
57
70
  /** Alias kept for the PC-02 spec's naming. */
58
71
  export const resolveWorkspaceRoot = workspaceRoot;
59
72
 
73
+ /**
74
+ * Locate the active data root (chosen directory, e.g. --data-root ./data/demo_vault).
75
+ * Returns null if unset or if the directory does not exist.
76
+ */
77
+ export function dataRoot(): string | null {
78
+ const envData = process.env.MCARD_DATA_ROOT || process.env.DATA_ROOT;
79
+ if (envData) {
80
+ const res = resolve(envData);
81
+ if (existsSync(res)) return res;
82
+ const base = process.env.MCARD_PROJECT_ROOT ? resolve(process.env.MCARD_PROJECT_ROOT) : repoRoot();
83
+ const relRes = resolve(base, envData);
84
+ if (existsSync(relRes)) return relRes;
85
+ }
86
+ return null;
87
+ }
88
+
89
+ /**
90
+ * Resolves a locator path (e.g. 'workspace/foo' or 'assets/clm') to an absolute
91
+ * path on disk. When running as an installed package, the workspace lives under
92
+ * the host project root rather than inside the immutable package directory.
93
+ */
94
+ export function resolveHostPath(
95
+ targetPath: string,
96
+ rootDir: string = repoRoot(),
97
+ config: PathsConfig = PATHS,
98
+ ): string {
99
+ const wsDir = config.paths.workspace_dirname;
100
+ const wsRoot = resolve(workspaceRoot(config));
101
+ const dRoot = dataRoot();
102
+
103
+ if (resolve(targetPath) === targetPath) {
104
+ return targetPath;
105
+ }
106
+ let cleanRel = targetPath.trim();
107
+ if (cleanRel.startsWith('mcard://')) {
108
+ try {
109
+ const parsed = parseMcardUri(cleanRel);
110
+ if (parsed.type === 'handle') {
111
+ cleanRel = parsed.target.replace(/^mcard:/, '');
112
+ } else {
113
+ cleanRel = parsed.target;
114
+ }
115
+ } catch {
116
+ cleanRel = cleanRel.replace(/^mcard:\/\//, '');
117
+ }
118
+ }
119
+ cleanRel = cleanRel.replace(/:/g, '/').replace(/^[/\\]+/, '');
120
+ if (cleanRel === wsDir || cleanRel.startsWith(wsDir + '/')) {
121
+ const sub = cleanRel === wsDir ? '' : cleanRel.slice(wsDir.length + 1);
122
+ return resolve(wsRoot, sub);
123
+ }
124
+ if (dRoot) {
125
+ const cand1 = resolve(dRoot, cleanRel);
126
+ if (existsSync(cand1)) {
127
+ return cand1;
128
+ }
129
+ const dBasename = basename(dRoot);
130
+ const prefix1 = `data/${dBasename}/`;
131
+ const prefix2 = `${dBasename}/`;
132
+ if (cleanRel.startsWith(prefix1)) {
133
+ const stripped = cleanRel.slice(prefix1.length);
134
+ const cand = resolve(dRoot, stripped);
135
+ if (existsSync(cand)) return cand;
136
+ } else if (cleanRel.startsWith(prefix2)) {
137
+ const stripped = cleanRel.slice(prefix2.length);
138
+ const cand = resolve(dRoot, stripped);
139
+ if (existsSync(cand)) return cand;
140
+ }
141
+ }
142
+
143
+ const candRoot = resolve(rootDir, cleanRel);
144
+ if (existsSync(candRoot)) {
145
+ return candRoot;
146
+ }
147
+
148
+ const candCwd = resolve(process.cwd(), cleanRel);
149
+ if (existsSync(candCwd)) {
150
+ return candCwd;
151
+ }
152
+
153
+ if (cleanRel.startsWith('assets/')) {
154
+ const candStudioAsset = resolve(rootDir, cleanRel);
155
+ if (existsSync(candStudioAsset)) return candStudioAsset;
156
+ const candCwdStudioAsset = resolve(process.cwd(), 'mcard-studio', cleanRel);
157
+ if (existsSync(candCwdStudioAsset)) return candCwdStudioAsset;
158
+ }
159
+
160
+ if (dRoot) {
161
+ const dBasename = basename(dRoot);
162
+ if (cleanRel.startsWith(`data/${dBasename}/`)) {
163
+ return resolve(dRoot, cleanRel.slice(`data/${dBasename}/`.length));
164
+ }
165
+ if (cleanRel.startsWith(`${dBasename}/`)) {
166
+ return resolve(dRoot, cleanRel.slice(`${dBasename}/`.length));
167
+ }
168
+ if (cleanRel.startsWith('cards/') || cleanRel.startsWith('guest/')) {
169
+ return resolve(dRoot, cleanRel);
170
+ }
171
+ }
172
+
173
+ return resolve(rootDir, cleanRel);
174
+ }
175
+
60
176
  /**
61
177
  * Security containment check (INV-PC-09): ensures the target path is strictly
62
178
  * within any configured `vfs.scan_roots` directory or the resolved workspace root.
@@ -68,10 +184,30 @@ export function isPathAllowed(
68
184
  rootDir: string = repoRoot(),
69
185
  config: PathsConfig = PATHS,
70
186
  ): boolean {
71
- const resolved = resolve(rootDir, targetPath);
72
- const allowedRoots = new Set<string>([resolve(workspaceRoot(config))]);
187
+ const wsDir = config.paths.workspace_dirname;
188
+ const wsRoot = resolve(workspaceRoot(config));
189
+ const resolved = resolveHostPath(targetPath, rootDir, config);
190
+ const dRoot = dataRoot();
191
+
192
+ const allowedRoots = new Set<string>([wsRoot]);
193
+ if (dRoot) {
194
+ allowedRoots.add(dRoot);
195
+ }
73
196
  for (const scanRoot of config.vfs.scan_roots) {
74
- allowedRoots.add(resolve(rootDir, scanRoot));
197
+ if (scanRoot === wsDir) {
198
+ allowedRoots.add(wsRoot);
199
+ } else {
200
+ allowedRoots.add(resolve(rootDir, scanRoot));
201
+ }
202
+ }
203
+ if (config.workspaces?.directory_projections) {
204
+ for (const proj of config.workspaces.directory_projections) {
205
+ if (proj.path === wsDir) {
206
+ allowedRoots.add(wsRoot);
207
+ } else {
208
+ allowedRoots.add(resolve(rootDir, proj.path));
209
+ }
210
+ }
75
211
  }
76
212
  for (const root of allowedRoots) {
77
213
  if (resolved === root || resolved.startsWith(root + '/')) return true;
@@ -89,8 +225,10 @@ export function isPathWritable(
89
225
  rootDir: string = repoRoot(),
90
226
  config: PathsConfig = PATHS,
91
227
  ): boolean {
92
- const resolved = resolve(rootDir, targetPath);
228
+ const resolved = resolveHostPath(targetPath, rootDir, config);
93
229
  const wsRoot = resolve(workspaceRoot(config));
230
+ const dRoot = dataRoot();
231
+ if (dRoot && (resolved === dRoot || resolved.startsWith(dRoot + '/'))) return true;
94
232
  return resolved === wsRoot || resolved.startsWith(wsRoot + '/');
95
233
  }
96
234
 
@@ -48,6 +48,10 @@ export function sniffMimeType(filePath: string): string {
48
48
  }
49
49
  if (ext === 'rs') return 'text/rust';
50
50
  if (ext === 'sh') return 'text/x-sh';
51
+ if (ext === 'dxf') return 'image/vnd.dxf';
52
+ if (ext === 'webm') return 'video/webm';
53
+ if (ext === 'ogg') return 'audio/ogg';
54
+ if (ext === 'flac') return 'audio/flac';
51
55
  return 'application/octet-stream';
52
56
  }
53
57