Subramanya97 commited on
Commit
6d57fe0
·
1 Parent(s): 5f9654f

Deploy from markdownfs@ee79781

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.dockerignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ target/
2
+ .git/
3
+ docs/
4
+ huggingface/
5
+ *.md
6
+ !README.md
Cargo.lock ADDED
@@ -0,0 +1,1816 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "aho-corasick"
7
+ version = "1.1.4"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
10
+ dependencies = [
11
+ "memchr",
12
+ ]
13
+
14
+ [[package]]
15
+ name = "android_system_properties"
16
+ version = "0.1.5"
17
+ source = "registry+https://github.com/rust-lang/crates.io-index"
18
+ checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
19
+ dependencies = [
20
+ "libc",
21
+ ]
22
+
23
+ [[package]]
24
+ name = "anstream"
25
+ version = "1.0.0"
26
+ source = "registry+https://github.com/rust-lang/crates.io-index"
27
+ checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
28
+ dependencies = [
29
+ "anstyle",
30
+ "anstyle-parse",
31
+ "anstyle-query",
32
+ "anstyle-wincon",
33
+ "colorchoice",
34
+ "is_terminal_polyfill",
35
+ "utf8parse",
36
+ ]
37
+
38
+ [[package]]
39
+ name = "anstyle"
40
+ version = "1.0.14"
41
+ source = "registry+https://github.com/rust-lang/crates.io-index"
42
+ checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
43
+
44
+ [[package]]
45
+ name = "anstyle-parse"
46
+ version = "1.0.0"
47
+ source = "registry+https://github.com/rust-lang/crates.io-index"
48
+ checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
49
+ dependencies = [
50
+ "utf8parse",
51
+ ]
52
+
53
+ [[package]]
54
+ name = "anstyle-query"
55
+ version = "1.1.5"
56
+ source = "registry+https://github.com/rust-lang/crates.io-index"
57
+ checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
58
+ dependencies = [
59
+ "windows-sys 0.61.2",
60
+ ]
61
+
62
+ [[package]]
63
+ name = "anstyle-wincon"
64
+ version = "3.0.11"
65
+ source = "registry+https://github.com/rust-lang/crates.io-index"
66
+ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
67
+ dependencies = [
68
+ "anstyle",
69
+ "once_cell_polyfill",
70
+ "windows-sys 0.61.2",
71
+ ]
72
+
73
+ [[package]]
74
+ name = "async-trait"
75
+ version = "0.1.89"
76
+ source = "registry+https://github.com/rust-lang/crates.io-index"
77
+ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
78
+ dependencies = [
79
+ "proc-macro2",
80
+ "quote",
81
+ "syn",
82
+ ]
83
+
84
+ [[package]]
85
+ name = "atomic-waker"
86
+ version = "1.1.2"
87
+ source = "registry+https://github.com/rust-lang/crates.io-index"
88
+ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
89
+
90
+ [[package]]
91
+ name = "autocfg"
92
+ version = "1.5.0"
93
+ source = "registry+https://github.com/rust-lang/crates.io-index"
94
+ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
95
+
96
+ [[package]]
97
+ name = "axum"
98
+ version = "0.8.8"
99
+ source = "registry+https://github.com/rust-lang/crates.io-index"
100
+ checksum = "8b52af3cb4058c895d37317bb27508dccc8e5f2d39454016b297bf4a400597b8"
101
+ dependencies = [
102
+ "axum-core",
103
+ "bytes",
104
+ "form_urlencoded",
105
+ "futures-util",
106
+ "http",
107
+ "http-body",
108
+ "http-body-util",
109
+ "hyper",
110
+ "hyper-util",
111
+ "itoa",
112
+ "matchit",
113
+ "memchr",
114
+ "mime",
115
+ "percent-encoding",
116
+ "pin-project-lite",
117
+ "serde_core",
118
+ "serde_json",
119
+ "serde_path_to_error",
120
+ "serde_urlencoded",
121
+ "sync_wrapper",
122
+ "tokio",
123
+ "tower",
124
+ "tower-layer",
125
+ "tower-service",
126
+ "tracing",
127
+ ]
128
+
129
+ [[package]]
130
+ name = "axum-core"
131
+ version = "0.5.6"
132
+ source = "registry+https://github.com/rust-lang/crates.io-index"
133
+ checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
134
+ dependencies = [
135
+ "bytes",
136
+ "futures-core",
137
+ "http",
138
+ "http-body",
139
+ "http-body-util",
140
+ "mime",
141
+ "pin-project-lite",
142
+ "sync_wrapper",
143
+ "tower-layer",
144
+ "tower-service",
145
+ "tracing",
146
+ ]
147
+
148
+ [[package]]
149
+ name = "base64"
150
+ version = "0.22.1"
151
+ source = "registry+https://github.com/rust-lang/crates.io-index"
152
+ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
153
+
154
+ [[package]]
155
+ name = "bincode"
156
+ version = "1.3.3"
157
+ source = "registry+https://github.com/rust-lang/crates.io-index"
158
+ checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
159
+ dependencies = [
160
+ "serde",
161
+ ]
162
+
163
+ [[package]]
164
+ name = "bitflags"
165
+ version = "2.11.0"
166
+ source = "registry+https://github.com/rust-lang/crates.io-index"
167
+ checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
168
+
169
+ [[package]]
170
+ name = "block-buffer"
171
+ version = "0.10.4"
172
+ source = "registry+https://github.com/rust-lang/crates.io-index"
173
+ checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
174
+ dependencies = [
175
+ "generic-array",
176
+ ]
177
+
178
+ [[package]]
179
+ name = "bumpalo"
180
+ version = "3.20.2"
181
+ source = "registry+https://github.com/rust-lang/crates.io-index"
182
+ checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
183
+
184
+ [[package]]
185
+ name = "bytes"
186
+ version = "1.11.1"
187
+ source = "registry+https://github.com/rust-lang/crates.io-index"
188
+ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
189
+
190
+ [[package]]
191
+ name = "cc"
192
+ version = "1.2.60"
193
+ source = "registry+https://github.com/rust-lang/crates.io-index"
194
+ checksum = "43c5703da9466b66a946814e1adf53ea2c90f10063b86290cc9eb67ce3478a20"
195
+ dependencies = [
196
+ "find-msvc-tools",
197
+ "shlex",
198
+ ]
199
+
200
+ [[package]]
201
+ name = "cfg-if"
202
+ version = "1.0.4"
203
+ source = "registry+https://github.com/rust-lang/crates.io-index"
204
+ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
205
+
206
+ [[package]]
207
+ name = "cfg_aliases"
208
+ version = "0.2.1"
209
+ source = "registry+https://github.com/rust-lang/crates.io-index"
210
+ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
211
+
212
+ [[package]]
213
+ name = "chrono"
214
+ version = "0.4.44"
215
+ source = "registry+https://github.com/rust-lang/crates.io-index"
216
+ checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"
217
+ dependencies = [
218
+ "iana-time-zone",
219
+ "js-sys",
220
+ "num-traits",
221
+ "serde",
222
+ "wasm-bindgen",
223
+ "windows-link",
224
+ ]
225
+
226
+ [[package]]
227
+ name = "clap"
228
+ version = "4.6.1"
229
+ source = "registry+https://github.com/rust-lang/crates.io-index"
230
+ checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
231
+ dependencies = [
232
+ "clap_builder",
233
+ "clap_derive",
234
+ ]
235
+
236
+ [[package]]
237
+ name = "clap_builder"
238
+ version = "4.6.0"
239
+ source = "registry+https://github.com/rust-lang/crates.io-index"
240
+ checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
241
+ dependencies = [
242
+ "anstream",
243
+ "anstyle",
244
+ "clap_lex",
245
+ "strsim",
246
+ ]
247
+
248
+ [[package]]
249
+ name = "clap_derive"
250
+ version = "4.6.1"
251
+ source = "registry+https://github.com/rust-lang/crates.io-index"
252
+ checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"
253
+ dependencies = [
254
+ "heck",
255
+ "proc-macro2",
256
+ "quote",
257
+ "syn",
258
+ ]
259
+
260
+ [[package]]
261
+ name = "clap_lex"
262
+ version = "1.1.0"
263
+ source = "registry+https://github.com/rust-lang/crates.io-index"
264
+ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
265
+
266
+ [[package]]
267
+ name = "clipboard-win"
268
+ version = "5.4.1"
269
+ source = "registry+https://github.com/rust-lang/crates.io-index"
270
+ checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
271
+ dependencies = [
272
+ "error-code",
273
+ ]
274
+
275
+ [[package]]
276
+ name = "colorchoice"
277
+ version = "1.0.5"
278
+ source = "registry+https://github.com/rust-lang/crates.io-index"
279
+ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
280
+
281
+ [[package]]
282
+ name = "core-foundation-sys"
283
+ version = "0.8.7"
284
+ source = "registry+https://github.com/rust-lang/crates.io-index"
285
+ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
286
+
287
+ [[package]]
288
+ name = "cpufeatures"
289
+ version = "0.2.17"
290
+ source = "registry+https://github.com/rust-lang/crates.io-index"
291
+ checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
292
+ dependencies = [
293
+ "libc",
294
+ ]
295
+
296
+ [[package]]
297
+ name = "crypto-common"
298
+ version = "0.1.7"
299
+ source = "registry+https://github.com/rust-lang/crates.io-index"
300
+ checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
301
+ dependencies = [
302
+ "generic-array",
303
+ "typenum",
304
+ ]
305
+
306
+ [[package]]
307
+ name = "darling"
308
+ version = "0.23.0"
309
+ source = "registry+https://github.com/rust-lang/crates.io-index"
310
+ checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
311
+ dependencies = [
312
+ "darling_core",
313
+ "darling_macro",
314
+ ]
315
+
316
+ [[package]]
317
+ name = "darling_core"
318
+ version = "0.23.0"
319
+ source = "registry+https://github.com/rust-lang/crates.io-index"
320
+ checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"
321
+ dependencies = [
322
+ "ident_case",
323
+ "proc-macro2",
324
+ "quote",
325
+ "strsim",
326
+ "syn",
327
+ ]
328
+
329
+ [[package]]
330
+ name = "darling_macro"
331
+ version = "0.23.0"
332
+ source = "registry+https://github.com/rust-lang/crates.io-index"
333
+ checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
334
+ dependencies = [
335
+ "darling_core",
336
+ "quote",
337
+ "syn",
338
+ ]
339
+
340
+ [[package]]
341
+ name = "digest"
342
+ version = "0.10.7"
343
+ source = "registry+https://github.com/rust-lang/crates.io-index"
344
+ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
345
+ dependencies = [
346
+ "block-buffer",
347
+ "crypto-common",
348
+ ]
349
+
350
+ [[package]]
351
+ name = "dyn-clone"
352
+ version = "1.0.20"
353
+ source = "registry+https://github.com/rust-lang/crates.io-index"
354
+ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
355
+
356
+ [[package]]
357
+ name = "endian-type"
358
+ version = "0.1.2"
359
+ source = "registry+https://github.com/rust-lang/crates.io-index"
360
+ checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d"
361
+
362
+ [[package]]
363
+ name = "equivalent"
364
+ version = "1.0.2"
365
+ source = "registry+https://github.com/rust-lang/crates.io-index"
366
+ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
367
+
368
+ [[package]]
369
+ name = "errno"
370
+ version = "0.3.14"
371
+ source = "registry+https://github.com/rust-lang/crates.io-index"
372
+ checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
373
+ dependencies = [
374
+ "libc",
375
+ "windows-sys 0.61.2",
376
+ ]
377
+
378
+ [[package]]
379
+ name = "error-code"
380
+ version = "3.3.2"
381
+ source = "registry+https://github.com/rust-lang/crates.io-index"
382
+ checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59"
383
+
384
+ [[package]]
385
+ name = "fd-lock"
386
+ version = "4.0.4"
387
+ source = "registry+https://github.com/rust-lang/crates.io-index"
388
+ checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78"
389
+ dependencies = [
390
+ "cfg-if",
391
+ "rustix",
392
+ "windows-sys 0.59.0",
393
+ ]
394
+
395
+ [[package]]
396
+ name = "find-msvc-tools"
397
+ version = "0.1.9"
398
+ source = "registry+https://github.com/rust-lang/crates.io-index"
399
+ checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
400
+
401
+ [[package]]
402
+ name = "form_urlencoded"
403
+ version = "1.2.2"
404
+ source = "registry+https://github.com/rust-lang/crates.io-index"
405
+ checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
406
+ dependencies = [
407
+ "percent-encoding",
408
+ ]
409
+
410
+ [[package]]
411
+ name = "fuser"
412
+ version = "0.17.0"
413
+ source = "registry+https://github.com/rust-lang/crates.io-index"
414
+ checksum = "80a5eca878900c2e39e9e52fd797954b7fc39eeefc8558257114bfea6a698fcf"
415
+ dependencies = [
416
+ "bitflags",
417
+ "libc",
418
+ "log",
419
+ "memchr",
420
+ "nix 0.30.1",
421
+ "num_enum",
422
+ "page_size",
423
+ "parking_lot",
424
+ "pkg-config",
425
+ "ref-cast",
426
+ "smallvec",
427
+ "zerocopy",
428
+ ]
429
+
430
+ [[package]]
431
+ name = "futures"
432
+ version = "0.3.32"
433
+ source = "registry+https://github.com/rust-lang/crates.io-index"
434
+ checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"
435
+ dependencies = [
436
+ "futures-channel",
437
+ "futures-core",
438
+ "futures-executor",
439
+ "futures-io",
440
+ "futures-sink",
441
+ "futures-task",
442
+ "futures-util",
443
+ ]
444
+
445
+ [[package]]
446
+ name = "futures-channel"
447
+ version = "0.3.32"
448
+ source = "registry+https://github.com/rust-lang/crates.io-index"
449
+ checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
450
+ dependencies = [
451
+ "futures-core",
452
+ "futures-sink",
453
+ ]
454
+
455
+ [[package]]
456
+ name = "futures-core"
457
+ version = "0.3.32"
458
+ source = "registry+https://github.com/rust-lang/crates.io-index"
459
+ checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
460
+
461
+ [[package]]
462
+ name = "futures-executor"
463
+ version = "0.3.32"
464
+ source = "registry+https://github.com/rust-lang/crates.io-index"
465
+ checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"
466
+ dependencies = [
467
+ "futures-core",
468
+ "futures-task",
469
+ "futures-util",
470
+ ]
471
+
472
+ [[package]]
473
+ name = "futures-io"
474
+ version = "0.3.32"
475
+ source = "registry+https://github.com/rust-lang/crates.io-index"
476
+ checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
477
+
478
+ [[package]]
479
+ name = "futures-macro"
480
+ version = "0.3.32"
481
+ source = "registry+https://github.com/rust-lang/crates.io-index"
482
+ checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
483
+ dependencies = [
484
+ "proc-macro2",
485
+ "quote",
486
+ "syn",
487
+ ]
488
+
489
+ [[package]]
490
+ name = "futures-sink"
491
+ version = "0.3.32"
492
+ source = "registry+https://github.com/rust-lang/crates.io-index"
493
+ checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
494
+
495
+ [[package]]
496
+ name = "futures-task"
497
+ version = "0.3.32"
498
+ source = "registry+https://github.com/rust-lang/crates.io-index"
499
+ checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
500
+
501
+ [[package]]
502
+ name = "futures-util"
503
+ version = "0.3.32"
504
+ source = "registry+https://github.com/rust-lang/crates.io-index"
505
+ checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
506
+ dependencies = [
507
+ "futures-channel",
508
+ "futures-core",
509
+ "futures-io",
510
+ "futures-macro",
511
+ "futures-sink",
512
+ "futures-task",
513
+ "memchr",
514
+ "pin-project-lite",
515
+ "slab",
516
+ ]
517
+
518
+ [[package]]
519
+ name = "generic-array"
520
+ version = "0.14.7"
521
+ source = "registry+https://github.com/rust-lang/crates.io-index"
522
+ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
523
+ dependencies = [
524
+ "typenum",
525
+ "version_check",
526
+ ]
527
+
528
+ [[package]]
529
+ name = "glob"
530
+ version = "0.3.3"
531
+ source = "registry+https://github.com/rust-lang/crates.io-index"
532
+ checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
533
+
534
+ [[package]]
535
+ name = "hashbrown"
536
+ version = "0.17.0"
537
+ source = "registry+https://github.com/rust-lang/crates.io-index"
538
+ checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"
539
+
540
+ [[package]]
541
+ name = "heck"
542
+ version = "0.5.0"
543
+ source = "registry+https://github.com/rust-lang/crates.io-index"
544
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
545
+
546
+ [[package]]
547
+ name = "home"
548
+ version = "0.5.12"
549
+ source = "registry+https://github.com/rust-lang/crates.io-index"
550
+ checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
551
+ dependencies = [
552
+ "windows-sys 0.61.2",
553
+ ]
554
+
555
+ [[package]]
556
+ name = "http"
557
+ version = "1.4.0"
558
+ source = "registry+https://github.com/rust-lang/crates.io-index"
559
+ checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"
560
+ dependencies = [
561
+ "bytes",
562
+ "itoa",
563
+ ]
564
+
565
+ [[package]]
566
+ name = "http-body"
567
+ version = "1.0.1"
568
+ source = "registry+https://github.com/rust-lang/crates.io-index"
569
+ checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
570
+ dependencies = [
571
+ "bytes",
572
+ "http",
573
+ ]
574
+
575
+ [[package]]
576
+ name = "http-body-util"
577
+ version = "0.1.3"
578
+ source = "registry+https://github.com/rust-lang/crates.io-index"
579
+ checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
580
+ dependencies = [
581
+ "bytes",
582
+ "futures-core",
583
+ "http",
584
+ "http-body",
585
+ "pin-project-lite",
586
+ ]
587
+
588
+ [[package]]
589
+ name = "httparse"
590
+ version = "1.10.1"
591
+ source = "registry+https://github.com/rust-lang/crates.io-index"
592
+ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
593
+
594
+ [[package]]
595
+ name = "httpdate"
596
+ version = "1.0.3"
597
+ source = "registry+https://github.com/rust-lang/crates.io-index"
598
+ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
599
+
600
+ [[package]]
601
+ name = "hyper"
602
+ version = "1.9.0"
603
+ source = "registry+https://github.com/rust-lang/crates.io-index"
604
+ checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca"
605
+ dependencies = [
606
+ "atomic-waker",
607
+ "bytes",
608
+ "futures-channel",
609
+ "futures-core",
610
+ "http",
611
+ "http-body",
612
+ "httparse",
613
+ "httpdate",
614
+ "itoa",
615
+ "pin-project-lite",
616
+ "smallvec",
617
+ "tokio",
618
+ ]
619
+
620
+ [[package]]
621
+ name = "hyper-util"
622
+ version = "0.1.20"
623
+ source = "registry+https://github.com/rust-lang/crates.io-index"
624
+ checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
625
+ dependencies = [
626
+ "bytes",
627
+ "http",
628
+ "http-body",
629
+ "hyper",
630
+ "pin-project-lite",
631
+ "tokio",
632
+ "tower-service",
633
+ ]
634
+
635
+ [[package]]
636
+ name = "iana-time-zone"
637
+ version = "0.1.65"
638
+ source = "registry+https://github.com/rust-lang/crates.io-index"
639
+ checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
640
+ dependencies = [
641
+ "android_system_properties",
642
+ "core-foundation-sys",
643
+ "iana-time-zone-haiku",
644
+ "js-sys",
645
+ "log",
646
+ "wasm-bindgen",
647
+ "windows-core",
648
+ ]
649
+
650
+ [[package]]
651
+ name = "iana-time-zone-haiku"
652
+ version = "0.1.2"
653
+ source = "registry+https://github.com/rust-lang/crates.io-index"
654
+ checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
655
+ dependencies = [
656
+ "cc",
657
+ ]
658
+
659
+ [[package]]
660
+ name = "ident_case"
661
+ version = "1.0.1"
662
+ source = "registry+https://github.com/rust-lang/crates.io-index"
663
+ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
664
+
665
+ [[package]]
666
+ name = "indexmap"
667
+ version = "2.14.0"
668
+ source = "registry+https://github.com/rust-lang/crates.io-index"
669
+ checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
670
+ dependencies = [
671
+ "equivalent",
672
+ "hashbrown",
673
+ ]
674
+
675
+ [[package]]
676
+ name = "is_terminal_polyfill"
677
+ version = "1.70.2"
678
+ source = "registry+https://github.com/rust-lang/crates.io-index"
679
+ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
680
+
681
+ [[package]]
682
+ name = "itoa"
683
+ version = "1.0.18"
684
+ source = "registry+https://github.com/rust-lang/crates.io-index"
685
+ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
686
+
687
+ [[package]]
688
+ name = "js-sys"
689
+ version = "0.3.95"
690
+ source = "registry+https://github.com/rust-lang/crates.io-index"
691
+ checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca"
692
+ dependencies = [
693
+ "once_cell",
694
+ "wasm-bindgen",
695
+ ]
696
+
697
+ [[package]]
698
+ name = "lazy_static"
699
+ version = "1.5.0"
700
+ source = "registry+https://github.com/rust-lang/crates.io-index"
701
+ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
702
+
703
+ [[package]]
704
+ name = "libc"
705
+ version = "0.2.184"
706
+ source = "registry+https://github.com/rust-lang/crates.io-index"
707
+ checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af"
708
+
709
+ [[package]]
710
+ name = "linux-raw-sys"
711
+ version = "0.12.1"
712
+ source = "registry+https://github.com/rust-lang/crates.io-index"
713
+ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
714
+
715
+ [[package]]
716
+ name = "lock_api"
717
+ version = "0.4.14"
718
+ source = "registry+https://github.com/rust-lang/crates.io-index"
719
+ checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
720
+ dependencies = [
721
+ "scopeguard",
722
+ ]
723
+
724
+ [[package]]
725
+ name = "log"
726
+ version = "0.4.29"
727
+ source = "registry+https://github.com/rust-lang/crates.io-index"
728
+ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
729
+
730
+ [[package]]
731
+ name = "markdownfs"
732
+ version = "0.2.0"
733
+ dependencies = [
734
+ "axum",
735
+ "bincode",
736
+ "bytes",
737
+ "chrono",
738
+ "clap",
739
+ "fuser",
740
+ "glob",
741
+ "memmap2",
742
+ "regex",
743
+ "rmcp",
744
+ "rustyline",
745
+ "serde",
746
+ "serde_json",
747
+ "sha2",
748
+ "thiserror",
749
+ "tokio",
750
+ "tower-http",
751
+ "tracing",
752
+ "tracing-subscriber",
753
+ ]
754
+
755
+ [[package]]
756
+ name = "matchers"
757
+ version = "0.2.0"
758
+ source = "registry+https://github.com/rust-lang/crates.io-index"
759
+ checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
760
+ dependencies = [
761
+ "regex-automata",
762
+ ]
763
+
764
+ [[package]]
765
+ name = "matchit"
766
+ version = "0.8.4"
767
+ source = "registry+https://github.com/rust-lang/crates.io-index"
768
+ checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
769
+
770
+ [[package]]
771
+ name = "memchr"
772
+ version = "2.8.0"
773
+ source = "registry+https://github.com/rust-lang/crates.io-index"
774
+ checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
775
+
776
+ [[package]]
777
+ name = "memmap2"
778
+ version = "0.9.10"
779
+ source = "registry+https://github.com/rust-lang/crates.io-index"
780
+ checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3"
781
+ dependencies = [
782
+ "libc",
783
+ ]
784
+
785
+ [[package]]
786
+ name = "memoffset"
787
+ version = "0.9.1"
788
+ source = "registry+https://github.com/rust-lang/crates.io-index"
789
+ checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
790
+ dependencies = [
791
+ "autocfg",
792
+ ]
793
+
794
+ [[package]]
795
+ name = "mime"
796
+ version = "0.3.17"
797
+ source = "registry+https://github.com/rust-lang/crates.io-index"
798
+ checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
799
+
800
+ [[package]]
801
+ name = "mio"
802
+ version = "1.2.0"
803
+ source = "registry+https://github.com/rust-lang/crates.io-index"
804
+ checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
805
+ dependencies = [
806
+ "libc",
807
+ "wasi",
808
+ "windows-sys 0.61.2",
809
+ ]
810
+
811
+ [[package]]
812
+ name = "nibble_vec"
813
+ version = "0.1.0"
814
+ source = "registry+https://github.com/rust-lang/crates.io-index"
815
+ checksum = "77a5d83df9f36fe23f0c3648c6bbb8b0298bb5f1939c8f2704431371f4b84d43"
816
+ dependencies = [
817
+ "smallvec",
818
+ ]
819
+
820
+ [[package]]
821
+ name = "nix"
822
+ version = "0.29.0"
823
+ source = "registry+https://github.com/rust-lang/crates.io-index"
824
+ checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
825
+ dependencies = [
826
+ "bitflags",
827
+ "cfg-if",
828
+ "cfg_aliases",
829
+ "libc",
830
+ ]
831
+
832
+ [[package]]
833
+ name = "nix"
834
+ version = "0.30.1"
835
+ source = "registry+https://github.com/rust-lang/crates.io-index"
836
+ checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6"
837
+ dependencies = [
838
+ "bitflags",
839
+ "cfg-if",
840
+ "cfg_aliases",
841
+ "libc",
842
+ "memoffset",
843
+ ]
844
+
845
+ [[package]]
846
+ name = "nu-ansi-term"
847
+ version = "0.50.3"
848
+ source = "registry+https://github.com/rust-lang/crates.io-index"
849
+ checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
850
+ dependencies = [
851
+ "windows-sys 0.61.2",
852
+ ]
853
+
854
+ [[package]]
855
+ name = "num-traits"
856
+ version = "0.2.19"
857
+ source = "registry+https://github.com/rust-lang/crates.io-index"
858
+ checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
859
+ dependencies = [
860
+ "autocfg",
861
+ ]
862
+
863
+ [[package]]
864
+ name = "num_enum"
865
+ version = "0.7.6"
866
+ source = "registry+https://github.com/rust-lang/crates.io-index"
867
+ checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"
868
+ dependencies = [
869
+ "num_enum_derive",
870
+ "rustversion",
871
+ ]
872
+
873
+ [[package]]
874
+ name = "num_enum_derive"
875
+ version = "0.7.6"
876
+ source = "registry+https://github.com/rust-lang/crates.io-index"
877
+ checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
878
+ dependencies = [
879
+ "proc-macro-crate",
880
+ "proc-macro2",
881
+ "quote",
882
+ "syn",
883
+ ]
884
+
885
+ [[package]]
886
+ name = "once_cell"
887
+ version = "1.21.4"
888
+ source = "registry+https://github.com/rust-lang/crates.io-index"
889
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
890
+
891
+ [[package]]
892
+ name = "once_cell_polyfill"
893
+ version = "1.70.2"
894
+ source = "registry+https://github.com/rust-lang/crates.io-index"
895
+ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
896
+
897
+ [[package]]
898
+ name = "page_size"
899
+ version = "0.6.0"
900
+ source = "registry+https://github.com/rust-lang/crates.io-index"
901
+ checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da"
902
+ dependencies = [
903
+ "libc",
904
+ "winapi",
905
+ ]
906
+
907
+ [[package]]
908
+ name = "parking_lot"
909
+ version = "0.12.5"
910
+ source = "registry+https://github.com/rust-lang/crates.io-index"
911
+ checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
912
+ dependencies = [
913
+ "lock_api",
914
+ "parking_lot_core",
915
+ ]
916
+
917
+ [[package]]
918
+ name = "parking_lot_core"
919
+ version = "0.9.12"
920
+ source = "registry+https://github.com/rust-lang/crates.io-index"
921
+ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
922
+ dependencies = [
923
+ "cfg-if",
924
+ "libc",
925
+ "redox_syscall",
926
+ "smallvec",
927
+ "windows-link",
928
+ ]
929
+
930
+ [[package]]
931
+ name = "pastey"
932
+ version = "0.2.1"
933
+ source = "registry+https://github.com/rust-lang/crates.io-index"
934
+ checksum = "b867cad97c0791bbd3aaa6472142568c6c9e8f71937e98379f584cfb0cf35bec"
935
+
936
+ [[package]]
937
+ name = "percent-encoding"
938
+ version = "2.3.2"
939
+ source = "registry+https://github.com/rust-lang/crates.io-index"
940
+ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
941
+
942
+ [[package]]
943
+ name = "pin-project-lite"
944
+ version = "0.2.17"
945
+ source = "registry+https://github.com/rust-lang/crates.io-index"
946
+ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
947
+
948
+ [[package]]
949
+ name = "pkg-config"
950
+ version = "0.3.33"
951
+ source = "registry+https://github.com/rust-lang/crates.io-index"
952
+ checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
953
+
954
+ [[package]]
955
+ name = "proc-macro-crate"
956
+ version = "3.5.0"
957
+ source = "registry+https://github.com/rust-lang/crates.io-index"
958
+ checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
959
+ dependencies = [
960
+ "toml_edit",
961
+ ]
962
+
963
+ [[package]]
964
+ name = "proc-macro2"
965
+ version = "1.0.106"
966
+ source = "registry+https://github.com/rust-lang/crates.io-index"
967
+ checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
968
+ dependencies = [
969
+ "unicode-ident",
970
+ ]
971
+
972
+ [[package]]
973
+ name = "quote"
974
+ version = "1.0.45"
975
+ source = "registry+https://github.com/rust-lang/crates.io-index"
976
+ checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
977
+ dependencies = [
978
+ "proc-macro2",
979
+ ]
980
+
981
+ [[package]]
982
+ name = "radix_trie"
983
+ version = "0.2.1"
984
+ source = "registry+https://github.com/rust-lang/crates.io-index"
985
+ checksum = "c069c179fcdc6a2fe24d8d18305cf085fdbd4f922c041943e203685d6a1c58fd"
986
+ dependencies = [
987
+ "endian-type",
988
+ "nibble_vec",
989
+ ]
990
+
991
+ [[package]]
992
+ name = "redox_syscall"
993
+ version = "0.5.18"
994
+ source = "registry+https://github.com/rust-lang/crates.io-index"
995
+ checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
996
+ dependencies = [
997
+ "bitflags",
998
+ ]
999
+
1000
+ [[package]]
1001
+ name = "ref-cast"
1002
+ version = "1.0.25"
1003
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1004
+ checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d"
1005
+ dependencies = [
1006
+ "ref-cast-impl",
1007
+ ]
1008
+
1009
+ [[package]]
1010
+ name = "ref-cast-impl"
1011
+ version = "1.0.25"
1012
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1013
+ checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"
1014
+ dependencies = [
1015
+ "proc-macro2",
1016
+ "quote",
1017
+ "syn",
1018
+ ]
1019
+
1020
+ [[package]]
1021
+ name = "regex"
1022
+ version = "1.12.3"
1023
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1024
+ checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
1025
+ dependencies = [
1026
+ "aho-corasick",
1027
+ "memchr",
1028
+ "regex-automata",
1029
+ "regex-syntax",
1030
+ ]
1031
+
1032
+ [[package]]
1033
+ name = "regex-automata"
1034
+ version = "0.4.14"
1035
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1036
+ checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
1037
+ dependencies = [
1038
+ "aho-corasick",
1039
+ "memchr",
1040
+ "regex-syntax",
1041
+ ]
1042
+
1043
+ [[package]]
1044
+ name = "regex-syntax"
1045
+ version = "0.8.10"
1046
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1047
+ checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
1048
+
1049
+ [[package]]
1050
+ name = "rmcp"
1051
+ version = "1.4.0"
1052
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1053
+ checksum = "f542f74cf247da16f19bbc87e298cd201e912314f4083e88cdd671f44f5fcb53"
1054
+ dependencies = [
1055
+ "async-trait",
1056
+ "base64",
1057
+ "chrono",
1058
+ "futures",
1059
+ "pastey",
1060
+ "pin-project-lite",
1061
+ "rmcp-macros",
1062
+ "schemars",
1063
+ "serde",
1064
+ "serde_json",
1065
+ "thiserror",
1066
+ "tokio",
1067
+ "tokio-util",
1068
+ "tracing",
1069
+ ]
1070
+
1071
+ [[package]]
1072
+ name = "rmcp-macros"
1073
+ version = "1.4.0"
1074
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1075
+ checksum = "b2391e4ae47f314e70eaafb6c7bd82e495e770b935448864446302143019151f"
1076
+ dependencies = [
1077
+ "darling",
1078
+ "proc-macro2",
1079
+ "quote",
1080
+ "serde_json",
1081
+ "syn",
1082
+ ]
1083
+
1084
+ [[package]]
1085
+ name = "rustix"
1086
+ version = "1.1.4"
1087
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1088
+ checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
1089
+ dependencies = [
1090
+ "bitflags",
1091
+ "errno",
1092
+ "libc",
1093
+ "linux-raw-sys",
1094
+ "windows-sys 0.61.2",
1095
+ ]
1096
+
1097
+ [[package]]
1098
+ name = "rustversion"
1099
+ version = "1.0.22"
1100
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1101
+ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
1102
+
1103
+ [[package]]
1104
+ name = "rustyline"
1105
+ version = "15.0.0"
1106
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1107
+ checksum = "2ee1e066dc922e513bda599c6ccb5f3bb2b0ea5870a579448f2622993f0a9a2f"
1108
+ dependencies = [
1109
+ "bitflags",
1110
+ "cfg-if",
1111
+ "clipboard-win",
1112
+ "fd-lock",
1113
+ "home",
1114
+ "libc",
1115
+ "log",
1116
+ "memchr",
1117
+ "nix 0.29.0",
1118
+ "radix_trie",
1119
+ "unicode-segmentation",
1120
+ "unicode-width",
1121
+ "utf8parse",
1122
+ "windows-sys 0.59.0",
1123
+ ]
1124
+
1125
+ [[package]]
1126
+ name = "ryu"
1127
+ version = "1.0.23"
1128
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1129
+ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
1130
+
1131
+ [[package]]
1132
+ name = "schemars"
1133
+ version = "1.2.1"
1134
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1135
+ checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"
1136
+ dependencies = [
1137
+ "chrono",
1138
+ "dyn-clone",
1139
+ "ref-cast",
1140
+ "schemars_derive",
1141
+ "serde",
1142
+ "serde_json",
1143
+ ]
1144
+
1145
+ [[package]]
1146
+ name = "schemars_derive"
1147
+ version = "1.2.1"
1148
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1149
+ checksum = "7d115b50f4aaeea07e79c1912f645c7513d81715d0420f8bc77a18c6260b307f"
1150
+ dependencies = [
1151
+ "proc-macro2",
1152
+ "quote",
1153
+ "serde_derive_internals",
1154
+ "syn",
1155
+ ]
1156
+
1157
+ [[package]]
1158
+ name = "scopeguard"
1159
+ version = "1.2.0"
1160
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1161
+ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
1162
+
1163
+ [[package]]
1164
+ name = "serde"
1165
+ version = "1.0.228"
1166
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1167
+ checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
1168
+ dependencies = [
1169
+ "serde_core",
1170
+ "serde_derive",
1171
+ ]
1172
+
1173
+ [[package]]
1174
+ name = "serde_core"
1175
+ version = "1.0.228"
1176
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1177
+ checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
1178
+ dependencies = [
1179
+ "serde_derive",
1180
+ ]
1181
+
1182
+ [[package]]
1183
+ name = "serde_derive"
1184
+ version = "1.0.228"
1185
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1186
+ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
1187
+ dependencies = [
1188
+ "proc-macro2",
1189
+ "quote",
1190
+ "syn",
1191
+ ]
1192
+
1193
+ [[package]]
1194
+ name = "serde_derive_internals"
1195
+ version = "0.29.1"
1196
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1197
+ checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"
1198
+ dependencies = [
1199
+ "proc-macro2",
1200
+ "quote",
1201
+ "syn",
1202
+ ]
1203
+
1204
+ [[package]]
1205
+ name = "serde_json"
1206
+ version = "1.0.149"
1207
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1208
+ checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
1209
+ dependencies = [
1210
+ "itoa",
1211
+ "memchr",
1212
+ "serde",
1213
+ "serde_core",
1214
+ "zmij",
1215
+ ]
1216
+
1217
+ [[package]]
1218
+ name = "serde_path_to_error"
1219
+ version = "0.1.20"
1220
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1221
+ checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
1222
+ dependencies = [
1223
+ "itoa",
1224
+ "serde",
1225
+ "serde_core",
1226
+ ]
1227
+
1228
+ [[package]]
1229
+ name = "serde_urlencoded"
1230
+ version = "0.7.1"
1231
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1232
+ checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
1233
+ dependencies = [
1234
+ "form_urlencoded",
1235
+ "itoa",
1236
+ "ryu",
1237
+ "serde",
1238
+ ]
1239
+
1240
+ [[package]]
1241
+ name = "sha2"
1242
+ version = "0.10.9"
1243
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1244
+ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
1245
+ dependencies = [
1246
+ "cfg-if",
1247
+ "cpufeatures",
1248
+ "digest",
1249
+ ]
1250
+
1251
+ [[package]]
1252
+ name = "sharded-slab"
1253
+ version = "0.1.7"
1254
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1255
+ checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
1256
+ dependencies = [
1257
+ "lazy_static",
1258
+ ]
1259
+
1260
+ [[package]]
1261
+ name = "shlex"
1262
+ version = "1.3.0"
1263
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1264
+ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
1265
+
1266
+ [[package]]
1267
+ name = "signal-hook-registry"
1268
+ version = "1.4.8"
1269
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1270
+ checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
1271
+ dependencies = [
1272
+ "errno",
1273
+ "libc",
1274
+ ]
1275
+
1276
+ [[package]]
1277
+ name = "slab"
1278
+ version = "0.4.12"
1279
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1280
+ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
1281
+
1282
+ [[package]]
1283
+ name = "smallvec"
1284
+ version = "1.15.1"
1285
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1286
+ checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
1287
+
1288
+ [[package]]
1289
+ name = "socket2"
1290
+ version = "0.6.3"
1291
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1292
+ checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
1293
+ dependencies = [
1294
+ "libc",
1295
+ "windows-sys 0.61.2",
1296
+ ]
1297
+
1298
+ [[package]]
1299
+ name = "strsim"
1300
+ version = "0.11.1"
1301
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1302
+ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
1303
+
1304
+ [[package]]
1305
+ name = "syn"
1306
+ version = "2.0.117"
1307
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1308
+ checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
1309
+ dependencies = [
1310
+ "proc-macro2",
1311
+ "quote",
1312
+ "unicode-ident",
1313
+ ]
1314
+
1315
+ [[package]]
1316
+ name = "sync_wrapper"
1317
+ version = "1.0.2"
1318
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1319
+ checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
1320
+
1321
+ [[package]]
1322
+ name = "thiserror"
1323
+ version = "2.0.18"
1324
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1325
+ checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
1326
+ dependencies = [
1327
+ "thiserror-impl",
1328
+ ]
1329
+
1330
+ [[package]]
1331
+ name = "thiserror-impl"
1332
+ version = "2.0.18"
1333
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1334
+ checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
1335
+ dependencies = [
1336
+ "proc-macro2",
1337
+ "quote",
1338
+ "syn",
1339
+ ]
1340
+
1341
+ [[package]]
1342
+ name = "thread_local"
1343
+ version = "1.1.9"
1344
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1345
+ checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
1346
+ dependencies = [
1347
+ "cfg-if",
1348
+ ]
1349
+
1350
+ [[package]]
1351
+ name = "tokio"
1352
+ version = "1.51.1"
1353
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1354
+ checksum = "f66bf9585cda4b724d3e78ab34b73fb2bbaba9011b9bfdf69dc836382ea13b8c"
1355
+ dependencies = [
1356
+ "bytes",
1357
+ "libc",
1358
+ "mio",
1359
+ "parking_lot",
1360
+ "pin-project-lite",
1361
+ "signal-hook-registry",
1362
+ "socket2",
1363
+ "tokio-macros",
1364
+ "windows-sys 0.61.2",
1365
+ ]
1366
+
1367
+ [[package]]
1368
+ name = "tokio-macros"
1369
+ version = "2.7.0"
1370
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1371
+ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
1372
+ dependencies = [
1373
+ "proc-macro2",
1374
+ "quote",
1375
+ "syn",
1376
+ ]
1377
+
1378
+ [[package]]
1379
+ name = "tokio-util"
1380
+ version = "0.7.18"
1381
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1382
+ checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
1383
+ dependencies = [
1384
+ "bytes",
1385
+ "futures-core",
1386
+ "futures-sink",
1387
+ "pin-project-lite",
1388
+ "tokio",
1389
+ ]
1390
+
1391
+ [[package]]
1392
+ name = "toml_datetime"
1393
+ version = "1.1.1+spec-1.1.0"
1394
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1395
+ checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
1396
+ dependencies = [
1397
+ "serde_core",
1398
+ ]
1399
+
1400
+ [[package]]
1401
+ name = "toml_edit"
1402
+ version = "0.25.11+spec-1.1.0"
1403
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1404
+ checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b"
1405
+ dependencies = [
1406
+ "indexmap",
1407
+ "toml_datetime",
1408
+ "toml_parser",
1409
+ "winnow",
1410
+ ]
1411
+
1412
+ [[package]]
1413
+ name = "toml_parser"
1414
+ version = "1.1.2+spec-1.1.0"
1415
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1416
+ checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
1417
+ dependencies = [
1418
+ "winnow",
1419
+ ]
1420
+
1421
+ [[package]]
1422
+ name = "tower"
1423
+ version = "0.5.3"
1424
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1425
+ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
1426
+ dependencies = [
1427
+ "futures-core",
1428
+ "futures-util",
1429
+ "pin-project-lite",
1430
+ "sync_wrapper",
1431
+ "tokio",
1432
+ "tower-layer",
1433
+ "tower-service",
1434
+ "tracing",
1435
+ ]
1436
+
1437
+ [[package]]
1438
+ name = "tower-http"
1439
+ version = "0.6.8"
1440
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1441
+ checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"
1442
+ dependencies = [
1443
+ "bitflags",
1444
+ "bytes",
1445
+ "http",
1446
+ "http-body",
1447
+ "pin-project-lite",
1448
+ "tower-layer",
1449
+ "tower-service",
1450
+ "tracing",
1451
+ ]
1452
+
1453
+ [[package]]
1454
+ name = "tower-layer"
1455
+ version = "0.3.3"
1456
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1457
+ checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
1458
+
1459
+ [[package]]
1460
+ name = "tower-service"
1461
+ version = "0.3.3"
1462
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1463
+ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
1464
+
1465
+ [[package]]
1466
+ name = "tracing"
1467
+ version = "0.1.44"
1468
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1469
+ checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
1470
+ dependencies = [
1471
+ "log",
1472
+ "pin-project-lite",
1473
+ "tracing-attributes",
1474
+ "tracing-core",
1475
+ ]
1476
+
1477
+ [[package]]
1478
+ name = "tracing-attributes"
1479
+ version = "0.1.31"
1480
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1481
+ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
1482
+ dependencies = [
1483
+ "proc-macro2",
1484
+ "quote",
1485
+ "syn",
1486
+ ]
1487
+
1488
+ [[package]]
1489
+ name = "tracing-core"
1490
+ version = "0.1.36"
1491
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1492
+ checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
1493
+ dependencies = [
1494
+ "once_cell",
1495
+ "valuable",
1496
+ ]
1497
+
1498
+ [[package]]
1499
+ name = "tracing-log"
1500
+ version = "0.2.0"
1501
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1502
+ checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
1503
+ dependencies = [
1504
+ "log",
1505
+ "once_cell",
1506
+ "tracing-core",
1507
+ ]
1508
+
1509
+ [[package]]
1510
+ name = "tracing-subscriber"
1511
+ version = "0.3.23"
1512
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1513
+ checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
1514
+ dependencies = [
1515
+ "matchers",
1516
+ "nu-ansi-term",
1517
+ "once_cell",
1518
+ "regex-automata",
1519
+ "sharded-slab",
1520
+ "smallvec",
1521
+ "thread_local",
1522
+ "tracing",
1523
+ "tracing-core",
1524
+ "tracing-log",
1525
+ ]
1526
+
1527
+ [[package]]
1528
+ name = "typenum"
1529
+ version = "1.19.0"
1530
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1531
+ checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
1532
+
1533
+ [[package]]
1534
+ name = "unicode-ident"
1535
+ version = "1.0.24"
1536
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1537
+ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
1538
+
1539
+ [[package]]
1540
+ name = "unicode-segmentation"
1541
+ version = "1.13.2"
1542
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1543
+ checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c"
1544
+
1545
+ [[package]]
1546
+ name = "unicode-width"
1547
+ version = "0.2.2"
1548
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1549
+ checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
1550
+
1551
+ [[package]]
1552
+ name = "utf8parse"
1553
+ version = "0.2.2"
1554
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1555
+ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
1556
+
1557
+ [[package]]
1558
+ name = "valuable"
1559
+ version = "0.1.1"
1560
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1561
+ checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
1562
+
1563
+ [[package]]
1564
+ name = "version_check"
1565
+ version = "0.9.5"
1566
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1567
+ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
1568
+
1569
+ [[package]]
1570
+ name = "wasi"
1571
+ version = "0.11.1+wasi-snapshot-preview1"
1572
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1573
+ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
1574
+
1575
+ [[package]]
1576
+ name = "wasm-bindgen"
1577
+ version = "0.2.118"
1578
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1579
+ checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89"
1580
+ dependencies = [
1581
+ "cfg-if",
1582
+ "once_cell",
1583
+ "rustversion",
1584
+ "wasm-bindgen-macro",
1585
+ "wasm-bindgen-shared",
1586
+ ]
1587
+
1588
+ [[package]]
1589
+ name = "wasm-bindgen-macro"
1590
+ version = "0.2.118"
1591
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1592
+ checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed"
1593
+ dependencies = [
1594
+ "quote",
1595
+ "wasm-bindgen-macro-support",
1596
+ ]
1597
+
1598
+ [[package]]
1599
+ name = "wasm-bindgen-macro-support"
1600
+ version = "0.2.118"
1601
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1602
+ checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904"
1603
+ dependencies = [
1604
+ "bumpalo",
1605
+ "proc-macro2",
1606
+ "quote",
1607
+ "syn",
1608
+ "wasm-bindgen-shared",
1609
+ ]
1610
+
1611
+ [[package]]
1612
+ name = "wasm-bindgen-shared"
1613
+ version = "0.2.118"
1614
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1615
+ checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129"
1616
+ dependencies = [
1617
+ "unicode-ident",
1618
+ ]
1619
+
1620
+ [[package]]
1621
+ name = "winapi"
1622
+ version = "0.3.9"
1623
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1624
+ checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
1625
+ dependencies = [
1626
+ "winapi-i686-pc-windows-gnu",
1627
+ "winapi-x86_64-pc-windows-gnu",
1628
+ ]
1629
+
1630
+ [[package]]
1631
+ name = "winapi-i686-pc-windows-gnu"
1632
+ version = "0.4.0"
1633
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1634
+ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
1635
+
1636
+ [[package]]
1637
+ name = "winapi-x86_64-pc-windows-gnu"
1638
+ version = "0.4.0"
1639
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1640
+ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
1641
+
1642
+ [[package]]
1643
+ name = "windows-core"
1644
+ version = "0.62.2"
1645
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1646
+ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
1647
+ dependencies = [
1648
+ "windows-implement",
1649
+ "windows-interface",
1650
+ "windows-link",
1651
+ "windows-result",
1652
+ "windows-strings",
1653
+ ]
1654
+
1655
+ [[package]]
1656
+ name = "windows-implement"
1657
+ version = "0.60.2"
1658
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1659
+ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
1660
+ dependencies = [
1661
+ "proc-macro2",
1662
+ "quote",
1663
+ "syn",
1664
+ ]
1665
+
1666
+ [[package]]
1667
+ name = "windows-interface"
1668
+ version = "0.59.3"
1669
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1670
+ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
1671
+ dependencies = [
1672
+ "proc-macro2",
1673
+ "quote",
1674
+ "syn",
1675
+ ]
1676
+
1677
+ [[package]]
1678
+ name = "windows-link"
1679
+ version = "0.2.1"
1680
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1681
+ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
1682
+
1683
+ [[package]]
1684
+ name = "windows-result"
1685
+ version = "0.4.1"
1686
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1687
+ checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
1688
+ dependencies = [
1689
+ "windows-link",
1690
+ ]
1691
+
1692
+ [[package]]
1693
+ name = "windows-strings"
1694
+ version = "0.5.1"
1695
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1696
+ checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
1697
+ dependencies = [
1698
+ "windows-link",
1699
+ ]
1700
+
1701
+ [[package]]
1702
+ name = "windows-sys"
1703
+ version = "0.59.0"
1704
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1705
+ checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
1706
+ dependencies = [
1707
+ "windows-targets",
1708
+ ]
1709
+
1710
+ [[package]]
1711
+ name = "windows-sys"
1712
+ version = "0.61.2"
1713
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1714
+ checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
1715
+ dependencies = [
1716
+ "windows-link",
1717
+ ]
1718
+
1719
+ [[package]]
1720
+ name = "windows-targets"
1721
+ version = "0.52.6"
1722
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1723
+ checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
1724
+ dependencies = [
1725
+ "windows_aarch64_gnullvm",
1726
+ "windows_aarch64_msvc",
1727
+ "windows_i686_gnu",
1728
+ "windows_i686_gnullvm",
1729
+ "windows_i686_msvc",
1730
+ "windows_x86_64_gnu",
1731
+ "windows_x86_64_gnullvm",
1732
+ "windows_x86_64_msvc",
1733
+ ]
1734
+
1735
+ [[package]]
1736
+ name = "windows_aarch64_gnullvm"
1737
+ version = "0.52.6"
1738
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1739
+ checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
1740
+
1741
+ [[package]]
1742
+ name = "windows_aarch64_msvc"
1743
+ version = "0.52.6"
1744
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1745
+ checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
1746
+
1747
+ [[package]]
1748
+ name = "windows_i686_gnu"
1749
+ version = "0.52.6"
1750
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1751
+ checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
1752
+
1753
+ [[package]]
1754
+ name = "windows_i686_gnullvm"
1755
+ version = "0.52.6"
1756
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1757
+ checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
1758
+
1759
+ [[package]]
1760
+ name = "windows_i686_msvc"
1761
+ version = "0.52.6"
1762
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1763
+ checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
1764
+
1765
+ [[package]]
1766
+ name = "windows_x86_64_gnu"
1767
+ version = "0.52.6"
1768
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1769
+ checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
1770
+
1771
+ [[package]]
1772
+ name = "windows_x86_64_gnullvm"
1773
+ version = "0.52.6"
1774
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1775
+ checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
1776
+
1777
+ [[package]]
1778
+ name = "windows_x86_64_msvc"
1779
+ version = "0.52.6"
1780
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1781
+ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
1782
+
1783
+ [[package]]
1784
+ name = "winnow"
1785
+ version = "1.0.2"
1786
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1787
+ checksum = "2ee1708bef14716a11bae175f579062d4554d95be2c6829f518df847b7b3fdd0"
1788
+ dependencies = [
1789
+ "memchr",
1790
+ ]
1791
+
1792
+ [[package]]
1793
+ name = "zerocopy"
1794
+ version = "0.8.48"
1795
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1796
+ checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
1797
+ dependencies = [
1798
+ "zerocopy-derive",
1799
+ ]
1800
+
1801
+ [[package]]
1802
+ name = "zerocopy-derive"
1803
+ version = "0.8.48"
1804
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1805
+ checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
1806
+ dependencies = [
1807
+ "proc-macro2",
1808
+ "quote",
1809
+ "syn",
1810
+ ]
1811
+
1812
+ [[package]]
1813
+ name = "zmij"
1814
+ version = "1.0.21"
1815
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1816
+ checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
Cargo.toml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "markdownfs"
3
+ version = "0.2.0"
4
+ edition = "2024"
5
+
6
+ [[bin]]
7
+ name = "markdownfs"
8
+ path = "src/main.rs"
9
+
10
+ [[bin]]
11
+ name = "mdfs-server"
12
+ path = "src/bin/mdfs_server.rs"
13
+
14
+ [[bin]]
15
+ name = "markdownfs-server"
16
+ path = "src/bin/mdfs_server.rs"
17
+
18
+ [[bin]]
19
+ name = "mdfs-mcp"
20
+ path = "src/bin/mdfs_mcp.rs"
21
+
22
+ [[bin]]
23
+ name = "markdownfs-mcp"
24
+ path = "src/bin/mdfs_mcp.rs"
25
+
26
+ [[bin]]
27
+ name = "mdfs-mount"
28
+ path = "src/bin/mdfs_mount.rs"
29
+ required-features = ["fuser"]
30
+
31
+ [[bin]]
32
+ name = "markdownfs-mount"
33
+ path = "src/bin/mdfs_mount.rs"
34
+ required-features = ["fuser"]
35
+
36
+ [dependencies]
37
+ sha2 = "0.10"
38
+ memmap2 = "0.9"
39
+ bytes = "1"
40
+ serde = { version = "1", features = ["derive"] }
41
+ serde_json = "1"
42
+ bincode = "1"
43
+ regex = "1"
44
+ glob = "0.3"
45
+ rustyline = "15"
46
+ thiserror = "2"
47
+ chrono = "0.4"
48
+ tokio = { version = "1", features = ["full"] }
49
+ axum = "0.8"
50
+ tower-http = { version = "0.6", features = ["cors", "trace"] }
51
+ tracing = "0.1"
52
+ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
53
+ rmcp = { version = "1.4", features = ["server", "transport-io"] }
54
+ clap = { version = "4", features = ["derive", "env"] }
55
+ fuser = { version = "0.17.0", optional = true, default-features = false, features = ["abi-7-31", "macfuse-4-compat"] }
56
+
57
+ [features]
58
+ fuser = ["dep:fuser"]
Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1.6
2
+ #
3
+ # Hugging Face Space image for MarkdownFS.
4
+ # Builds the `mdfs-server` REST binary and runs it on port 7860
5
+ # (HF Spaces routes external traffic to this port by convention).
6
+
7
+ FROM rust:1.83-slim-bookworm AS builder
8
+
9
+ WORKDIR /build
10
+
11
+ RUN apt-get update \
12
+ && apt-get install -y --no-install-recommends pkg-config libssl-dev ca-certificates \
13
+ && rm -rf /var/lib/apt/lists/*
14
+
15
+ COPY Cargo.toml Cargo.lock ./
16
+ COPY src ./src
17
+ COPY tests ./tests
18
+ COPY examples ./examples
19
+
20
+ RUN cargo build --release --bin mdfs-server
21
+
22
+ FROM debian:bookworm-slim AS runtime
23
+
24
+ RUN apt-get update \
25
+ && apt-get install -y --no-install-recommends ca-certificates \
26
+ && rm -rf /var/lib/apt/lists/* \
27
+ && useradd --create-home --uid 1000 mdfs
28
+
29
+ COPY --from=builder /build/target/release/mdfs-server /usr/local/bin/mdfs-server
30
+
31
+ USER mdfs
32
+ WORKDIR /home/mdfs
33
+
34
+ ENV MARKDOWNFS_DATA_DIR=/home/mdfs/data \
35
+ MARKDOWNFS_LISTEN=0.0.0.0:7860 \
36
+ RUST_LOG=markdownfs=info,tower_http=info
37
+
38
+ RUN mkdir -p /home/mdfs/data
39
+
40
+ EXPOSE 7860
41
+
42
+ CMD ["mdfs-server"]
README.md CHANGED
@@ -1,12 +1,77 @@
1
  ---
2
- title: Markdownfs
3
- emoji: 📈
4
- colorFrom: red
5
- colorTo: yellow
6
  sdk: docker
 
7
  pinned: false
8
  license: mit
9
  short_description: A versioned markdown filesystem with a REST API for agents.
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: MarkdownFS
3
+ emoji: 📝
4
+ colorFrom: indigo
5
+ colorTo: purple
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  license: mit
10
  short_description: A versioned markdown filesystem with a REST API for agents.
11
  ---
12
 
13
+ # MarkdownFS on Hugging Face
14
+
15
+ MarkdownFS is a high-performance concurrent markdown database with built-in
16
+ versioning, permissions, and a REST API. This Space hosts the `mdfs-server`
17
+ binary so any agent or app can use it as durable, inspectable workspace memory.
18
+
19
+ ## Endpoints
20
+
21
+ Base URL: `https://<your-username>-<space-name>.hf.space`
22
+
23
+ | Method | Path | Purpose |
24
+ |--------|-----------------------|----------------------------------|
25
+ | GET | `/health` | Health check |
26
+ | GET | `/fs/{path}` | Read file or list directory |
27
+ | PUT | `/fs/{path}` | Write file or create directory |
28
+ | DELETE | `/fs/{path}` | Delete file or directory |
29
+ | GET | `/search/grep` | Grep across markdown |
30
+ | GET | `/search/find` | Find by name |
31
+ | GET | `/tree/{path}` | Directory tree |
32
+ | POST | `/vcs/commit` | Commit current state |
33
+ | GET | `/vcs/log` | Commit history |
34
+ | POST | `/vcs/revert` | Revert to a commit |
35
+
36
+ See full docs at the project repo.
37
+
38
+ ## Quick examples
39
+
40
+ ```bash
41
+ SPACE=https://your-username-markdownfs.hf.space
42
+
43
+ # write a file
44
+ curl -X PUT "$SPACE/fs/notes/hello.md" \
45
+ -H "Content-Type: text/markdown" \
46
+ --data-binary "# Hello from MarkdownFS"
47
+
48
+ # read it back
49
+ curl "$SPACE/fs/notes/hello.md"
50
+
51
+ # commit
52
+ curl -X POST "$SPACE/vcs/commit" \
53
+ -H "Content-Type: application/json" \
54
+ -d '{"message": "first note"}'
55
+ ```
56
+
57
+ ## Storage
58
+
59
+ By default the Space uses ephemeral container storage at
60
+ `/home/mdfs/data`. **State is lost when the Space restarts.**
61
+
62
+ For durable storage, either:
63
+ - Enable Hugging Face **Persistent Storage** for this Space and point
64
+ `MARKDOWNFS_DATA_DIR` at the mounted volume, or
65
+ - Periodically sync the data directory to an HF Dataset repo.
66
+
67
+ ## Configuration
68
+
69
+ Override via Space → Settings → Variables:
70
+
71
+ | Variable | Default |
72
+ |--------------------------------|--------------------|
73
+ | `MARKDOWNFS_DATA_DIR` | `/home/mdfs/data` |
74
+ | `MARKDOWNFS_LISTEN` | `0.0.0.0:7860` |
75
+ | `MARKDOWNFS_AUTOSAVE_SECS` | `5` |
76
+ | `MARKDOWNFS_MAX_FILE_SIZE` | `10485760` |
77
+ | `RUST_LOG` | `markdownfs=info` |
examples/notebooks/01_getting_started_http.ipynb ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Getting Started With mdfs Over HTTP\n",
8
+ "\n",
9
+ "This notebook starts a local `mdfs-server`, writes markdown files, reads them back, searches the workspace, and commits the result.\n",
10
+ "\n",
11
+ "Run it from the repository root. The notebook uses a throwaway data directory under `.demo/notebook-http`."
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "markdown",
16
+ "metadata": {},
17
+ "source": [
18
+ "## 1. Start A Local Server\n",
19
+ "\n",
20
+ "The HTTP server is the safest integration point for notebooks and agents because it acts as the single writer to the mdfs state file."
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "metadata": {},
26
+ "source": [
27
+ "from pathlib import Path\n",
28
+ "import atexit\n",
29
+ "import json\n",
30
+ "import os\n",
31
+ "import shutil\n",
32
+ "import subprocess\n",
33
+ "import time\n",
34
+ "import urllib.error\n",
35
+ "import urllib.parse\n",
36
+ "import urllib.request\n",
37
+ "\n",
38
+ "\n",
39
+ "def find_repo_root(start=None):\n",
40
+ " \"\"\"Find the mdfs repo even when Jupyter starts in examples/notebooks.\"\"\"\n",
41
+ " env_root = os.environ.get(\"MDFS_REPO_ROOT\") or os.environ.get(\"MARKDOWNFS_REPO_ROOT\")\n",
42
+ " candidates = []\n",
43
+ " if env_root:\n",
44
+ " candidates.append(Path(env_root).expanduser())\n",
45
+ "\n",
46
+ " start_path = Path(start or Path.cwd()).resolve()\n",
47
+ " candidates.extend([start_path, *start_path.parents])\n",
48
+ "\n",
49
+ " for candidate in candidates:\n",
50
+ " if (candidate / \"Cargo.toml\").exists() and (candidate / \"src\").is_dir():\n",
51
+ " return candidate\n",
52
+ "\n",
53
+ " raise RuntimeError(\n",
54
+ " \"Could not find the mdfs repository root. \"\n",
55
+ " \"Run the notebook from inside the repo or set MDFS_REPO_ROOT.\"\n",
56
+ " )\n",
57
+ "\n",
58
+ "\n",
59
+ "def find_cargo():\n",
60
+ " \"\"\"Find Cargo even when the Jupyter kernel has a minimal PATH.\"\"\"\n",
61
+ " candidates = []\n",
62
+ " env_cargo = os.environ.get(\"CARGO\")\n",
63
+ " if env_cargo:\n",
64
+ " candidates.append(Path(env_cargo).expanduser())\n",
65
+ "\n",
66
+ " path_cargo = shutil.which(\"cargo\")\n",
67
+ " if path_cargo:\n",
68
+ " candidates.append(Path(path_cargo))\n",
69
+ "\n",
70
+ " candidates.extend([\n",
71
+ " Path.home() / \".cargo\" / \"bin\" / \"cargo\",\n",
72
+ " Path(\"/opt/homebrew/bin/cargo\"),\n",
73
+ " Path(\"/usr/local/bin/cargo\"),\n",
74
+ " ])\n",
75
+ "\n",
76
+ " for candidate in candidates:\n",
77
+ " if candidate.exists() and candidate.is_file():\n",
78
+ " return str(candidate)\n",
79
+ "\n",
80
+ " raise RuntimeError(\n",
81
+ " \"Could not find Cargo. Install Rust from https://rustup.rs, \"\n",
82
+ " \"or set CARGO=/absolute/path/to/cargo before running this notebook.\"\n",
83
+ " )\n",
84
+ "\n",
85
+ "\n",
86
+ "ROOT = find_repo_root()\n",
87
+ "CARGO = find_cargo()\n",
88
+ "DATA_DIR = ROOT / \".demo\" / \"notebook-http\"\n",
89
+ "BASE_URL = \"http://127.0.0.1:3000\"\n",
90
+ "print(f\"Using mdfs repo at {ROOT}\")\n",
91
+ "print(f\"Using cargo at {CARGO}\")\n",
92
+ "\n",
93
+ "if DATA_DIR.exists():\n",
94
+ " shutil.rmtree(DATA_DIR)\n",
95
+ "DATA_DIR.mkdir(parents=True)\n",
96
+ "\n",
97
+ "env = os.environ.copy()\n",
98
+ "env.update({\n",
99
+ " \"MARKDOWNFS_DATA_DIR\": str(DATA_DIR),\n",
100
+ " \"MARKDOWNFS_LISTEN\": \"127.0.0.1:3000\",\n",
101
+ "})\n",
102
+ "env[\"PATH\"] = os.pathsep.join([str(Path(CARGO).parent), env.get(\"PATH\", \"\")])\n",
103
+ "\n",
104
+ "server = subprocess.Popen(\n",
105
+ " [CARGO, \"run\", \"--quiet\", \"--bin\", \"mdfs-server\"],\n",
106
+ " cwd=ROOT,\n",
107
+ " env=env,\n",
108
+ " stdout=subprocess.PIPE,\n",
109
+ " stderr=subprocess.STDOUT,\n",
110
+ " text=True,\n",
111
+ ")\n",
112
+ "\n",
113
+ "def stop_server():\n",
114
+ " if server.poll() is None:\n",
115
+ " server.terminate()\n",
116
+ " try:\n",
117
+ " server.wait(timeout=5)\n",
118
+ " except subprocess.TimeoutExpired:\n",
119
+ " server.kill()\n",
120
+ "\n",
121
+ "atexit.register(stop_server)\n",
122
+ "\n",
123
+ "def request(method, path, body=None, headers=None):\n",
124
+ " url = f\"{BASE_URL}{path}\"\n",
125
+ " data = body.encode(\"utf-8\") if isinstance(body, str) else body\n",
126
+ " req = urllib.request.Request(url, data=data, method=method, headers=headers or {})\n",
127
+ " try:\n",
128
+ " with urllib.request.urlopen(req, timeout=5) as response:\n",
129
+ " raw = response.read().decode(\"utf-8\")\n",
130
+ " content_type = response.headers.get(\"content-type\", \"\")\n",
131
+ " if \"application/json\" in content_type:\n",
132
+ " return json.loads(raw)\n",
133
+ " return raw\n",
134
+ " except urllib.error.HTTPError as exc:\n",
135
+ " message = exc.read().decode(\"utf-8\")\n",
136
+ " raise RuntimeError(f\"{method} {path} failed: {exc.code} {message}\") from exc\n",
137
+ "\n",
138
+ "for _ in range(60):\n",
139
+ " try:\n",
140
+ " print(request(\"GET\", \"/health\"))\n",
141
+ " break\n",
142
+ " except Exception:\n",
143
+ " if server.poll() is not None:\n",
144
+ " output = server.stdout.read() if server.stdout else \"\"\n",
145
+ " raise RuntimeError(f\"mdfs-server exited early:\\n{output}\")\n",
146
+ " time.sleep(0.25)\n",
147
+ "else:\n",
148
+ " raise TimeoutError(\"mdfs-server did not become ready\")"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": [],
152
+ "id": "92ffc9f6"
153
+ },
154
+ {
155
+ "cell_type": "markdown",
156
+ "metadata": {},
157
+ "source": [
158
+ "## 2. Write Markdown Files\n",
159
+ "\n",
160
+ "Write markdown files directly. The HTTP API creates missing parent directories for new files."
161
+ ],
162
+ "id": "e16a5812"
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "readme = \"\"\"# Notebook Demo\n",
169
+ "\n",
170
+ "This file was written through the mdfs HTTP API.\n",
171
+ "\n",
172
+ "TODO: delegate the next draft to an agent.\n",
173
+ "\"\"\"\n",
174
+ "\n",
175
+ "plan = \"\"\"# Agent Plan\n",
176
+ "\n",
177
+ "- Inspect the workspace before writing.\n",
178
+ "- Save every meaningful result as markdown.\n",
179
+ "- Commit the state after each handoff.\n",
180
+ "\"\"\"\n",
181
+ "\n",
182
+ "print(request(\"PUT\", \"/fs/notebook-demo/readme.md\", readme))\n",
183
+ "print(request(\"PUT\", \"/fs/notebook-demo/agent-plan.md\", plan))"
184
+ ],
185
+ "execution_count": null,
186
+ "outputs": [],
187
+ "id": "55dd6495"
188
+ },
189
+ {
190
+ "cell_type": "markdown",
191
+ "metadata": {},
192
+ "source": [
193
+ "## 3. Read, List, Search"
194
+ ],
195
+ "id": "36d31719"
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "metadata": {},
200
+ "source": [
201
+ "print(request(\"GET\", \"/fs/notebook-demo/readme.md\"))\n",
202
+ "print(json.dumps(request(\"GET\", \"/fs/notebook-demo/\"), indent=2))\n",
203
+ "\n",
204
+ "query = urllib.parse.urlencode({\"pattern\": \"TODO|agent\", \"path\": \"notebook-demo\", \"recursive\": \"true\"})\n",
205
+ "print(json.dumps(request(\"GET\", f\"/search/grep?{query}\"), indent=2))"
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": [],
209
+ "id": "902143d9"
210
+ },
211
+ {
212
+ "cell_type": "markdown",
213
+ "metadata": {},
214
+ "source": [
215
+ "## 4. Commit And Inspect History"
216
+ ],
217
+ "id": "b9ab61a5"
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "metadata": {},
222
+ "source": [
223
+ "commit = request(\n",
224
+ " \"POST\",\n",
225
+ " \"/vcs/commit\",\n",
226
+ " json.dumps({\"message\": \"notebook getting started demo\"}),\n",
227
+ " {\"Content-Type\": \"application/json\"},\n",
228
+ ")\n",
229
+ "print(json.dumps(commit, indent=2))\n",
230
+ "print(request(\"GET\", \"/vcs/status\"))\n",
231
+ "print(json.dumps(request(\"GET\", \"/vcs/log\"), indent=2))"
232
+ ],
233
+ "execution_count": null,
234
+ "outputs": [],
235
+ "id": "1a2f578e"
236
+ },
237
+ {
238
+ "cell_type": "markdown",
239
+ "metadata": {},
240
+ "source": [
241
+ "## 5. Clean Up"
242
+ ],
243
+ "id": "11dbd153"
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "metadata": {},
248
+ "source": [
249
+ "stop_server()\n",
250
+ "print(\"server stopped\")"
251
+ ],
252
+ "execution_count": null,
253
+ "outputs": [],
254
+ "id": "0d14d3ee"
255
+ }
256
+ ],
257
+ "metadata": {
258
+ "kernelspec": {
259
+ "display_name": "Python 3",
260
+ "language": "python",
261
+ "name": "python3"
262
+ },
263
+ "language_info": {
264
+ "codemirror_mode": {
265
+ "name": "ipython",
266
+ "version": 3
267
+ },
268
+ "file_extension": ".py",
269
+ "mimetype": "text/x-python",
270
+ "name": "python",
271
+ "nbconvert_exporter": "python",
272
+ "pygments_lexer": "ipython3",
273
+ "version": "3.9.6"
274
+ }
275
+ },
276
+ "nbformat": 4,
277
+ "nbformat_minor": 5
278
+ }
examples/notebooks/02_mount_and_start_using_mdfs.ipynb ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Mount And Start Using mdfs\n",
8
+ "\n",
9
+ "This notebook shows the optional OS mount path using the `mdfs-mount` binary.\n",
10
+ "\n",
11
+ "The mount binary is behind the Rust `fuser` feature. On macOS you need macFUSE and `pkg-config` available so `fuser` can link against the real mount library. If your machine is not configured for FUSE, use `01_getting_started_http.ipynb` first; the HTTP path is the recommended agent integration path today."
12
+ ],
13
+ "id": "c516b31b"
14
+ },
15
+ {
16
+ "cell_type": "markdown",
17
+ "metadata": {},
18
+ "source": [
19
+ "## 1. Build The Mount Binary\n",
20
+ "\n",
21
+ "On macOS, install prerequisites with something like `brew install macfuse pkg-config` if this build cannot find FUSE."
22
+ ],
23
+ "id": "3b607607"
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "metadata": {},
28
+ "source": [
29
+ "from pathlib import Path\n",
30
+ "import atexit\n",
31
+ "import os\n",
32
+ "import platform\n",
33
+ "import shutil\n",
34
+ "import subprocess\n",
35
+ "import time\n",
36
+ "\n",
37
+ "\n",
38
+ "def find_repo_root(start=None):\n",
39
+ " \"\"\"Find the mdfs repo even when Jupyter starts in examples/notebooks.\"\"\"\n",
40
+ " env_root = os.environ.get(\"MDFS_REPO_ROOT\") or os.environ.get(\"MARKDOWNFS_REPO_ROOT\")\n",
41
+ " candidates = []\n",
42
+ " if env_root:\n",
43
+ " candidates.append(Path(env_root).expanduser())\n",
44
+ "\n",
45
+ " start_path = Path(start or Path.cwd()).resolve()\n",
46
+ " candidates.extend([start_path, *start_path.parents])\n",
47
+ "\n",
48
+ " for candidate in candidates:\n",
49
+ " if (candidate / \"Cargo.toml\").exists() and (candidate / \"src\").is_dir():\n",
50
+ " return candidate\n",
51
+ "\n",
52
+ " raise RuntimeError(\n",
53
+ " \"Could not find the mdfs repository root. \"\n",
54
+ " \"Run the notebook from inside the repo or set MDFS_REPO_ROOT.\"\n",
55
+ " )\n",
56
+ "\n",
57
+ "\n",
58
+ "def find_cargo():\n",
59
+ " \"\"\"Find Cargo even when the Jupyter kernel has a minimal PATH.\"\"\"\n",
60
+ " candidates = []\n",
61
+ " env_cargo = os.environ.get(\"CARGO\")\n",
62
+ " if env_cargo:\n",
63
+ " candidates.append(Path(env_cargo).expanduser())\n",
64
+ "\n",
65
+ " path_cargo = shutil.which(\"cargo\")\n",
66
+ " if path_cargo:\n",
67
+ " candidates.append(Path(path_cargo))\n",
68
+ "\n",
69
+ " candidates.extend([\n",
70
+ " Path.home() / \".cargo\" / \"bin\" / \"cargo\",\n",
71
+ " Path(\"/opt/homebrew/bin/cargo\"),\n",
72
+ " Path(\"/usr/local/bin/cargo\"),\n",
73
+ " ])\n",
74
+ "\n",
75
+ " for candidate in candidates:\n",
76
+ " if candidate.exists() and candidate.is_file():\n",
77
+ " return str(candidate)\n",
78
+ "\n",
79
+ " raise RuntimeError(\n",
80
+ " \"Could not find Cargo. Install Rust from https://rustup.rs, \"\n",
81
+ " \"or set CARGO=/absolute/path/to/cargo before running this notebook.\"\n",
82
+ " )\n",
83
+ "\n",
84
+ "\n",
85
+ "def find_pkg_config():\n",
86
+ " \"\"\"Find pkg-config even when the Jupyter kernel has a minimal PATH.\"\"\"\n",
87
+ " candidates = []\n",
88
+ " env_pkg_config = os.environ.get(\"PKG_CONFIG\")\n",
89
+ " if env_pkg_config:\n",
90
+ " candidates.append(Path(env_pkg_config).expanduser())\n",
91
+ "\n",
92
+ " path_pkg_config = shutil.which(\"pkg-config\")\n",
93
+ " if path_pkg_config:\n",
94
+ " candidates.append(Path(path_pkg_config))\n",
95
+ "\n",
96
+ " candidates.extend([\n",
97
+ " Path(\"/opt/homebrew/bin/pkg-config\"),\n",
98
+ " Path(\"/usr/local/bin/pkg-config\"),\n",
99
+ " Path(\"/opt/local/bin/pkg-config\"),\n",
100
+ " ])\n",
101
+ "\n",
102
+ " for candidate in candidates:\n",
103
+ " if candidate.exists() and candidate.is_file():\n",
104
+ " return str(candidate)\n",
105
+ "\n",
106
+ " raise RuntimeError(\n",
107
+ " \"Could not find pkg-config. On macOS with Homebrew, run `brew install pkg-config`, \"\n",
108
+ " \"or set PKG_CONFIG=/absolute/path/to/pkg-config before running this notebook.\"\n",
109
+ " )\n",
110
+ "\n",
111
+ "\n",
112
+ "def add_common_fuse_pkg_config_paths(env):\n",
113
+ " \"\"\"Help pkg-config find macFUSE when Jupyter has a minimal environment.\"\"\"\n",
114
+ " candidates = [\n",
115
+ " Path(\"/opt/homebrew/lib/pkgconfig\"),\n",
116
+ " Path(\"/usr/local/lib/pkgconfig\"),\n",
117
+ " Path(\"/usr/local/share/pkgconfig\"),\n",
118
+ " Path(\"/opt/local/lib/pkgconfig\"),\n",
119
+ " Path(\"/Library/Filesystems/macfuse.fs/Contents/Resources/lib/pkgconfig\"),\n",
120
+ " ]\n",
121
+ " existing = [str(path) for path in candidates if path.exists()]\n",
122
+ " current = env.get(\"PKG_CONFIG_PATH\", \"\")\n",
123
+ " if current:\n",
124
+ " existing.append(current)\n",
125
+ " if existing:\n",
126
+ " env[\"PKG_CONFIG_PATH\"] = os.pathsep.join(existing)\n",
127
+ "\n",
128
+ "\n",
129
+ "ROOT = find_repo_root()\n",
130
+ "CARGO = find_cargo()\n",
131
+ "PKG_CONFIG = find_pkg_config()\n",
132
+ "DEMO_ROOT = ROOT / \".demo\" / \"notebook-mount\"\n",
133
+ "DATA_DIR = DEMO_ROOT / \"data\"\n",
134
+ "MOUNTPOINT = DEMO_ROOT / \"mnt\"\n",
135
+ "print(f\"Using mdfs repo at {ROOT}\")\n",
136
+ "print(f\"Using cargo at {CARGO}\")\n",
137
+ "print(f\"Using pkg-config at {PKG_CONFIG}\")\n",
138
+ "\n",
139
+ "DEMO_ROOT.mkdir(parents=True, exist_ok=True)\n",
140
+ "DATA_DIR.mkdir(parents=True, exist_ok=True)\n",
141
+ "MOUNTPOINT.mkdir(parents=True, exist_ok=True)\n",
142
+ "\n",
143
+ "cargo_env = os.environ.copy()\n",
144
+ "cargo_env[\"PKG_CONFIG\"] = PKG_CONFIG\n",
145
+ "cargo_env[\"PATH\"] = os.pathsep.join([\n",
146
+ " str(Path(CARGO).parent),\n",
147
+ " str(Path(PKG_CONFIG).parent),\n",
148
+ " cargo_env.get(\"PATH\", \"\"),\n",
149
+ "])\n",
150
+ "add_common_fuse_pkg_config_paths(cargo_env)\n",
151
+ "\n",
152
+ "build = subprocess.run(\n",
153
+ " [CARGO, \"build\", \"--release\", \"--features\", \"fuser\", \"--bin\", \"mdfs-mount\"],\n",
154
+ " cwd=ROOT,\n",
155
+ " env=cargo_env,\n",
156
+ " text=True,\n",
157
+ " capture_output=True,\n",
158
+ ")\n",
159
+ "print(build.stdout)\n",
160
+ "print(build.stderr)\n",
161
+ "MOUNT_BUILD_OK = build.returncode == 0\n",
162
+ "MOUNT_BINARY = ROOT / \"target\" / \"release\" / \"mdfs-mount\"\n",
163
+ "\n",
164
+ "if not MOUNT_BUILD_OK:\n",
165
+ " print(\n",
166
+ " \"Mount build skipped: mdfs-mount could not be built on this machine.\\n\"\n",
167
+ " \"On macOS, install macFUSE and pkg-config so fuser can find fuse.pc.\\n\"\n",
168
+ " \"For Homebrew, try: brew install pkg-config && brew install --cask macfuse.\\n\"\n",
169
+ " \"If macFUSE is installed elsewhere, set PKG_CONFIG_PATH to the directory containing fuse.pc.\\n\"\n",
170
+ " \"You can still use 01_getting_started_http.ipynb without FUSE.\"\n",
171
+ " )\n",
172
+ "else:\n",
173
+ " print(f\"Built mdfs-mount at {MOUNT_BINARY}\")"
174
+ ],
175
+ "execution_count": null,
176
+ "outputs": [],
177
+ "id": "34720839"
178
+ },
179
+ {
180
+ "cell_type": "markdown",
181
+ "metadata": {},
182
+ "source": [
183
+ "## 2. Start The Mount\n",
184
+ "\n",
185
+ "This starts `target/release/mdfs-mount` in the background. Keep the process alive while you use the mounted directory."
186
+ ],
187
+ "id": "45596564"
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "metadata": {},
192
+ "source": [
193
+ "mount_proc = None\n",
194
+ "MOUNT_ACTIVE = False\n",
195
+ "\n",
196
+ "def unmount():\n",
197
+ " if mount_proc is None:\n",
198
+ " return\n",
199
+ " if platform.system() == \"Darwin\":\n",
200
+ " subprocess.run([\"diskutil\", \"unmount\", str(MOUNTPOINT)], capture_output=True, text=True)\n",
201
+ " else:\n",
202
+ " subprocess.run([\"fusermount\", \"-u\", str(MOUNTPOINT)], capture_output=True, text=True)\n",
203
+ " if mount_proc.poll() is None:\n",
204
+ " mount_proc.terminate()\n",
205
+ " try:\n",
206
+ " mount_proc.wait(timeout=5)\n",
207
+ " except subprocess.TimeoutExpired:\n",
208
+ " mount_proc.kill()\n",
209
+ "\n",
210
+ "if not MOUNT_BUILD_OK:\n",
211
+ " print(\"Skipping mount start because mdfs-mount was not built. See the previous cell for prerequisites.\")\n",
212
+ "else:\n",
213
+ " env = os.environ.copy()\n",
214
+ " env.update({\n",
215
+ " \"MARKDOWNFS_DATA_DIR\": str(DATA_DIR),\n",
216
+ " \"MARKDOWNFS_MOUNTPOINT\": str(MOUNTPOINT),\n",
217
+ " })\n",
218
+ " env[\"PATH\"] = os.pathsep.join([\n",
219
+ " str(Path(CARGO).parent),\n",
220
+ " str(Path(PKG_CONFIG).parent),\n",
221
+ " env.get(\"PATH\", \"\"),\n",
222
+ " ])\n",
223
+ "\n",
224
+ " mount_proc = subprocess.Popen(\n",
225
+ " [str(MOUNT_BINARY), \"--mountpoint\", str(MOUNTPOINT)],\n",
226
+ " cwd=ROOT,\n",
227
+ " env=env,\n",
228
+ " stdout=subprocess.PIPE,\n",
229
+ " stderr=subprocess.STDOUT,\n",
230
+ " text=True,\n",
231
+ " )\n",
232
+ " atexit.register(unmount)\n",
233
+ "\n",
234
+ " time.sleep(2)\n",
235
+ " if mount_proc.poll() is not None:\n",
236
+ " output = mount_proc.stdout.read() if mount_proc.stdout else \"\"\n",
237
+ " print(f\"Mount process exited early. FUSE may not be installed or permitted.\\n{output}\")\n",
238
+ " else:\n",
239
+ " MOUNT_ACTIVE = True\n",
240
+ " print(f\"Mounted markdownfs at {MOUNTPOINT}\")"
241
+ ],
242
+ "execution_count": null,
243
+ "outputs": [],
244
+ "id": "665c78b3"
245
+ },
246
+ {
247
+ "cell_type": "markdown",
248
+ "metadata": {},
249
+ "source": [
250
+ "## 3. Use The Mounted Directory\n",
251
+ "\n",
252
+ "`mdfs` is markdown-only by design, so create `.md` files."
253
+ ],
254
+ "id": "2e73845a"
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "metadata": {},
259
+ "source": [
260
+ "if not MOUNT_ACTIVE:\n",
261
+ " print(\"Skipping mounted-directory example because no FUSE mount is active.\")\n",
262
+ "else:\n",
263
+ " note = MOUNTPOINT / \"hello.md\"\n",
264
+ " note.write_text(\"# Hello From A Mount\\n\\nThis markdown file was created through the OS mount.\\n\", encoding=\"utf-8\")\n",
265
+ "\n",
266
+ " print(note.read_text(encoding=\"utf-8\"))\n",
267
+ " print(sorted(path.name for path in MOUNTPOINT.iterdir()))"
268
+ ],
269
+ "execution_count": null,
270
+ "outputs": [],
271
+ "id": "8cf5a1c0"
272
+ },
273
+ {
274
+ "cell_type": "markdown",
275
+ "metadata": {},
276
+ "source": [
277
+ "## 4. Unmount\n",
278
+ "\n",
279
+ "The mount binary uses an explicit unmount flow, so run this cell when you are done."
280
+ ],
281
+ "id": "c86130f7"
282
+ },
283
+ {
284
+ "cell_type": "code",
285
+ "metadata": {},
286
+ "source": [
287
+ "if MOUNT_ACTIVE:\n",
288
+ " unmount()\n",
289
+ " MOUNT_ACTIVE = False\n",
290
+ " print(\"unmounted\")\n",
291
+ "else:\n",
292
+ " print(\"No active mount to unmount.\")"
293
+ ],
294
+ "execution_count": null,
295
+ "outputs": []
296
+ }
297
+ ],
298
+ "metadata": {
299
+ "kernelspec": {
300
+ "display_name": "Python 3",
301
+ "language": "python",
302
+ "name": "python3"
303
+ },
304
+ "language_info": {
305
+ "codemirror_mode": {
306
+ "name": "ipython",
307
+ "version": 3
308
+ },
309
+ "file_extension": ".py",
310
+ "mimetype": "text/x-python",
311
+ "name": "python",
312
+ "nbconvert_exporter": "python",
313
+ "pygments_lexer": "ipython3",
314
+ "version": "3.9.6"
315
+ }
316
+ },
317
+ "nbformat": 4,
318
+ "nbformat_minor": 5
319
+ }
examples/notebooks/03_user_delegation_to_agents.ipynb ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# User Delegation To Agents\n",
8
+ "\n",
9
+ "This notebook demonstrates the CLI/session delegation model: an agent can act on behalf of a user, but operations are constrained by the intersection of the agent's permissions and the delegated user's permissions.\n",
10
+ "\n",
11
+ "Delegation is currently a CLI/session feature. The HTTP API supports bearer-token agents, but it does not yet expose `delegate` and `undelegate` endpoints."
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "markdown",
16
+ "metadata": {},
17
+ "source": [
18
+ "## 1. Run A Scripted CLI Session\n",
19
+ "\n",
20
+ "The helper below drives the interactive `mdfs` binary through stdin so the notebook remains reproducible."
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "metadata": {},
26
+ "source": [
27
+ "from pathlib import Path\n",
28
+ "import os\n",
29
+ "import re\n",
30
+ "import shutil\n",
31
+ "import subprocess\n",
32
+ "\n",
33
+ "\n",
34
+ "def find_repo_root(start=None):\n",
35
+ " \"\"\"Find the mdfs repo even when Jupyter starts in examples/notebooks.\"\"\"\n",
36
+ " env_root = os.environ.get(\"MDFS_REPO_ROOT\") or os.environ.get(\"MARKDOWNFS_REPO_ROOT\")\n",
37
+ " candidates = []\n",
38
+ " if env_root:\n",
39
+ " candidates.append(Path(env_root).expanduser())\n",
40
+ "\n",
41
+ " start_path = Path(start or Path.cwd()).resolve()\n",
42
+ " candidates.extend([start_path, *start_path.parents])\n",
43
+ "\n",
44
+ " for candidate in candidates:\n",
45
+ " if (candidate / \"Cargo.toml\").exists() and (candidate / \"src\").is_dir():\n",
46
+ " return candidate\n",
47
+ "\n",
48
+ " raise RuntimeError(\n",
49
+ " \"Could not find the mdfs repository root. \"\n",
50
+ " \"Run the notebook from inside the repo or set MDFS_REPO_ROOT.\"\n",
51
+ " )\n",
52
+ "\n",
53
+ "\n",
54
+ "def find_cargo():\n",
55
+ " \"\"\"Find Cargo even when the Jupyter kernel has a minimal PATH.\"\"\"\n",
56
+ " candidates = []\n",
57
+ " env_cargo = os.environ.get(\"CARGO\")\n",
58
+ " if env_cargo:\n",
59
+ " candidates.append(Path(env_cargo).expanduser())\n",
60
+ "\n",
61
+ " path_cargo = shutil.which(\"cargo\")\n",
62
+ " if path_cargo:\n",
63
+ " candidates.append(Path(path_cargo))\n",
64
+ "\n",
65
+ " candidates.extend([\n",
66
+ " Path.home() / \".cargo\" / \"bin\" / \"cargo\",\n",
67
+ " Path(\"/opt/homebrew/bin/cargo\"),\n",
68
+ " Path(\"/usr/local/bin/cargo\"),\n",
69
+ " ])\n",
70
+ "\n",
71
+ " for candidate in candidates:\n",
72
+ " if candidate.exists() and candidate.is_file():\n",
73
+ " return str(candidate)\n",
74
+ "\n",
75
+ " raise RuntimeError(\n",
76
+ " \"Could not find Cargo. Install Rust from https://rustup.rs, \"\n",
77
+ " \"or set CARGO=/absolute/path/to/cargo before running this notebook.\"\n",
78
+ " )\n",
79
+ "\n",
80
+ "\n",
81
+ "ROOT = find_repo_root()\n",
82
+ "CARGO = find_cargo()\n",
83
+ "DATA_DIR = ROOT / \".demo\" / \"notebook-delegation\"\n",
84
+ "print(f\"Using mdfs repo at {ROOT}\")\n",
85
+ "print(f\"Using cargo at {CARGO}\")\n",
86
+ "\n",
87
+ "if DATA_DIR.exists():\n",
88
+ " shutil.rmtree(DATA_DIR)\n",
89
+ "DATA_DIR.mkdir(parents=True)\n",
90
+ "\n",
91
+ "def run_mdfs_script(lines):\n",
92
+ " env = os.environ.copy()\n",
93
+ " env[\"MARKDOWNFS_DATA_DIR\"] = str(DATA_DIR)\n",
94
+ " env[\"PATH\"] = os.pathsep.join([str(Path(CARGO).parent), env.get(\"PATH\", \"\")])\n",
95
+ " script = \"\\n\".join(lines) + \"\\n\"\n",
96
+ " return subprocess.run(\n",
97
+ " [CARGO, \"run\", \"--quiet\", \"--bin\", \"markdownfs\"],\n",
98
+ " cwd=ROOT,\n",
99
+ " env=env,\n",
100
+ " input=script,\n",
101
+ " text=True,\n",
102
+ " capture_output=True,\n",
103
+ " timeout=60,\n",
104
+ " )"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "markdown",
111
+ "metadata": {},
112
+ "source": [
113
+ "## 2. Create Users, An Agent, And Delegated Work\n",
114
+ "\n",
115
+ "The session creates:\n",
116
+ "\n",
117
+ "- `alice`, the first admin user\n",
118
+ "- `bob`, a human user whose work can be delegated\n",
119
+ "- `research-bot`, an agent with a bearer token\n",
120
+ "- one private file where delegation should fail\n",
121
+ "- one shared file where delegation should succeed"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "result = run_mdfs_script([\n",
129
+ " \"alice\",\n",
130
+ " \"su root\",\n",
131
+ " \"adduser bob\",\n",
132
+ " \"addagent research-bot\",\n",
133
+ " \"mkdir /delegation\",\n",
134
+ " \"chmod 777 /delegation\",\n",
135
+ " \"touch /delegation/private-note.md\",\n",
136
+ " \"chown bob:bob /delegation/private-note.md\",\n",
137
+ " \"chmod 600 /delegation/private-note.md\",\n",
138
+ " \"touch /delegation/shared-note.md\",\n",
139
+ " \"chown bob:bob /delegation/shared-note.md\",\n",
140
+ " \"chmod 666 /delegation/shared-note.md\",\n",
141
+ " \"su research-bot\",\n",
142
+ " \"delegate bob\",\n",
143
+ " \"write /delegation/private-note.md # This should fail because the agent has no write bit\",\n",
144
+ " \"write /delegation/shared-note.md # Delegated Research Note\",\n",
145
+ " \"stat /delegation/shared-note.md\",\n",
146
+ " \"cat /delegation/shared-note.md\",\n",
147
+ " \"commit delegated research note\",\n",
148
+ " \"log\",\n",
149
+ " \"exit\",\n",
150
+ "])\n",
151
+ "\n",
152
+ "print(\"STDOUT:\\n\")\n",
153
+ "print(result.stdout)\n",
154
+ "print(\"STDERR:\\n\")\n",
155
+ "print(result.stderr)\n",
156
+ "\n",
157
+ "if result.returncode != 0:\n",
158
+ " raise RuntimeError(\"scripted mdfs session failed\")"
159
+ ],
160
+ "execution_count": null,
161
+ "outputs": []
162
+ },
163
+ {
164
+ "cell_type": "markdown",
165
+ "metadata": {},
166
+ "source": [
167
+ "## 3. Pull Out The Agent Token\n",
168
+ "\n",
169
+ "The raw token is printed once. In a real workflow, save it immediately and pass it as `Authorization: Bearer <token>` to the HTTP API."
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "metadata": {},
175
+ "source": [
176
+ "token_match = re.search(r\"API token \\(save this .*?\\):\\n\\s+([a-f0-9]+)\", result.stdout)\n",
177
+ "agent_token = token_match.group(1) if token_match else None\n",
178
+ "print(agent_token)"
179
+ ],
180
+ "execution_count": null,
181
+ "outputs": []
182
+ },
183
+ {
184
+ "cell_type": "markdown",
185
+ "metadata": {},
186
+ "source": [
187
+ "## 4. What To Notice\n",
188
+ "\n",
189
+ "- `delegate bob` changes the effective ownership of successful writes to Bob.\n",
190
+ "- The write to `private-note.md` fails because Bob can write it, but the agent cannot; delegation uses least privilege.\n",
191
+ "- The write to `shared-note.md` succeeds because both Bob and the agent have write permission.\n",
192
+ "- The commit gives the handoff a recoverable version boundary."
193
+ ]
194
+ }
195
+ ],
196
+ "metadata": {
197
+ "kernelspec": {
198
+ "display_name": "Python 3",
199
+ "language": "python",
200
+ "name": "python3"
201
+ },
202
+ "language_info": {
203
+ "name": "python",
204
+ "pygments_lexer": "ipython3"
205
+ }
206
+ },
207
+ "nbformat": 4,
208
+ "nbformat_minor": 5
209
+ }
examples/notebooks/README.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Notebook Examples
2
+
3
+ These notebooks are runnable walkthroughs for trying `mdfs` from Python/Jupyter.
4
+
5
+ | Notebook | Shows |
6
+ |---|---|
7
+ | `01_getting_started_http.ipynb` | Start the HTTP server, write markdown, read it back, search, commit, and inspect history |
8
+ | `02_mount_and_start_using_mdfs.ipynb` | Build and run the optional FUSE mount, then use `mdfs` like a local directory |
9
+ | `03_user_delegation_to_agents.ipynb` | Create users and an agent, delegate work to the agent, and observe least-privilege behavior |
10
+
11
+ The notebooks auto-detect the repository root when launched from inside the repo, including from `examples/notebooks/`. If Jupyter starts somewhere else, set `MDFS_REPO_ROOT` to the repository path before running the first cell.
12
+
13
+ ## Prerequisites
14
+
15
+ - Rust toolchain installed (`rustc` and `cargo`)
16
+ - Python 3 Jupyter environment
17
+ - For the mount notebook only: a working FUSE/macFUSE setup for your OS. On macOS, install `pkg-config` and macFUSE so `fuser` can find `fuse.pc`, for example `brew install pkg-config && brew install --cask macfuse`.
18
+
19
+ If Jupyter does not inherit your shell `PATH`, the notebooks will also look for Cargo at `~/.cargo/bin/cargo`, `/opt/homebrew/bin/cargo`, and `/usr/local/bin/cargo`, and for `pkg-config` at common Homebrew/MacPorts locations. You can override discovery with `CARGO=/absolute/path/to/cargo` and `PKG_CONFIG=/absolute/path/to/pkg-config`.
20
+
21
+ The HTTP and delegation notebooks use only Python's standard library.
src/auth/mod.rs ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pub mod perms;
2
+ pub mod registry;
3
+ pub mod session;
4
+
5
+ use serde::{Deserialize, Serialize};
6
+
7
+ pub type Uid = u32;
8
+ pub type Gid = u32;
9
+
10
+ pub const ROOT_UID: Uid = 0;
11
+ pub const ROOT_GID: Gid = 0;
12
+ pub const WHEEL_GID: Gid = 1;
13
+
14
+ #[derive(Debug, Clone, Serialize, Deserialize)]
15
+ pub struct User {
16
+ pub uid: Uid,
17
+ pub name: String,
18
+ pub groups: Vec<Gid>,
19
+ pub api_token: Option<String>,
20
+ pub is_agent: bool,
21
+ }
22
+
23
+ #[derive(Debug, Clone, Serialize, Deserialize)]
24
+ pub struct Group {
25
+ pub gid: Gid,
26
+ pub name: String,
27
+ pub members: Vec<Uid>,
28
+ }
src/auth/perms.rs ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use super::{Gid, Uid, ROOT_UID};
2
+ use crate::fs::inode::Inode;
3
+
4
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5
+ pub enum Access {
6
+ Read,
7
+ Write,
8
+ Execute,
9
+ }
10
+
11
+ /// Check if user `uid` with `user_groups` can perform `access` on `inode`.
12
+ /// Root (uid=0) bypasses all checks.
13
+ pub fn check_permission(inode: &Inode, uid: Uid, user_groups: &[Gid], access: Access) -> bool {
14
+ if uid == ROOT_UID {
15
+ return true;
16
+ }
17
+
18
+ let bit = match access {
19
+ Access::Read => 4,
20
+ Access::Write => 2,
21
+ Access::Execute => 1,
22
+ };
23
+
24
+ if uid == inode.uid {
25
+ // Owner bits (bits 8-6)
26
+ return (inode.mode >> 6) & bit != 0;
27
+ }
28
+
29
+ if user_groups.contains(&inode.gid) {
30
+ // Group bits (bits 5-3)
31
+ return (inode.mode >> 3) & bit != 0;
32
+ }
33
+
34
+ // Other bits (bits 2-0)
35
+ inode.mode & bit != 0
36
+ }
37
+
38
+ /// Check if sticky bit is set (0o1000).
39
+ /// In a sticky directory, only the file owner, dir owner, or root can delete/rename.
40
+ pub fn has_sticky_bit(mode: u16) -> bool {
41
+ mode & 0o1000 != 0
42
+ }
43
+
44
+ /// Check if setgid bit is set (0o2000).
45
+ /// New files/dirs in a setgid directory inherit the directory's group.
46
+ pub fn has_setgid(mode: u16) -> bool {
47
+ mode & 0o2000 != 0
48
+ }
49
+
50
+ #[cfg(test)]
51
+ mod tests {
52
+ use super::*;
53
+ use crate::fs::inode::Inode;
54
+
55
+ fn make_file(mode: u16, uid: u32, gid: u32) -> Inode {
56
+ let mut inode = Inode::new_file(1, uid, gid);
57
+ inode.mode = mode;
58
+ inode
59
+ }
60
+
61
+ #[test]
62
+ fn test_root_bypasses_all() {
63
+ let inode = make_file(0o000, 99, 99); // no permissions
64
+ assert!(check_permission(&inode, ROOT_UID, &[0], Access::Read));
65
+ assert!(check_permission(&inode, ROOT_UID, &[0], Access::Write));
66
+ assert!(check_permission(&inode, ROOT_UID, &[0], Access::Execute));
67
+ }
68
+
69
+ #[test]
70
+ fn test_owner_permissions() {
71
+ let inode = make_file(0o600, 1, 10); // rw- --- ---
72
+ assert!(check_permission(&inode, 1, &[10], Access::Read));
73
+ assert!(check_permission(&inode, 1, &[10], Access::Write));
74
+ assert!(!check_permission(&inode, 1, &[10], Access::Execute));
75
+ }
76
+
77
+ #[test]
78
+ fn test_group_permissions() {
79
+ let inode = make_file(0o050, 1, 10); // --- r-x ---
80
+ assert!(!check_permission(&inode, 2, &[10], Access::Write));
81
+ assert!(check_permission(&inode, 2, &[10], Access::Read));
82
+ assert!(check_permission(&inode, 2, &[10], Access::Execute));
83
+ }
84
+
85
+ #[test]
86
+ fn test_other_permissions() {
87
+ let inode = make_file(0o004, 1, 10); // --- --- r--
88
+ assert!(check_permission(&inode, 99, &[99], Access::Read));
89
+ assert!(!check_permission(&inode, 99, &[99], Access::Write));
90
+ }
91
+
92
+ #[test]
93
+ fn test_no_permissions() {
94
+ let inode = make_file(0o000, 1, 10);
95
+ assert!(!check_permission(&inode, 2, &[20], Access::Read));
96
+ assert!(!check_permission(&inode, 2, &[20], Access::Write));
97
+ assert!(!check_permission(&inode, 2, &[20], Access::Execute));
98
+ }
99
+
100
+ #[test]
101
+ fn test_sticky_and_setgid() {
102
+ assert!(has_sticky_bit(0o1755));
103
+ assert!(!has_sticky_bit(0o0755));
104
+ assert!(has_setgid(0o2755));
105
+ assert!(!has_setgid(0o0755));
106
+ }
107
+ }
src/auth/registry.rs ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use super::{Gid, Group, Uid, User, ROOT_GID, ROOT_UID, WHEEL_GID};
2
+ use crate::error::VfsError;
3
+ use serde::{Deserialize, Serialize};
4
+ use sha2::{Digest, Sha256};
5
+ use std::collections::HashMap;
6
+
7
+ #[derive(Debug, Clone, Serialize, Deserialize)]
8
+ pub struct UserRegistry {
9
+ users: HashMap<Uid, User>,
10
+ groups: HashMap<Gid, Group>,
11
+ name_to_uid: HashMap<String, Uid>,
12
+ name_to_gid: HashMap<String, Gid>,
13
+ next_uid: Uid,
14
+ next_gid: Gid,
15
+ }
16
+
17
+ impl UserRegistry {
18
+ pub fn new() -> Self {
19
+ let mut reg = UserRegistry {
20
+ users: HashMap::new(),
21
+ groups: HashMap::new(),
22
+ name_to_uid: HashMap::new(),
23
+ name_to_gid: HashMap::new(),
24
+ next_uid: 1,
25
+ next_gid: 2,
26
+ };
27
+
28
+ // Bootstrap: root group
29
+ reg.groups.insert(
30
+ ROOT_GID,
31
+ Group {
32
+ gid: ROOT_GID,
33
+ name: "root".to_string(),
34
+ members: vec![ROOT_UID],
35
+ },
36
+ );
37
+ reg.name_to_gid.insert("root".to_string(), ROOT_GID);
38
+
39
+ // Bootstrap: wheel group (admin)
40
+ reg.groups.insert(
41
+ WHEEL_GID,
42
+ Group {
43
+ gid: WHEEL_GID,
44
+ name: "wheel".to_string(),
45
+ members: vec![ROOT_UID],
46
+ },
47
+ );
48
+ reg.name_to_gid.insert("wheel".to_string(), WHEEL_GID);
49
+
50
+ // Bootstrap: root user
51
+ reg.users.insert(
52
+ ROOT_UID,
53
+ User {
54
+ uid: ROOT_UID,
55
+ name: "root".to_string(),
56
+ groups: vec![ROOT_GID, WHEEL_GID],
57
+ api_token: None,
58
+ is_agent: false,
59
+ },
60
+ );
61
+ reg.name_to_uid.insert("root".to_string(), ROOT_UID);
62
+
63
+ reg
64
+ }
65
+
66
+ pub fn add_user(&mut self, name: &str, is_agent: bool) -> Result<(Uid, Option<String>), VfsError> {
67
+ if self.name_to_uid.contains_key(name) {
68
+ return Err(VfsError::AuthError {
69
+ message: format!("user already exists: {name}"),
70
+ });
71
+ }
72
+
73
+ let uid = self.next_uid;
74
+ self.next_uid += 1;
75
+
76
+ // Create personal group
77
+ let gid = self.next_gid;
78
+ self.next_gid += 1;
79
+
80
+ let group = Group {
81
+ gid,
82
+ name: name.to_string(),
83
+ members: vec![uid],
84
+ };
85
+ self.groups.insert(gid, group);
86
+ self.name_to_gid.insert(name.to_string(), gid);
87
+
88
+ // Generate API token for agents
89
+ let (api_token, raw_token) = if is_agent {
90
+ let raw = generate_token();
91
+ let hash = hash_token(&raw);
92
+ (Some(hash), Some(raw))
93
+ } else {
94
+ (None, None)
95
+ };
96
+
97
+ let user = User {
98
+ uid,
99
+ name: name.to_string(),
100
+ groups: vec![gid],
101
+ api_token,
102
+ is_agent,
103
+ };
104
+ self.users.insert(uid, user);
105
+ self.name_to_uid.insert(name.to_string(), uid);
106
+
107
+ Ok((uid, raw_token))
108
+ }
109
+
110
+ pub fn del_user(&mut self, name: &str) -> Result<(), VfsError> {
111
+ let uid = self.lookup_uid(name).ok_or_else(|| VfsError::AuthError {
112
+ message: format!("no such user: {name}"),
113
+ })?;
114
+
115
+ if uid == ROOT_UID {
116
+ return Err(VfsError::AuthError {
117
+ message: "cannot delete root".to_string(),
118
+ });
119
+ }
120
+
121
+ // Remove from all groups
122
+ for group in self.groups.values_mut() {
123
+ group.members.retain(|&m| m != uid);
124
+ }
125
+
126
+ self.users.remove(&uid);
127
+ self.name_to_uid.remove(name);
128
+ Ok(())
129
+ }
130
+
131
+ pub fn add_group(&mut self, name: &str) -> Result<Gid, VfsError> {
132
+ if self.name_to_gid.contains_key(name) {
133
+ return Err(VfsError::AuthError {
134
+ message: format!("group already exists: {name}"),
135
+ });
136
+ }
137
+
138
+ let gid = self.next_gid;
139
+ self.next_gid += 1;
140
+
141
+ let group = Group {
142
+ gid,
143
+ name: name.to_string(),
144
+ members: Vec::new(),
145
+ };
146
+ self.groups.insert(gid, group);
147
+ self.name_to_gid.insert(name.to_string(), gid);
148
+ Ok(gid)
149
+ }
150
+
151
+ pub fn del_group(&mut self, name: &str) -> Result<(), VfsError> {
152
+ let gid = self.lookup_gid(name).ok_or_else(|| VfsError::AuthError {
153
+ message: format!("no such group: {name}"),
154
+ })?;
155
+
156
+ if gid == ROOT_GID || gid == WHEEL_GID {
157
+ return Err(VfsError::AuthError {
158
+ message: format!("cannot delete system group: {name}"),
159
+ });
160
+ }
161
+
162
+ // Remove group from all users' group lists
163
+ for user in self.users.values_mut() {
164
+ user.groups.retain(|&g| g != gid);
165
+ }
166
+
167
+ self.groups.remove(&gid);
168
+ self.name_to_gid.remove(name);
169
+ Ok(())
170
+ }
171
+
172
+ pub fn usermod_add_group(&mut self, username: &str, groupname: &str) -> Result<(), VfsError> {
173
+ let uid = self.lookup_uid(username).ok_or_else(|| VfsError::AuthError {
174
+ message: format!("no such user: {username}"),
175
+ })?;
176
+ let gid = self.lookup_gid(groupname).ok_or_else(|| VfsError::AuthError {
177
+ message: format!("no such group: {groupname}"),
178
+ })?;
179
+
180
+ let user = self.users.get_mut(&uid).unwrap();
181
+ if !user.groups.contains(&gid) {
182
+ user.groups.push(gid);
183
+ }
184
+
185
+ let group = self.groups.get_mut(&gid).unwrap();
186
+ if !group.members.contains(&uid) {
187
+ group.members.push(uid);
188
+ }
189
+
190
+ Ok(())
191
+ }
192
+
193
+ pub fn usermod_remove_group(&mut self, username: &str, groupname: &str) -> Result<(), VfsError> {
194
+ let uid = self.lookup_uid(username).ok_or_else(|| VfsError::AuthError {
195
+ message: format!("no such user: {username}"),
196
+ })?;
197
+ let gid = self.lookup_gid(groupname).ok_or_else(|| VfsError::AuthError {
198
+ message: format!("no such group: {groupname}"),
199
+ })?;
200
+
201
+ let user = self.users.get_mut(&uid).unwrap();
202
+ user.groups.retain(|&g| g != gid);
203
+
204
+ let group = self.groups.get_mut(&gid).unwrap();
205
+ group.members.retain(|&m| m != uid);
206
+
207
+ Ok(())
208
+ }
209
+
210
+ pub fn lookup_uid(&self, name: &str) -> Option<Uid> {
211
+ self.name_to_uid.get(name).copied()
212
+ }
213
+
214
+ pub fn lookup_gid(&self, name: &str) -> Option<Gid> {
215
+ self.name_to_gid.get(name).copied()
216
+ }
217
+
218
+ pub fn get_user(&self, uid: Uid) -> Option<&User> {
219
+ self.users.get(&uid)
220
+ }
221
+
222
+ pub fn get_group(&self, gid: Gid) -> Option<&Group> {
223
+ self.groups.get(&gid)
224
+ }
225
+
226
+ pub fn user_in_group(&self, uid: Uid, gid: Gid) -> bool {
227
+ self.users
228
+ .get(&uid)
229
+ .map(|u| u.groups.contains(&gid))
230
+ .unwrap_or(false)
231
+ }
232
+
233
+ pub fn authenticate_token(&self, raw_token: &str) -> Option<Uid> {
234
+ let hash = hash_token(raw_token);
235
+ self.users
236
+ .values()
237
+ .find(|u| u.api_token.as_deref() == Some(&hash))
238
+ .map(|u| u.uid)
239
+ }
240
+
241
+ pub fn list_users(&self) -> Vec<&User> {
242
+ let mut users: Vec<&User> = self.users.values().collect();
243
+ users.sort_by_key(|u| u.uid);
244
+ users
245
+ }
246
+
247
+ pub fn list_groups(&self) -> Vec<&Group> {
248
+ let mut groups: Vec<&Group> = self.groups.values().collect();
249
+ groups.sort_by_key(|g| g.gid);
250
+ groups
251
+ }
252
+
253
+ pub fn group_name(&self, gid: Gid) -> Option<&str> {
254
+ self.groups.get(&gid).map(|g| g.name.as_str())
255
+ }
256
+
257
+ pub fn user_name(&self, uid: Uid) -> Option<&str> {
258
+ self.users.get(&uid).map(|u| u.name.as_str())
259
+ }
260
+
261
+ pub fn is_wheel_member(&self, uid: Uid) -> bool {
262
+ self.user_in_group(uid, WHEEL_GID)
263
+ }
264
+ }
265
+
266
+ fn generate_token() -> String {
267
+ use std::time::{SystemTime, UNIX_EPOCH};
268
+ let seed = SystemTime::now()
269
+ .duration_since(UNIX_EPOCH)
270
+ .unwrap_or_default()
271
+ .as_nanos();
272
+ let mut hasher = Sha256::new();
273
+ hasher.update(seed.to_le_bytes());
274
+ hasher.update(b"markdownfs-agent-token");
275
+ let result = hasher.finalize();
276
+ result.iter().map(|b| format!("{b:02x}")).collect()
277
+ }
278
+
279
+ fn hash_token(raw: &str) -> String {
280
+ let mut hasher = Sha256::new();
281
+ hasher.update(raw.as_bytes());
282
+ let result = hasher.finalize();
283
+ result.iter().map(|b| format!("{b:02x}")).collect()
284
+ }
285
+
286
+ #[cfg(test)]
287
+ mod tests {
288
+ use super::*;
289
+
290
+ #[test]
291
+ fn test_bootstrap() {
292
+ let reg = UserRegistry::new();
293
+ assert!(reg.get_user(ROOT_UID).is_some());
294
+ assert_eq!(reg.get_user(ROOT_UID).unwrap().name, "root");
295
+ assert!(reg.get_group(ROOT_GID).is_some());
296
+ assert!(reg.get_group(WHEEL_GID).is_some());
297
+ assert!(reg.is_wheel_member(ROOT_UID));
298
+ }
299
+
300
+ #[test]
301
+ fn test_add_user() {
302
+ let mut reg = UserRegistry::new();
303
+ let (uid, token) = reg.add_user("alice", false).unwrap();
304
+ assert_eq!(uid, 1);
305
+ assert!(token.is_none());
306
+ assert_eq!(reg.lookup_uid("alice"), Some(1));
307
+ assert!(reg.get_user(1).is_some());
308
+ // Personal group created
309
+ assert!(reg.lookup_gid("alice").is_some());
310
+ }
311
+
312
+ #[test]
313
+ fn test_add_agent() {
314
+ let mut reg = UserRegistry::new();
315
+ let (uid, token) = reg.add_user("bot1", true).unwrap();
316
+ assert!(token.is_some());
317
+ // Authenticate with token
318
+ let raw = token.unwrap();
319
+ assert_eq!(reg.authenticate_token(&raw), Some(uid));
320
+ assert_eq!(reg.authenticate_token("wrong-token"), None);
321
+ }
322
+
323
+ #[test]
324
+ fn test_del_user() {
325
+ let mut reg = UserRegistry::new();
326
+ reg.add_user("bob", false).unwrap();
327
+ assert!(reg.lookup_uid("bob").is_some());
328
+ reg.del_user("bob").unwrap();
329
+ assert!(reg.lookup_uid("bob").is_none());
330
+ }
331
+
332
+ #[test]
333
+ fn test_cannot_delete_root() {
334
+ let mut reg = UserRegistry::new();
335
+ assert!(reg.del_user("root").is_err());
336
+ }
337
+
338
+ #[test]
339
+ fn test_add_group_and_membership() {
340
+ let mut reg = UserRegistry::new();
341
+ reg.add_user("alice", false).unwrap();
342
+ let gid = reg.add_group("devs").unwrap();
343
+ reg.usermod_add_group("alice", "devs").unwrap();
344
+ assert!(reg.user_in_group(1, gid));
345
+ // Remove from group
346
+ reg.usermod_remove_group("alice", "devs").unwrap();
347
+ assert!(!reg.user_in_group(1, gid));
348
+ }
349
+
350
+ #[test]
351
+ fn test_duplicate_user() {
352
+ let mut reg = UserRegistry::new();
353
+ reg.add_user("alice", false).unwrap();
354
+ assert!(reg.add_user("alice", false).is_err());
355
+ }
356
+
357
+ #[test]
358
+ fn test_cannot_delete_system_groups() {
359
+ let mut reg = UserRegistry::new();
360
+ assert!(reg.del_group("root").is_err());
361
+ assert!(reg.del_group("wheel").is_err());
362
+ }
363
+ }
src/auth/session.rs ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use super::perms::{check_permission, Access};
2
+ use super::{Gid, Uid, ROOT_UID};
3
+ use crate::fs::inode::Inode;
4
+
5
+ /// Context for the user an agent is acting on behalf of.
6
+ #[derive(Debug, Clone)]
7
+ pub struct DelegateContext {
8
+ pub uid: Uid,
9
+ pub gid: Gid,
10
+ pub groups: Vec<Gid>,
11
+ pub username: String,
12
+ }
13
+
14
+ #[derive(Debug, Clone)]
15
+ pub struct Session {
16
+ pub uid: Uid,
17
+ pub gid: Gid,
18
+ pub groups: Vec<Gid>,
19
+ pub username: String,
20
+ /// When set, the session acts on behalf of this user.
21
+ /// All permission checks require BOTH the principal AND
22
+ /// the delegate to have access (intersection / least-privilege).
23
+ pub delegate: Option<DelegateContext>,
24
+ }
25
+
26
+ impl Session {
27
+ pub fn new(uid: Uid, gid: Gid, groups: Vec<Gid>, username: String) -> Self {
28
+ Session {
29
+ uid,
30
+ gid,
31
+ groups,
32
+ username,
33
+ delegate: None,
34
+ }
35
+ }
36
+
37
+ pub fn root() -> Self {
38
+ Session {
39
+ uid: ROOT_UID,
40
+ gid: 0,
41
+ groups: vec![0, 1],
42
+ username: "root".to_string(),
43
+ delegate: None,
44
+ }
45
+ }
46
+
47
+ pub fn is_root(&self) -> bool {
48
+ self.uid == ROOT_UID
49
+ }
50
+
51
+ /// Check permission with delegation intersection.
52
+ /// Returns true only if both the principal AND the delegate (if any) have access.
53
+ pub fn has_permission(&self, inode: &Inode, access: Access) -> bool {
54
+ if !check_permission(inode, self.uid, &self.groups, access) {
55
+ return false;
56
+ }
57
+ if let Some(ref delegate) = self.delegate {
58
+ if !check_permission(inode, delegate.uid, &delegate.groups, access) {
59
+ return false;
60
+ }
61
+ }
62
+ true
63
+ }
64
+
65
+ /// Check permission using raw mode/uid/gid bits (for LsEntry filtering).
66
+ /// Respects delegation intersection.
67
+ pub fn has_permission_bits(
68
+ &self,
69
+ mode: u16,
70
+ file_uid: Uid,
71
+ file_gid: Gid,
72
+ access: Access,
73
+ ) -> bool {
74
+ if !check_bits(self.uid, &self.groups, mode, file_uid, file_gid, access) {
75
+ return false;
76
+ }
77
+ if let Some(ref delegate) = self.delegate {
78
+ if !check_bits(
79
+ delegate.uid,
80
+ &delegate.groups,
81
+ mode,
82
+ file_uid,
83
+ file_gid,
84
+ access,
85
+ ) {
86
+ return false;
87
+ }
88
+ }
89
+ true
90
+ }
91
+
92
+ /// The effective uid for file ownership — if delegating, use the delegate's uid.
93
+ pub fn effective_uid(&self) -> Uid {
94
+ match &self.delegate {
95
+ Some(d) => d.uid,
96
+ None => self.uid,
97
+ }
98
+ }
99
+
100
+ /// The effective gid for file ownership — if delegating, use the delegate's gid.
101
+ pub fn effective_gid(&self) -> Gid {
102
+ match &self.delegate {
103
+ Some(d) => d.gid,
104
+ None => self.gid,
105
+ }
106
+ }
107
+
108
+ /// Whether either the principal or (if delegating) the delegate is root.
109
+ /// For intersection: both must pass, so root status only helps if the OTHER side passes.
110
+ /// This is used for checks like "is this session effectively root?" — answer: only if
111
+ /// there's no delegate constraining it.
112
+ pub fn is_effectively_root(&self) -> bool {
113
+ if self.uid != ROOT_UID {
114
+ return false;
115
+ }
116
+ match &self.delegate {
117
+ Some(d) => d.uid == ROOT_UID,
118
+ None => true,
119
+ }
120
+ }
121
+
122
+ /// Whether the principal (ignoring delegation) is the owner of a file.
123
+ /// When delegating, checks if the delegate is the owner.
124
+ pub fn is_effective_owner(&self, file_uid: Uid) -> bool {
125
+ match &self.delegate {
126
+ Some(d) => {
127
+ // Both must be owner or root
128
+ let principal_ok = self.uid == ROOT_UID || self.uid == file_uid;
129
+ let delegate_ok = d.uid == ROOT_UID || d.uid == file_uid;
130
+ principal_ok && delegate_ok
131
+ }
132
+ None => self.uid == ROOT_UID || self.uid == file_uid,
133
+ }
134
+ }
135
+ }
136
+
137
+ /// Raw bit-level permission check for a single principal.
138
+ fn check_bits(
139
+ uid: Uid,
140
+ groups: &[Gid],
141
+ mode: u16,
142
+ file_uid: Uid,
143
+ file_gid: Gid,
144
+ access: Access,
145
+ ) -> bool {
146
+ if uid == ROOT_UID {
147
+ return true;
148
+ }
149
+ let bit = match access {
150
+ Access::Read => 4,
151
+ Access::Write => 2,
152
+ Access::Execute => 1,
153
+ };
154
+ if uid == file_uid {
155
+ return (mode >> 6) & bit != 0;
156
+ }
157
+ if groups.contains(&file_gid) {
158
+ return (mode >> 3) & bit != 0;
159
+ }
160
+ mode & bit != 0
161
+ }
src/bin/mdfs_mcp.rs ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use markdownfs::config::Config;
2
+ use markdownfs::db::MarkdownDb;
3
+
4
+ use rmcp::model::*;
5
+ use rmcp::service::RoleServer;
6
+ use rmcp::{ErrorData as McpError, ServerHandler, ServiceExt};
7
+
8
+ use std::sync::Arc;
9
+
10
+ struct McpServer {
11
+ db: MarkdownDb,
12
+ }
13
+
14
+ fn tool_schema(props: serde_json::Value) -> Arc<JsonObject> {
15
+ let mut obj = serde_json::Map::new();
16
+ obj.insert("type".into(), "object".into());
17
+ if let Some(p) = props.get("properties") {
18
+ obj.insert("properties".into(), p.clone());
19
+ }
20
+ if let Some(r) = props.get("required") {
21
+ obj.insert("required".into(), r.clone());
22
+ }
23
+ Arc::new(obj.into())
24
+ }
25
+
26
+ fn make_tool(name: &'static str, desc: &'static str, schema: serde_json::Value) -> Tool {
27
+ Tool::new(name, desc, tool_schema(schema))
28
+ }
29
+
30
+ impl McpServer {
31
+ fn tool_defs() -> Vec<Tool> {
32
+ vec![
33
+ make_tool("read_file", "Read a markdown file by path", serde_json::json!({
34
+ "properties": {"path": {"type": "string"}},
35
+ "required": ["path"]
36
+ })),
37
+ make_tool("write_file", "Write content to a markdown file (creates if needed)", serde_json::json!({
38
+ "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
39
+ "required": ["path", "content"]
40
+ })),
41
+ make_tool("list_directory", "List files in a directory", serde_json::json!({
42
+ "properties": {"path": {"type": "string"}}
43
+ })),
44
+ make_tool("search_files", "Search file contents with a regex pattern", serde_json::json!({
45
+ "properties": {"pattern": {"type": "string"}, "path": {"type": "string"}, "recursive": {"type": "boolean"}},
46
+ "required": ["pattern"]
47
+ })),
48
+ make_tool("find_files", "Find files by glob pattern", serde_json::json!({
49
+ "properties": {"path": {"type": "string"}, "name": {"type": "string"}}
50
+ })),
51
+ make_tool("create_directory", "Create a directory (with parents)", serde_json::json!({
52
+ "properties": {"path": {"type": "string"}},
53
+ "required": ["path"]
54
+ })),
55
+ make_tool("delete_file", "Delete a file or directory", serde_json::json!({
56
+ "properties": {"path": {"type": "string"}, "recursive": {"type": "boolean"}},
57
+ "required": ["path"]
58
+ })),
59
+ make_tool("move_file", "Move or rename a file/directory", serde_json::json!({
60
+ "properties": {"source": {"type": "string"}, "destination": {"type": "string"}},
61
+ "required": ["source", "destination"]
62
+ })),
63
+ make_tool("commit", "Commit current filesystem state", serde_json::json!({
64
+ "properties": {"message": {"type": "string"}},
65
+ "required": ["message"]
66
+ })),
67
+ make_tool("get_history", "Show commit history", serde_json::json!({
68
+ "properties": {}
69
+ })),
70
+ make_tool("revert", "Revert to a previous commit", serde_json::json!({
71
+ "properties": {"hash": {"type": "string"}},
72
+ "required": ["hash"]
73
+ })),
74
+ ]
75
+ }
76
+
77
+ async fn handle_tool(&self, name: &str, args: &serde_json::Value) -> Result<String, String> {
78
+ match name {
79
+ "read_file" => {
80
+ let path = args["path"].as_str().ok_or("missing path")?;
81
+ let content = self.db.cat(path).await.map_err(|e| e.to_string())?;
82
+ Ok(String::from_utf8_lossy(&content).into_owned())
83
+ }
84
+ "write_file" => {
85
+ let path = args["path"].as_str().ok_or("missing path")?;
86
+ let content = args["content"].as_str().ok_or("missing content")?;
87
+ if self.db.stat(path).await.is_err() {
88
+ let trimmed = path.trim_end_matches('/');
89
+ if let Some(idx) = trimmed.rfind('/') {
90
+ let parent = &trimmed[..idx];
91
+ if !parent.is_empty() && self.db.stat(parent).await.is_err() {
92
+ self.db.mkdir_p(parent, 0, 0).await.map_err(|e| e.to_string())?;
93
+ }
94
+ }
95
+ self.db.touch(path, 0, 0).await.map_err(|e| e.to_string())?;
96
+ }
97
+ self.db.write_file(path, content.as_bytes().to_vec()).await.map_err(|e| e.to_string())?;
98
+ Ok(format!("Written {} bytes to {path}", content.len()))
99
+ }
100
+ "list_directory" => {
101
+ let path = args.get("path").and_then(|v| v.as_str());
102
+ let entries = self.db.ls(path).await.map_err(|e| e.to_string())?;
103
+ let mut out = String::new();
104
+ for e in &entries {
105
+ let suffix = if e.is_dir { "/" } else { "" };
106
+ out.push_str(&format!("{}{suffix}\n", e.name));
107
+ }
108
+ Ok(out)
109
+ }
110
+ "search_files" => {
111
+ let pattern = args["pattern"].as_str().ok_or("missing pattern")?;
112
+ let path = args.get("path").and_then(|v| v.as_str());
113
+ let recursive = args.get("recursive").and_then(|v| v.as_bool()).unwrap_or(true);
114
+ let results = self.db.grep(pattern, path, recursive, None).await.map_err(|e| e.to_string())?;
115
+ let mut out = String::new();
116
+ for r in &results { out.push_str(&format!("{}:{}: {}\n", r.file, r.line_num, r.line)); }
117
+ if out.is_empty() { out = "No matches found.".to_string(); }
118
+ Ok(out)
119
+ }
120
+ "find_files" => {
121
+ let path = args.get("path").and_then(|v| v.as_str());
122
+ let name = args.get("name").and_then(|v| v.as_str());
123
+ let results = self.db.find(path, name, None).await.map_err(|e| e.to_string())?;
124
+ Ok(results.join("\n"))
125
+ }
126
+ "create_directory" => {
127
+ let path = args["path"].as_str().ok_or("missing path")?;
128
+ self.db.mkdir_p(path, 0, 0).await.map_err(|e| e.to_string())?;
129
+ Ok(format!("Created directory: {path}"))
130
+ }
131
+ "delete_file" => {
132
+ let path = args["path"].as_str().ok_or("missing path")?;
133
+ let recursive = args.get("recursive").and_then(|v| v.as_bool()).unwrap_or(false);
134
+ if recursive { self.db.rm_rf(path).await } else { self.db.rm(path).await }
135
+ .map_err(|e| e.to_string())?;
136
+ Ok(format!("Deleted: {path}"))
137
+ }
138
+ "move_file" => {
139
+ let src = args["source"].as_str().ok_or("missing source")?;
140
+ let dst = args["destination"].as_str().ok_or("missing destination")?;
141
+ self.db.mv(src, dst).await.map_err(|e| e.to_string())?;
142
+ Ok(format!("Moved {src} -> {dst}"))
143
+ }
144
+ "commit" => {
145
+ let message = args["message"].as_str().ok_or("missing message")?;
146
+ let hash = self.db.commit(message, "mcp-agent").await.map_err(|e| e.to_string())?;
147
+ Ok(format!("[{hash}] {message}"))
148
+ }
149
+ "get_history" => {
150
+ let commits = self.db.vcs_log().await;
151
+ if commits.is_empty() { return Ok("No commits yet.".to_string()); }
152
+ let mut out = String::new();
153
+ for c in &commits { out.push_str(&format!("{} {} {}\n", c.id.short_hex(), c.author, c.message)); }
154
+ Ok(out)
155
+ }
156
+ "revert" => {
157
+ let hash = args["hash"].as_str().ok_or("missing hash")?;
158
+ self.db.revert(hash).await.map_err(|e| e.to_string())?;
159
+ Ok(format!("Reverted to {hash}"))
160
+ }
161
+ _ => Err(format!("unknown tool: {name}")),
162
+ }
163
+ }
164
+ }
165
+
166
+ impl ServerHandler for McpServer {
167
+ fn get_info(&self) -> ServerInfo {
168
+ let mut caps = ServerCapabilities::default();
169
+ caps.tools = Some(ToolsCapability { list_changed: None });
170
+ caps.resources = Some(ResourcesCapability {
171
+ subscribe: None,
172
+ list_changed: None,
173
+ });
174
+ InitializeResult::new(caps)
175
+ .with_instructions(
176
+ "mdfs is a markdown-only virtual filesystem with Git-like versioning. \
177
+ Use tools to read, write, search, and manage markdown files. \
178
+ All files must have .md extension.",
179
+ )
180
+ }
181
+
182
+ fn list_tools(
183
+ &self,
184
+ _request: Option<PaginatedRequestParams>,
185
+ _context: rmcp::service::RequestContext<RoleServer>,
186
+ ) -> impl std::future::Future<Output = Result<ListToolsResult, McpError>> + Send + '_ {
187
+ async {
188
+ let mut result = ListToolsResult::default();
189
+ result.tools = Self::tool_defs();
190
+ Ok(result)
191
+ }
192
+ }
193
+
194
+ fn call_tool(
195
+ &self,
196
+ request: CallToolRequestParams,
197
+ _context: rmcp::service::RequestContext<RoleServer>,
198
+ ) -> impl std::future::Future<Output = Result<CallToolResult, McpError>> + Send + '_ {
199
+ async move {
200
+ let args = serde_json::to_value(&request.arguments).unwrap_or_default();
201
+ match self.handle_tool(&request.name, &args).await {
202
+ Ok(text) => {
203
+ let mut result = CallToolResult::default();
204
+ result.content = vec![Content::text(text)];
205
+ result.is_error = Some(false);
206
+ Ok(result)
207
+ }
208
+ Err(e) => {
209
+ let mut result = CallToolResult::default();
210
+ result.content = vec![Content::text(e)];
211
+ result.is_error = Some(true);
212
+ Ok(result)
213
+ }
214
+ }
215
+ }
216
+ }
217
+
218
+ fn list_resources(
219
+ &self,
220
+ _request: Option<PaginatedRequestParams>,
221
+ _context: rmcp::service::RequestContext<RoleServer>,
222
+ ) -> impl std::future::Future<Output = Result<ListResourcesResult, McpError>> + Send + '_ {
223
+ async {
224
+ let resource = RawResource::new("mdfs://tree", "Directory Tree")
225
+ .with_description("Full directory tree of the filesystem")
226
+ .with_mime_type("text/plain");
227
+ let legacy_resource = RawResource::new("markdownfs://tree", "Directory Tree (legacy)")
228
+ .with_description("Legacy alias for mdfs://tree")
229
+ .with_mime_type("text/plain");
230
+ let mut result = ListResourcesResult::default();
231
+ result.resources = vec![
232
+ Annotated::new(resource, None),
233
+ Annotated::new(legacy_resource, None),
234
+ ];
235
+ Ok(result)
236
+ }
237
+ }
238
+
239
+ fn read_resource(
240
+ &self,
241
+ request: ReadResourceRequestParams,
242
+ _context: rmcp::service::RequestContext<RoleServer>,
243
+ ) -> impl std::future::Future<Output = Result<ReadResourceResult, McpError>> + Send + '_ {
244
+ async move {
245
+ let uri = request.uri.as_str();
246
+ if uri == "mdfs://tree" || uri == "markdownfs://tree" {
247
+ let tree = self.db.tree(None, None).await
248
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
249
+ Ok(ReadResourceResult::new(vec![ResourceContents::text(tree, uri)]))
250
+ } else if let Some(path) = uri
251
+ .strip_prefix("mdfs://files/")
252
+ .or_else(|| uri.strip_prefix("markdownfs://files/"))
253
+ {
254
+ let content = self.db.cat(path).await
255
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
256
+ Ok(ReadResourceResult::new(vec![ResourceContents::text(
257
+ String::from_utf8_lossy(&content).into_owned(), uri,
258
+ )]))
259
+ } else {
260
+ Err(McpError::invalid_params(format!("unknown resource: {uri}"), None))
261
+ }
262
+ }
263
+ }
264
+ }
265
+
266
+ #[tokio::main]
267
+ async fn main() {
268
+ tracing_subscriber::fmt()
269
+ .with_env_filter(
270
+ tracing_subscriber::EnvFilter::try_from_default_env()
271
+ .unwrap_or_else(|_| "markdownfs=info".parse().unwrap()),
272
+ )
273
+ .with_writer(std::io::stderr)
274
+ .init();
275
+
276
+ let config = Config::from_env();
277
+ tracing::info!(data_dir = %config.data_dir.display(), "starting mdfs MCP server");
278
+
279
+ let db = MarkdownDb::open(config).expect("failed to open database");
280
+ let _save_handle = db.spawn_auto_save();
281
+
282
+ let server = McpServer { db };
283
+ let transport = rmcp::transport::io::stdio();
284
+ let service = server.serve(transport).await.expect("failed to start MCP server");
285
+ service.waiting().await.expect("MCP server error");
286
+ }
src/bin/mdfs_mount.rs ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![cfg(feature = "fuser")]
2
+
3
+ use clap::Parser;
4
+ use markdownfs::config::{CompatibilityTarget, Config};
5
+ use markdownfs::db::MarkdownDb;
6
+ use markdownfs::fuse_mount;
7
+ use std::path::PathBuf;
8
+ use std::sync::{Arc, Mutex};
9
+
10
+ #[derive(Parser)]
11
+ #[command(name = "mdfs-mount", version, about = "Mount mdfs through FUSE")]
12
+ struct Cli {
13
+ #[arg(long, env = "MARKDOWNFS_MOUNTPOINT")]
14
+ mountpoint: PathBuf,
15
+
16
+ #[arg(long)]
17
+ read_only: bool,
18
+ }
19
+
20
+ fn main() {
21
+ let cli = Cli::parse();
22
+ let config = Config::from_env().with_compatibility_target(CompatibilityTarget::Posix);
23
+ let db = match MarkdownDb::open(config) {
24
+ Ok(db) => db,
25
+ Err(err) => {
26
+ eprintln!("failed to open database: {err}");
27
+ std::process::exit(1);
28
+ }
29
+ };
30
+ let fs = Arc::new(Mutex::new(db.snapshot_fs()));
31
+ if let Err(err) = fuse_mount::mount(fs, cli.mountpoint, cli.read_only) {
32
+ eprintln!("failed to mount filesystem: {err}");
33
+ std::process::exit(1);
34
+ }
35
+ }
src/bin/mdfs_server.rs ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use markdownfs::config::Config;
2
+ use markdownfs::db::MarkdownDb;
3
+ use markdownfs::server;
4
+
5
+ #[tokio::main]
6
+ async fn main() {
7
+ tracing_subscriber::fmt()
8
+ .with_env_filter(
9
+ tracing_subscriber::EnvFilter::try_from_default_env()
10
+ .unwrap_or_else(|_| "markdownfs=info,tower_http=info".parse().unwrap()),
11
+ )
12
+ .init();
13
+
14
+ let config = Config::from_env();
15
+ let listen_addr = config.listen_addr.clone();
16
+
17
+ tracing::info!(data_dir = %config.data_dir.display(), "starting mdfs server");
18
+
19
+ let db = MarkdownDb::open(config).expect("failed to open database");
20
+
21
+ let save_handle = db.spawn_auto_save();
22
+
23
+ let app = server::build_router(db.clone());
24
+
25
+ let listener = tokio::net::TcpListener::bind(&listen_addr)
26
+ .await
27
+ .unwrap_or_else(|e| panic!("failed to bind {listen_addr}: {e}"));
28
+
29
+ tracing::info!("listening on {listen_addr}");
30
+ tracing::info!("endpoints:");
31
+ tracing::info!(" GET /health — health check");
32
+ tracing::info!(" POST /auth/login — login (JSON: {{\"username\": \"...\" }})");
33
+ tracing::info!(" GET /workspaces — list hosted workspaces");
34
+ tracing::info!(" POST /workspaces — create hosted workspace");
35
+ tracing::info!(" POST /workspaces/{{id}}/tokens — issue workspace-scoped token");
36
+ tracing::info!(" GET /fs/{{path}} — read file or list directory");
37
+ tracing::info!(" PUT /fs/{{path}} — write file or create directory");
38
+ tracing::info!(" DELETE /fs/{{path}} — delete file or directory");
39
+ tracing::info!(" POST /fs/{{path}} — copy/move (op=copy|move&dst=...)");
40
+ tracing::info!(" GET /search/grep — grep (pattern=...&path=...&recursive=true)");
41
+ tracing::info!(" GET /search/find — find (path=...&name=...)");
42
+ tracing::info!(" GET /tree/{{path}} — directory tree");
43
+ tracing::info!(" POST /vcs/commit — commit (JSON: {{\"message\": \"...\" }})");
44
+ tracing::info!(" GET /vcs/log — commit history");
45
+ tracing::info!(" POST /vcs/revert — revert (JSON: {{\"hash\": \"...\" }})");
46
+ tracing::info!(" GET /vcs/status — VCS status");
47
+
48
+ let shutdown = async {
49
+ tokio::signal::ctrl_c().await.ok();
50
+ tracing::info!("shutting down...");
51
+ };
52
+
53
+ axum::serve(listener, app)
54
+ .with_graceful_shutdown(shutdown)
55
+ .await
56
+ .expect("server error");
57
+
58
+ save_handle.abort();
59
+
60
+ if let Err(e) = db.save().await {
61
+ tracing::error!("failed to save on shutdown: {e}");
62
+ } else {
63
+ tracing::info!("state saved");
64
+ }
65
+ }
src/cmd/mod.rs ADDED
@@ -0,0 +1,1152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pub mod parser;
2
+
3
+ use crate::auth::perms::{has_sticky_bit, Access};
4
+ use crate::auth::session::Session;
5
+ use crate::auth::{ROOT_GID, ROOT_UID, WHEEL_GID};
6
+ use crate::error::VfsError;
7
+ use crate::fs::VirtualFs;
8
+ use parser::{ParsedCommand, Pipeline};
9
+
10
+ pub fn execute_pipeline(
11
+ pipeline: &Pipeline,
12
+ fs: &mut VirtualFs,
13
+ session: &mut Session,
14
+ ) -> Result<String, VfsError> {
15
+ let mut stdin = String::new();
16
+ for (i, cmd) in pipeline.commands.iter().enumerate() {
17
+ let is_last = i == pipeline.commands.len() - 1;
18
+ let has_stdin = i > 0;
19
+ stdin = execute_command(cmd, fs, session, if has_stdin { Some(&stdin) } else { None })?;
20
+ if !is_last && stdin.is_empty() {
21
+ break;
22
+ }
23
+ }
24
+ Ok(stdin)
25
+ }
26
+
27
+ fn execute_command(
28
+ cmd: &ParsedCommand,
29
+ fs: &mut VirtualFs,
30
+ session: &mut Session,
31
+ stdin: Option<&str>,
32
+ ) -> Result<String, VfsError> {
33
+ match cmd.program.as_str() {
34
+ "ls" => cmd_ls(fs, &cmd.args, session),
35
+ "cd" => cmd_cd(fs, &cmd.args, session),
36
+ "pwd" => Ok(format!("{}\n", fs.pwd())),
37
+ "mkdir" => cmd_mkdir(fs, &cmd.args, session),
38
+ "touch" => cmd_touch(fs, &cmd.args, session),
39
+ "cat" => cmd_cat(fs, &cmd.args, stdin, session),
40
+ "rm" => cmd_rm(fs, &cmd.args, session),
41
+ "rmdir" => cmd_rmdir(fs, &cmd.args, session),
42
+ "mv" => cmd_mv(fs, &cmd.args, session),
43
+ "cp" => cmd_cp(fs, &cmd.args, session),
44
+ "stat" => cmd_stat(fs, &cmd.args, session),
45
+ "tree" => cmd_tree(fs, &cmd.args, session),
46
+ "find" => cmd_find(fs, &cmd.args, session),
47
+ "grep" => cmd_grep(fs, &cmd.args, stdin, session),
48
+ "head" => cmd_head(&cmd.args, stdin),
49
+ "tail" => cmd_tail(&cmd.args, stdin),
50
+ "wc" => cmd_wc(&cmd.args, stdin),
51
+ "chmod" => cmd_chmod(fs, &cmd.args, session),
52
+ "chown" => cmd_chown(fs, &cmd.args, session),
53
+ "ln" => cmd_ln(fs, &cmd.args, session),
54
+ "echo" => cmd_echo(&cmd.args),
55
+ "write" => cmd_write(fs, &cmd.args, stdin, session),
56
+ // User management
57
+ "adduser" => cmd_adduser(fs, &cmd.args, session),
58
+ "addagent" => cmd_addagent(fs, &cmd.args, session),
59
+ "deluser" => cmd_deluser(fs, &cmd.args, session),
60
+ "addgroup" => cmd_addgroup(fs, &cmd.args, session),
61
+ "delgroup" => cmd_delgroup(fs, &cmd.args, session),
62
+ "usermod" => cmd_usermod(fs, &cmd.args, session),
63
+ "groups" => cmd_groups(fs, &cmd.args, session),
64
+ "whoami" => Ok(format!("{}\n", session.username)),
65
+ "id" => cmd_id(fs, &cmd.args, session),
66
+ "su" => cmd_su(fs, &cmd.args, session),
67
+ "delegate" => cmd_delegate(fs, &cmd.args, session),
68
+ "undelegate" => cmd_undelegate(session),
69
+ "help" => cmd_help(),
70
+ "clear" => Ok("\x1b[2J\x1b[H".to_string()),
71
+ name => Err(VfsError::UnknownCommand {
72
+ name: name.to_string(),
73
+ }),
74
+ }
75
+ }
76
+
77
+ // ───── Permission helpers ─────
78
+
79
+ /// Check that the session has the given access on an inode.
80
+ /// Respects delegation: both principal and delegate must have access.
81
+ fn require_access(
82
+ fs: &VirtualFs,
83
+ inode_id: u64,
84
+ session: &Session,
85
+ access: Access,
86
+ path: &str,
87
+ ) -> Result<(), VfsError> {
88
+ let inode = fs.get_inode(inode_id)?;
89
+ if !session.has_permission(inode, access) {
90
+ return Err(VfsError::PermissionDenied {
91
+ path: path.to_string(),
92
+ });
93
+ }
94
+ Ok(())
95
+ }
96
+
97
+ /// Require admin (root or wheel) — respects delegation intersection.
98
+ /// Both the principal and delegate must be admin.
99
+ fn require_admin(session: &Session) -> Result<(), VfsError> {
100
+ let principal_admin =
101
+ session.uid == ROOT_UID || session.groups.contains(&WHEEL_GID);
102
+ if !principal_admin {
103
+ return Err(VfsError::PermissionDenied {
104
+ path: "admin operation".to_string(),
105
+ });
106
+ }
107
+ if let Some(ref delegate) = session.delegate {
108
+ let delegate_admin =
109
+ delegate.uid == ROOT_UID || delegate.groups.contains(&WHEEL_GID);
110
+ if !delegate_admin {
111
+ return Err(VfsError::PermissionDenied {
112
+ path: "admin operation (delegate lacks admin)".to_string(),
113
+ });
114
+ }
115
+ }
116
+ Ok(())
117
+ }
118
+
119
+ // ───── File commands ─────
120
+
121
+ fn cmd_ls(fs: &VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
122
+ let mut long_format = false;
123
+ let mut all = false;
124
+ let mut path = None;
125
+
126
+ for arg in args {
127
+ match arg.as_str() {
128
+ "-l" => long_format = true,
129
+ "-a" => all = true,
130
+ "-la" | "-al" => {
131
+ long_format = true;
132
+ all = true;
133
+ }
134
+ p => path = Some(p),
135
+ }
136
+ }
137
+
138
+ let _ = all;
139
+
140
+ // Permission: Read + Execute on the directory
141
+ let dir_path = path.unwrap_or(".");
142
+ let dir_id = fs.resolve_path_checked(dir_path, session)?;
143
+ require_access(fs, dir_id, session, Access::Read, dir_path)?;
144
+ require_access(fs, dir_id, session, Access::Execute, dir_path)?;
145
+
146
+ let all_entries = fs.ls(path)?;
147
+ // Filter: only show entries the user can read — respects delegation intersection
148
+ let entries: Vec<_> = all_entries
149
+ .into_iter()
150
+ .filter(|e| session.has_permission_bits(e.mode, e.uid, e.gid, Access::Read))
151
+ .collect();
152
+
153
+ let mut output = String::new();
154
+
155
+ if long_format {
156
+ for e in &entries {
157
+ let kind = if e.is_dir {
158
+ 'd'
159
+ } else if e.is_symlink {
160
+ 'l'
161
+ } else {
162
+ '-'
163
+ };
164
+ let perms = format_permissions(e.mode);
165
+ let time = format_time(e.modified);
166
+ let owner = fs.registry.user_name(e.uid).unwrap_or("?");
167
+ let group = fs.registry.group_name(e.gid).unwrap_or("?");
168
+ output.push_str(&format!(
169
+ "{kind}{perms} {owner:<8} {group:<8} {:>8} {time} {}{}\n",
170
+ e.size,
171
+ e.name,
172
+ if e.is_dir { "/" } else { "" }
173
+ ));
174
+ }
175
+ } else {
176
+ for e in &entries {
177
+ output.push_str(&e.name);
178
+ if e.is_dir {
179
+ output.push('/');
180
+ }
181
+ output.push('\n');
182
+ }
183
+ }
184
+
185
+ Ok(output)
186
+ }
187
+
188
+ fn cmd_cd(fs: &mut VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
189
+ let path = args.first().map(|s| s.as_str()).unwrap_or("/");
190
+ // Permission: Execute on target directory
191
+ let target = fs.resolve_path_checked(path, session)?;
192
+ require_access(fs, target, session, Access::Execute, path)?;
193
+ fs.cd(path)?;
194
+ Ok(String::new())
195
+ }
196
+
197
+ fn cmd_mkdir(fs: &mut VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
198
+ let mut parents = false;
199
+ let mut paths = Vec::new();
200
+
201
+ for arg in args {
202
+ if arg == "-p" {
203
+ parents = true;
204
+ } else {
205
+ paths.push(arg.as_str());
206
+ }
207
+ }
208
+
209
+ if paths.is_empty() {
210
+ return Err(VfsError::InvalidArgs {
211
+ message: "mkdir: missing operand".to_string(),
212
+ });
213
+ }
214
+
215
+ for path in paths {
216
+ if parents {
217
+ // mkdir -p: intermediate dirs may not exist yet, so we can't resolve parent.
218
+ // Permission check happens inside mkdir_p for each existing parent.
219
+ fs.mkdir_p(path, session.effective_uid(), session.effective_gid())?;
220
+ } else {
221
+ // Permission: Write + Execute on parent
222
+ let (parent_id, _) = fs.resolve_parent_checked(path, session)?;
223
+ require_access(fs, parent_id, session, Access::Write, path)?;
224
+ require_access(fs, parent_id, session, Access::Execute, path)?;
225
+ fs.mkdir(path, session.effective_uid(), session.effective_gid())?;
226
+ }
227
+ }
228
+ Ok(String::new())
229
+ }
230
+
231
+ fn cmd_touch(fs: &mut VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
232
+ if args.is_empty() {
233
+ return Err(VfsError::InvalidArgs {
234
+ message: "touch: missing operand".to_string(),
235
+ });
236
+ }
237
+ for arg in args {
238
+ if fs.resolve_path(arg).is_ok() {
239
+ // File exists — update timestamp, need Write on file
240
+ let id = fs.resolve_path_checked(arg, session)?;
241
+ require_access(fs, id, session, Access::Write, arg)?;
242
+ fs.touch(arg, session.effective_uid(), session.effective_gid())?;
243
+ } else {
244
+ // New file — need Write + Execute on parent
245
+ let (parent_id, _) = fs.resolve_parent_checked(arg, session)?;
246
+ require_access(fs, parent_id, session, Access::Write, arg)?;
247
+ require_access(fs, parent_id, session, Access::Execute, arg)?;
248
+ fs.touch(arg, session.effective_uid(), session.effective_gid())?;
249
+ }
250
+ }
251
+ Ok(String::new())
252
+ }
253
+
254
+ fn cmd_cat(
255
+ fs: &VirtualFs,
256
+ args: &[String],
257
+ stdin: Option<&str>,
258
+ session: &Session,
259
+ ) -> Result<String, VfsError> {
260
+ if let Some(input) = stdin {
261
+ if args.is_empty() {
262
+ return Ok(input.to_string());
263
+ }
264
+ }
265
+
266
+ if args.is_empty() {
267
+ return Err(VfsError::InvalidArgs {
268
+ message: "cat: missing operand".to_string(),
269
+ });
270
+ }
271
+
272
+ let mut output = String::new();
273
+ for path in args {
274
+ // Permission: Read on file
275
+ let id = fs.resolve_path_checked(path, session)?;
276
+ require_access(fs, id, session, Access::Read, path)?;
277
+ let content = fs.cat(path)?;
278
+ output.push_str(&String::from_utf8_lossy(content));
279
+ }
280
+ Ok(output)
281
+ }
282
+
283
+ fn cmd_rm(fs: &mut VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
284
+ let mut recursive = false;
285
+ let mut paths = Vec::new();
286
+
287
+ for arg in args {
288
+ match arg.as_str() {
289
+ "-r" | "-rf" | "-fr" => recursive = true,
290
+ p => paths.push(p),
291
+ }
292
+ }
293
+
294
+ if paths.is_empty() {
295
+ return Err(VfsError::InvalidArgs {
296
+ message: "rm: missing operand".to_string(),
297
+ });
298
+ }
299
+
300
+ for path in paths {
301
+ // Permission: Write + Execute on parent
302
+ let (parent_id, _) = fs.resolve_parent_checked(path, session)?;
303
+ require_access(fs, parent_id, session, Access::Write, path)?;
304
+ require_access(fs, parent_id, session, Access::Execute, path)?;
305
+
306
+ // Sticky bit check: only owner of file, owner of dir, or root can delete
307
+ // With delegation: use effective identity
308
+ let parent = fs.get_inode(parent_id)?;
309
+ if has_sticky_bit(parent.mode) && !session.is_effectively_root() {
310
+ let file_id = fs.resolve_path(path)?;
311
+ let file_inode = fs.get_inode(file_id)?;
312
+ let eff_uid = session.effective_uid();
313
+ if file_inode.uid != eff_uid && parent.uid != eff_uid {
314
+ return Err(VfsError::PermissionDenied {
315
+ path: path.to_string(),
316
+ });
317
+ }
318
+ }
319
+
320
+ if recursive {
321
+ fs.rm_rf(path)?;
322
+ } else {
323
+ fs.rm(path)?;
324
+ }
325
+ }
326
+ Ok(String::new())
327
+ }
328
+
329
+ fn cmd_rmdir(fs: &mut VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
330
+ if args.is_empty() {
331
+ return Err(VfsError::InvalidArgs {
332
+ message: "rmdir: missing operand".to_string(),
333
+ });
334
+ }
335
+ for path in args {
336
+ let (parent_id, _) = fs.resolve_parent_checked(path, session)?;
337
+ require_access(fs, parent_id, session, Access::Write, path)?;
338
+ require_access(fs, parent_id, session, Access::Execute, path)?;
339
+ fs.rmdir(path)?;
340
+ }
341
+ Ok(String::new())
342
+ }
343
+
344
+ fn cmd_mv(fs: &mut VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
345
+ if args.len() < 2 {
346
+ return Err(VfsError::InvalidArgs {
347
+ message: "mv: need source and destination".to_string(),
348
+ });
349
+ }
350
+
351
+ // Permission: W+X on source parent, W+X on dest parent
352
+ let (src_parent, _) = fs.resolve_parent_checked(&args[0], session)?;
353
+ require_access(fs, src_parent, session, Access::Write, &args[0])?;
354
+ require_access(fs, src_parent, session, Access::Execute, &args[0])?;
355
+
356
+ // Sticky bit on source parent — use effective identity for delegation
357
+ let src_parent_inode = fs.get_inode(src_parent)?;
358
+ if has_sticky_bit(src_parent_inode.mode) && !session.is_effectively_root() {
359
+ let src_id = fs.resolve_path(&args[0])?;
360
+ let src_inode = fs.get_inode(src_id)?;
361
+ let eff_uid = session.effective_uid();
362
+ if src_inode.uid != eff_uid && src_parent_inode.uid != eff_uid {
363
+ return Err(VfsError::PermissionDenied {
364
+ path: args[0].to_string(),
365
+ });
366
+ }
367
+ }
368
+
369
+ // Check destination parent
370
+ if let Ok((dst_parent, _)) = fs.resolve_parent_checked(&args[1], session) {
371
+ require_access(fs, dst_parent, session, Access::Write, &args[1])?;
372
+ require_access(fs, dst_parent, session, Access::Execute, &args[1])?;
373
+ }
374
+
375
+ fs.mv(&args[0], &args[1])?;
376
+ Ok(String::new())
377
+ }
378
+
379
+ fn cmd_cp(fs: &mut VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
380
+ if args.len() < 2 {
381
+ return Err(VfsError::InvalidArgs {
382
+ message: "cp: need source and destination".to_string(),
383
+ });
384
+ }
385
+
386
+ // Permission: Read on source
387
+ let src_id = fs.resolve_path_checked(&args[0], session)?;
388
+ require_access(fs, src_id, session, Access::Read, &args[0])?;
389
+
390
+ // Permission: Write + Execute on destination parent
391
+ if let Ok((dst_parent, _)) = fs.resolve_parent_checked(&args[1], session) {
392
+ require_access(fs, dst_parent, session, Access::Write, &args[1])?;
393
+ require_access(fs, dst_parent, session, Access::Execute, &args[1])?;
394
+ }
395
+
396
+ fs.cp(&args[0], &args[1], session.effective_uid(), session.effective_gid())?;
397
+ Ok(String::new())
398
+ }
399
+
400
+ fn cmd_stat(fs: &VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
401
+ if args.is_empty() {
402
+ return Err(VfsError::InvalidArgs {
403
+ message: "stat: missing operand".to_string(),
404
+ });
405
+ }
406
+ let _id = fs.resolve_path_checked(&args[0], session)?;
407
+ let info = fs.stat(&args[0])?;
408
+ let owner = fs.registry.user_name(info.uid).unwrap_or("?");
409
+ let group = fs.registry.group_name(info.gid).unwrap_or("?");
410
+ Ok(format!(
411
+ " File: {}\n Size: {}\n Blocks: {}\n IO Block: {}\n Type: {}\n Inode: {}\n Links: {}\n Mode: {:04o}\n Uid: {} ({})\n Gid: {} ({})\nCreated: {}.{}\nAccessed: {}.{}\nModified: {}.{}\n Changed: {}.{}\n",
412
+ args[0], info.size, info.blocks, info.block_size, info.kind, info.inode_id, info.nlink, info.mode,
413
+ info.uid, owner, info.gid, group,
414
+ format_time(info.created), info.created_nanos,
415
+ format_time(info.accessed), info.accessed_nanos,
416
+ format_time(info.modified), info.modified_nanos,
417
+ format_time(info.changed), info.changed_nanos,
418
+ ))
419
+ }
420
+
421
+ fn cmd_tree(fs: &VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
422
+ let path = args.first().map(|s| s.as_str());
423
+ if let Some(p) = path {
424
+ let id = fs.resolve_path_checked(p, session)?;
425
+ require_access(fs, id, session, Access::Read, p)?;
426
+ require_access(fs, id, session, Access::Execute, p)?;
427
+ }
428
+ fs.tree(path, "", Some(session))
429
+ }
430
+
431
+ fn cmd_find(fs: &VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
432
+ let mut path = None;
433
+ let mut pattern = None;
434
+ let mut i = 0;
435
+
436
+ while i < args.len() {
437
+ match args[i].as_str() {
438
+ "-name" => {
439
+ i += 1;
440
+ if i < args.len() {
441
+ pattern = Some(args[i].as_str());
442
+ }
443
+ }
444
+ p => {
445
+ if path.is_none() {
446
+ path = Some(p);
447
+ }
448
+ }
449
+ }
450
+ i += 1;
451
+ }
452
+
453
+ if let Some(p) = path {
454
+ let id = fs.resolve_path_checked(p, session)?;
455
+ require_access(fs, id, session, Access::Read, p)?;
456
+ require_access(fs, id, session, Access::Execute, p)?;
457
+ }
458
+
459
+ let results = fs.find(path, pattern, Some(session))?;
460
+ Ok(results.join("\n") + if results.is_empty() { "" } else { "\n" })
461
+ }
462
+
463
+ fn cmd_grep(
464
+ fs: &VirtualFs,
465
+ args: &[String],
466
+ stdin: Option<&str>,
467
+ session: &Session,
468
+ ) -> Result<String, VfsError> {
469
+ if let Some(input) = stdin {
470
+ if args.is_empty() {
471
+ return Err(VfsError::InvalidArgs {
472
+ message: "grep: missing pattern".to_string(),
473
+ });
474
+ }
475
+ let re = regex::Regex::new(&args[0]).map_err(|e| VfsError::InvalidArgs {
476
+ message: format!("invalid regex: {e}"),
477
+ })?;
478
+ let mut output = String::new();
479
+ for line in input.lines() {
480
+ if re.is_match(line) {
481
+ output.push_str(line);
482
+ output.push('\n');
483
+ }
484
+ }
485
+ return Ok(output);
486
+ }
487
+
488
+ let mut recursive = false;
489
+ let mut pattern = None;
490
+ let mut path = None;
491
+
492
+ for arg in args {
493
+ match arg.as_str() {
494
+ "-r" | "-R" => recursive = true,
495
+ _ => {
496
+ if pattern.is_none() {
497
+ pattern = Some(arg.as_str());
498
+ } else if path.is_none() {
499
+ path = Some(arg.as_str());
500
+ }
501
+ }
502
+ }
503
+ }
504
+
505
+ let pattern = pattern.ok_or_else(|| VfsError::InvalidArgs {
506
+ message: "grep: missing pattern".to_string(),
507
+ })?;
508
+
509
+ // Permission: Read on file/dir
510
+ if let Some(p) = path {
511
+ let id = fs.resolve_path_checked(p, session)?;
512
+ require_access(fs, id, session, Access::Read, p)?;
513
+ }
514
+
515
+ let results = fs.grep(pattern, path, recursive, Some(session))?;
516
+ let mut output = String::new();
517
+ for r in &results {
518
+ output.push_str(&format!("{}:{}:{}\n", r.file, r.line_num, r.line));
519
+ }
520
+ Ok(output)
521
+ }
522
+
523
+ fn cmd_head(args: &[String], stdin: Option<&str>) -> Result<String, VfsError> {
524
+ let input = stdin.ok_or_else(|| VfsError::InvalidArgs {
525
+ message: "head: no input".to_string(),
526
+ })?;
527
+
528
+ let mut n = 10usize;
529
+ for i in 0..args.len() {
530
+ if args[i] == "-n" || args[i].starts_with('-') {
531
+ if args[i] == "-n" && i + 1 < args.len() {
532
+ n = args[i + 1].parse().unwrap_or(10);
533
+ } else if args[i].starts_with('-') {
534
+ n = args[i][1..].parse().unwrap_or(10);
535
+ }
536
+ }
537
+ }
538
+
539
+ let lines: Vec<&str> = input.lines().take(n).collect();
540
+ Ok(lines.join("\n") + "\n")
541
+ }
542
+
543
+ fn cmd_tail(args: &[String], stdin: Option<&str>) -> Result<String, VfsError> {
544
+ let input = stdin.ok_or_else(|| VfsError::InvalidArgs {
545
+ message: "tail: no input".to_string(),
546
+ })?;
547
+
548
+ let mut n = 10usize;
549
+ for i in 0..args.len() {
550
+ if args[i] == "-n" || args[i].starts_with('-') {
551
+ if args[i] == "-n" && i + 1 < args.len() {
552
+ n = args[i + 1].parse().unwrap_or(10);
553
+ } else if args[i].starts_with('-') {
554
+ n = args[i][1..].parse().unwrap_or(10);
555
+ }
556
+ }
557
+ }
558
+
559
+ let all_lines: Vec<&str> = input.lines().collect();
560
+ let start = all_lines.len().saturating_sub(n);
561
+ let lines = &all_lines[start..];
562
+ Ok(lines.join("\n") + "\n")
563
+ }
564
+
565
+ fn cmd_wc(args: &[String], stdin: Option<&str>) -> Result<String, VfsError> {
566
+ let input = stdin.ok_or_else(|| VfsError::InvalidArgs {
567
+ message: "wc: no input".to_string(),
568
+ })?;
569
+
570
+ let lines = input.lines().count();
571
+ let words = input.split_whitespace().count();
572
+ let bytes = input.len();
573
+
574
+ let count_lines = args.contains(&"-l".to_string());
575
+ let count_words = args.contains(&"-w".to_string());
576
+ let count_bytes = args.contains(&"-c".to_string());
577
+
578
+ if count_lines {
579
+ Ok(format!("{lines}\n"))
580
+ } else if count_words {
581
+ Ok(format!("{words}\n"))
582
+ } else if count_bytes {
583
+ Ok(format!("{bytes}\n"))
584
+ } else {
585
+ Ok(format!("{lines} {words} {bytes}\n"))
586
+ }
587
+ }
588
+
589
+ fn cmd_chmod(fs: &mut VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
590
+ if args.len() < 2 {
591
+ return Err(VfsError::InvalidArgs {
592
+ message: "chmod: need mode and file".to_string(),
593
+ });
594
+ }
595
+ let mode = u16::from_str_radix(&args[0], 8).map_err(|_| VfsError::InvalidArgs {
596
+ message: format!("chmod: invalid mode: {}", args[0]),
597
+ })?;
598
+
599
+ // Permission: must be owner or root (delegation: both must qualify)
600
+ let id = fs.resolve_path_checked(&args[1], session)?;
601
+ let inode = fs.get_inode(id)?;
602
+ if !session.is_effective_owner(inode.uid) {
603
+ return Err(VfsError::PermissionDenied {
604
+ path: args[1].to_string(),
605
+ });
606
+ }
607
+
608
+ fs.chmod(&args[1], mode)?;
609
+ Ok(String::new())
610
+ }
611
+
612
+ fn cmd_chown(fs: &mut VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
613
+ if args.len() < 2 {
614
+ return Err(VfsError::InvalidArgs {
615
+ message: "chown: need owner[:group] and file".to_string(),
616
+ });
617
+ }
618
+
619
+ let spec = &args[0];
620
+ let path = &args[1];
621
+
622
+ let (user_str, group_str) = if let Some(pos) = spec.find(':') {
623
+ (Some(&spec[..pos]), Some(&spec[pos + 1..]))
624
+ } else {
625
+ (Some(spec.as_str()), None)
626
+ };
627
+
628
+ let id = fs.resolve_path_checked(path, session)?;
629
+ let inode = fs.get_inode(id)?;
630
+
631
+ // Changing uid: root only (delegation: must be effectively root)
632
+ // Changing gid: root or owner (if member of target group)
633
+ if let Some(user) = user_str {
634
+ if !user.is_empty() {
635
+ if !session.is_effectively_root() {
636
+ return Err(VfsError::PermissionDenied {
637
+ path: path.to_string(),
638
+ });
639
+ }
640
+ let new_uid = fs.registry.lookup_uid(user).ok_or_else(|| VfsError::AuthError {
641
+ message: format!("no such user: {user}"),
642
+ })?;
643
+ let current_gid = inode.gid;
644
+ fs.chown(path, new_uid, current_gid)?;
645
+ }
646
+ }
647
+
648
+ if let Some(group) = group_str {
649
+ if !group.is_empty() {
650
+ let new_gid = fs.registry.lookup_gid(group).ok_or_else(|| VfsError::AuthError {
651
+ message: format!("no such group: {group}"),
652
+ })?;
653
+ // Owner can change group if they're a member of the target group
654
+ // Delegation: effective identity must be owner and in target group
655
+ let inode = fs.get_inode(fs.resolve_path(path)?)?;
656
+ if !session.is_effectively_root() {
657
+ if !session.is_effective_owner(inode.uid) {
658
+ return Err(VfsError::PermissionDenied {
659
+ path: path.to_string(),
660
+ });
661
+ }
662
+ // Both principal and delegate must be in target group
663
+ if !session.groups.contains(&new_gid) {
664
+ return Err(VfsError::PermissionDenied {
665
+ path: path.to_string(),
666
+ });
667
+ }
668
+ if let Some(ref delegate) = session.delegate {
669
+ if !delegate.groups.contains(&new_gid) {
670
+ return Err(VfsError::PermissionDenied {
671
+ path: path.to_string(),
672
+ });
673
+ }
674
+ }
675
+ }
676
+ fs.chown(path, inode.uid, new_gid)?;
677
+ }
678
+ }
679
+
680
+ Ok(String::new())
681
+ }
682
+
683
+ fn cmd_ln(fs: &mut VirtualFs, args: &[String], session: &Session) -> Result<String, VfsError> {
684
+ let mut symlink = false;
685
+ let mut targets = Vec::new();
686
+
687
+ for arg in args {
688
+ if arg == "-s" {
689
+ symlink = true;
690
+ } else {
691
+ targets.push(arg.as_str());
692
+ }
693
+ }
694
+
695
+ if targets.len() < 2 {
696
+ return Err(VfsError::InvalidArgs {
697
+ message: "ln: need target and link name".to_string(),
698
+ });
699
+ }
700
+
701
+ // Permission: Write + Execute on link's parent
702
+ let (parent_id, _) = fs.resolve_parent_checked(targets[1], session)?;
703
+ require_access(fs, parent_id, session, Access::Write, targets[1])?;
704
+ require_access(fs, parent_id, session, Access::Execute, targets[1])?;
705
+
706
+ if symlink {
707
+ fs.ln_s(targets[0], targets[1], session.effective_uid(), session.effective_gid())?;
708
+ } else {
709
+ let target_id = fs.resolve_path_checked(targets[0], session)?;
710
+ require_access(fs, target_id, session, Access::Read, targets[0])?;
711
+ fs.link(targets[0], targets[1])?;
712
+ }
713
+ Ok(String::new())
714
+ }
715
+
716
+ fn cmd_echo(args: &[String]) -> Result<String, VfsError> {
717
+ Ok(args.join(" ") + "\n")
718
+ }
719
+
720
+ fn cmd_write(
721
+ fs: &mut VirtualFs,
722
+ args: &[String],
723
+ stdin: Option<&str>,
724
+ session: &Session,
725
+ ) -> Result<String, VfsError> {
726
+ if args.is_empty() {
727
+ return Err(VfsError::InvalidArgs {
728
+ message: "write: need file path".to_string(),
729
+ });
730
+ }
731
+
732
+ let content = if let Some(input) = stdin {
733
+ input.to_string()
734
+ } else if args.len() > 1 {
735
+ args[1..].join(" ")
736
+ } else {
737
+ return Err(VfsError::InvalidArgs {
738
+ message: "write: need content (pipe input or provide as args)".to_string(),
739
+ });
740
+ };
741
+
742
+ // Create file if it doesn't exist
743
+ if fs.resolve_path(&args[0]).is_err() {
744
+ let (parent_id, _) = fs.resolve_parent_checked(&args[0], session)?;
745
+ require_access(fs, parent_id, session, Access::Write, &args[0])?;
746
+ fs.touch(&args[0], session.effective_uid(), session.effective_gid())?;
747
+ } else {
748
+ // File exists — need Write on file
749
+ let id = fs.resolve_path_checked(&args[0], session)?;
750
+ require_access(fs, id, session, Access::Write, &args[0])?;
751
+ }
752
+ fs.write_file(&args[0], content.into_bytes())?;
753
+ Ok(String::new())
754
+ }
755
+
756
+ // ───── User management commands ─────
757
+
758
+ fn cmd_adduser(
759
+ fs: &mut VirtualFs,
760
+ args: &[String],
761
+ _session: &Session,
762
+ ) -> Result<String, VfsError> {
763
+ require_admin(_session)?;
764
+ if args.is_empty() {
765
+ return Err(VfsError::InvalidArgs {
766
+ message: "adduser: missing username".to_string(),
767
+ });
768
+ }
769
+ let name = &args[0];
770
+ let (uid, _) = fs.registry.add_user(name, false)?;
771
+ let gid = fs.registry.get_user(uid).map(|u| u.groups.first().copied().unwrap_or(0)).unwrap_or(0);
772
+
773
+ let mut output = format!("User '{name}' created (uid={uid})\n");
774
+
775
+ let _ = fs.mkdir_p("/home", ROOT_UID, ROOT_GID);
776
+ let home_path = format!("/home/{name}");
777
+ if fs.mkdir(&home_path, uid, gid).is_ok() {
778
+ output.push_str(&format!("Home directory: /home/{name}\n"));
779
+ }
780
+
781
+ Ok(output)
782
+ }
783
+
784
+ fn cmd_addagent(
785
+ fs: &mut VirtualFs,
786
+ args: &[String],
787
+ _session: &Session,
788
+ ) -> Result<String, VfsError> {
789
+ require_admin(_session)?;
790
+ if args.is_empty() {
791
+ return Err(VfsError::InvalidArgs {
792
+ message: "addagent: missing agent name".to_string(),
793
+ });
794
+ }
795
+ let (uid, raw_token) = fs.registry.add_user(&args[0], true)?;
796
+ let token = raw_token.unwrap();
797
+ Ok(format!(
798
+ "Agent '{}' created (uid={uid})\nAPI token (save this — shown only once):\n {token}\n",
799
+ args[0]
800
+ ))
801
+ }
802
+
803
+ fn cmd_deluser(
804
+ fs: &mut VirtualFs,
805
+ args: &[String],
806
+ _session: &Session,
807
+ ) -> Result<String, VfsError> {
808
+ if !_session.is_effectively_root() {
809
+ return Err(VfsError::PermissionDenied {
810
+ path: "deluser: root only".to_string(),
811
+ });
812
+ }
813
+ if args.is_empty() {
814
+ return Err(VfsError::InvalidArgs {
815
+ message: "deluser: missing username".to_string(),
816
+ });
817
+ }
818
+ fs.registry.del_user(&args[0])?;
819
+ Ok(format!("User '{}' deleted\n", args[0]))
820
+ }
821
+
822
+ fn cmd_addgroup(
823
+ fs: &mut VirtualFs,
824
+ args: &[String],
825
+ _session: &Session,
826
+ ) -> Result<String, VfsError> {
827
+ require_admin(_session)?;
828
+ if args.is_empty() {
829
+ return Err(VfsError::InvalidArgs {
830
+ message: "addgroup: missing group name".to_string(),
831
+ });
832
+ }
833
+ let gid = fs.registry.add_group(&args[0])?;
834
+ Ok(format!("Group '{}' created (gid={gid})\n", args[0]))
835
+ }
836
+
837
+ fn cmd_delgroup(
838
+ fs: &mut VirtualFs,
839
+ args: &[String],
840
+ _session: &Session,
841
+ ) -> Result<String, VfsError> {
842
+ if !_session.is_effectively_root() {
843
+ return Err(VfsError::PermissionDenied {
844
+ path: "delgroup: root only".to_string(),
845
+ });
846
+ }
847
+ if args.is_empty() {
848
+ return Err(VfsError::InvalidArgs {
849
+ message: "delgroup: missing group name".to_string(),
850
+ });
851
+ }
852
+ fs.registry.del_group(&args[0])?;
853
+ Ok(format!("Group '{}' deleted\n", args[0]))
854
+ }
855
+
856
+ fn cmd_usermod(
857
+ fs: &mut VirtualFs,
858
+ args: &[String],
859
+ _session: &Session,
860
+ ) -> Result<String, VfsError> {
861
+ require_admin(_session)?;
862
+
863
+ // usermod -aG <group> <user> or usermod -rG <group> <user>
864
+ if args.len() < 3 {
865
+ return Err(VfsError::InvalidArgs {
866
+ message: "usermod: usage: usermod -aG <group> <user> | usermod -rG <group> <user>"
867
+ .to_string(),
868
+ });
869
+ }
870
+
871
+ match args[0].as_str() {
872
+ "-aG" => {
873
+ fs.registry.usermod_add_group(&args[2], &args[1])?;
874
+ Ok(format!("Added '{}' to group '{}'\n", args[2], args[1]))
875
+ }
876
+ "-rG" => {
877
+ fs.registry.usermod_remove_group(&args[2], &args[1])?;
878
+ Ok(format!(
879
+ "Removed '{}' from group '{}'\n",
880
+ args[2], args[1]
881
+ ))
882
+ }
883
+ _ => Err(VfsError::InvalidArgs {
884
+ message: "usermod: usage: usermod -aG <group> <user> | usermod -rG <group> <user>"
885
+ .to_string(),
886
+ }),
887
+ }
888
+ }
889
+
890
+ fn cmd_groups(
891
+ fs: &VirtualFs,
892
+ args: &[String],
893
+ session: &Session,
894
+ ) -> Result<String, VfsError> {
895
+ let username = if args.is_empty() {
896
+ &session.username
897
+ } else {
898
+ // Root, wheel members, or the user themselves can see others' groups
899
+ let is_admin =
900
+ session.uid == ROOT_UID || session.groups.contains(&WHEEL_GID);
901
+ if !is_admin && args[0] != session.username {
902
+ return Err(VfsError::PermissionDenied {
903
+ path: "groups".to_string(),
904
+ });
905
+ }
906
+ &args[0]
907
+ };
908
+
909
+ let uid = fs
910
+ .registry
911
+ .lookup_uid(username)
912
+ .ok_or_else(|| VfsError::AuthError {
913
+ message: format!("no such user: {username}"),
914
+ })?;
915
+ let user = fs.registry.get_user(uid).unwrap();
916
+
917
+ let group_names: Vec<&str> = user
918
+ .groups
919
+ .iter()
920
+ .filter_map(|&gid| fs.registry.group_name(gid))
921
+ .collect();
922
+ Ok(format!("{}\n", group_names.join(" ")))
923
+ }
924
+
925
+ fn cmd_id(
926
+ fs: &VirtualFs,
927
+ args: &[String],
928
+ session: &Session,
929
+ ) -> Result<String, VfsError> {
930
+ let username = if args.is_empty() {
931
+ &session.username
932
+ } else {
933
+ &args[0]
934
+ };
935
+
936
+ let uid = fs
937
+ .registry
938
+ .lookup_uid(username)
939
+ .ok_or_else(|| VfsError::AuthError {
940
+ message: format!("no such user: {username}"),
941
+ })?;
942
+ let user = fs.registry.get_user(uid).unwrap();
943
+
944
+ let primary_gid = user.groups.first().copied().unwrap_or(0);
945
+ let primary_group = fs.registry.group_name(primary_gid).unwrap_or("?");
946
+
947
+ let groups_str: Vec<String> = user
948
+ .groups
949
+ .iter()
950
+ .filter_map(|&gid| {
951
+ fs.registry
952
+ .group_name(gid)
953
+ .map(|name| format!("{gid}({name})"))
954
+ })
955
+ .collect();
956
+
957
+ Ok(format!(
958
+ "uid={uid}({}) gid={primary_gid}({primary_group}) groups={}\n",
959
+ user.name,
960
+ groups_str.join(",")
961
+ ))
962
+ }
963
+
964
+ fn cmd_su(
965
+ fs: &VirtualFs,
966
+ args: &[String],
967
+ session: &mut Session,
968
+ ) -> Result<String, VfsError> {
969
+ if args.is_empty() {
970
+ return Err(VfsError::InvalidArgs {
971
+ message: "su: missing username".to_string(),
972
+ });
973
+ }
974
+
975
+ let target = &args[0];
976
+
977
+ // Root can su to anyone; wheel members can su to anyone
978
+ // Delegation: the principal (not delegate) must be root or wheel
979
+ if session.uid != ROOT_UID && !session.groups.contains(&WHEEL_GID) {
980
+ return Err(VfsError::PermissionDenied {
981
+ path: format!("su: must be root or wheel member to switch user"),
982
+ });
983
+ }
984
+
985
+ let uid = fs
986
+ .registry
987
+ .lookup_uid(target)
988
+ .ok_or_else(|| VfsError::AuthError {
989
+ message: format!("no such user: {target}"),
990
+ })?;
991
+ let user = fs.registry.get_user(uid).unwrap();
992
+
993
+ session.uid = user.uid;
994
+ session.gid = user.groups.first().copied().unwrap_or(0);
995
+ session.groups = user.groups.clone();
996
+ session.username = user.name.clone();
997
+
998
+ Ok(format!("Switched to user '{}'\n", user.name))
999
+ }
1000
+
1001
+ fn cmd_delegate(
1002
+ fs: &VirtualFs,
1003
+ args: &[String],
1004
+ session: &mut Session,
1005
+ ) -> Result<String, VfsError> {
1006
+ if args.is_empty() {
1007
+ return Err(VfsError::InvalidArgs {
1008
+ message: "delegate: usage: delegate <user> or delegate :<group>".to_string(),
1009
+ });
1010
+ }
1011
+
1012
+ // Only agents or admins can delegate
1013
+ let is_agent = fs
1014
+ .registry
1015
+ .get_user(session.uid)
1016
+ .map(|u| u.is_agent)
1017
+ .unwrap_or(false);
1018
+ if !is_agent && session.uid != ROOT_UID && !session.groups.contains(&WHEEL_GID) {
1019
+ return Err(VfsError::PermissionDenied {
1020
+ path: "delegate: only agents or admins can delegate".to_string(),
1021
+ });
1022
+ }
1023
+
1024
+ let target = &args[0];
1025
+
1026
+ if let Some(group_name) = target.strip_prefix(':') {
1027
+ // Delegate for a group: permissions limited to what a generic member of that group can do
1028
+ let gid =
1029
+ fs.registry
1030
+ .lookup_gid(group_name)
1031
+ .ok_or_else(|| VfsError::AuthError {
1032
+ message: format!("no such group: {group_name}"),
1033
+ })?;
1034
+ session.delegate = Some(crate::auth::session::DelegateContext {
1035
+ // Use a synthetic uid that won't match any file owner — forces group/other bits only
1036
+ uid: u32::MAX,
1037
+ gid,
1038
+ groups: vec![gid],
1039
+ username: format!(":{group_name}"),
1040
+ });
1041
+ Ok(format!(
1042
+ "Now acting on behalf of group '{group_name}' (effective: intersection)\n"
1043
+ ))
1044
+ } else {
1045
+ // Delegate for a specific user
1046
+ let uid =
1047
+ fs.registry
1048
+ .lookup_uid(target)
1049
+ .ok_or_else(|| VfsError::AuthError {
1050
+ message: format!("no such user: {target}"),
1051
+ })?;
1052
+ let user = fs.registry.get_user(uid).unwrap();
1053
+ session.delegate = Some(crate::auth::session::DelegateContext {
1054
+ uid: user.uid,
1055
+ gid: user.groups.first().copied().unwrap_or(0),
1056
+ groups: user.groups.clone(),
1057
+ username: user.name.clone(),
1058
+ });
1059
+ Ok(format!(
1060
+ "Now acting on behalf of '{}' (effective: intersection)\n",
1061
+ user.name
1062
+ ))
1063
+ }
1064
+ }
1065
+
1066
+ fn cmd_undelegate(session: &mut Session) -> Result<String, VfsError> {
1067
+ if session.delegate.is_none() {
1068
+ return Ok("No active delegation\n".to_string());
1069
+ }
1070
+ let name = session
1071
+ .delegate
1072
+ .as_ref()
1073
+ .map(|d| d.username.clone())
1074
+ .unwrap_or_default();
1075
+ session.delegate = None;
1076
+ Ok(format!("Delegation for '{name}' ended\n"))
1077
+ }
1078
+
1079
+ // ───── Help ─────
1080
+
1081
+ fn cmd_help() -> Result<String, VfsError> {
1082
+ Ok(r#"markdownfs — Markdown Virtual File System
1083
+
1084
+ File commands:
1085
+ ls [-l] [path] List directory contents
1086
+ cd [path] Change directory
1087
+ pwd Print working directory
1088
+ mkdir [-p] <path> Create directory
1089
+ touch <file.md> Create empty markdown file
1090
+ cat <file> Display file contents
1091
+ write <file> [content] Write content to file (or pipe: echo "text" | write file.md)
1092
+ rm [-r] <path> Remove file or directory
1093
+ rmdir <path> Remove empty directory
1094
+ mv <src> <dst> Move/rename
1095
+ cp <src> <dst> Copy file
1096
+ stat <path> File information
1097
+ tree [path] Directory tree view
1098
+ find [path] [-name pat] Find files by pattern
1099
+ grep [-r] <pattern> [path] Search file contents
1100
+ head [-n N] First N lines (pipe)
1101
+ tail [-n N] Last N lines (pipe)
1102
+ wc [-l|-w|-c] Count lines/words/bytes (pipe)
1103
+ chmod <mode> <path> Change permissions (owner or root)
1104
+ chown <user:group> <path> Change ownership (root or owner)
1105
+ ln -s <target> <link> Create symbolic link
1106
+ echo <text> Print text
1107
+ edit <file.md> Edit file (multi-line input, auto-commits)
1108
+
1109
+ User management:
1110
+ adduser <name> Create user (admin)
1111
+ addagent <name> Create agent with API token (admin)
1112
+ deluser <name> Delete user (root only)
1113
+ addgroup <name> Create group (admin)
1114
+ delgroup <name> Delete group (root only)
1115
+ usermod -aG <grp> <user> Add user to group (admin)
1116
+ usermod -rG <grp> <user> Remove user from group (admin)
1117
+ groups [user] Show group memberships
1118
+ whoami Show current user
1119
+ id [user] Show user identity
1120
+ su <user> Switch user (root or wheel)
1121
+
1122
+ VCS commands:
1123
+ commit <message> Commit current state
1124
+ log Show commit history
1125
+ revert <hash> Revert to a commit
1126
+ status Show modified files
1127
+
1128
+ Pipes: grep "TODO" notes/ | head -5 | wc -l
1129
+ "#
1130
+ .to_string())
1131
+ }
1132
+
1133
+ // ───── Formatting ─────
1134
+
1135
+ fn format_permissions(mode: u16) -> String {
1136
+ let mut s = String::with_capacity(9);
1137
+ for shift in [6, 3, 0] {
1138
+ let bits = (mode >> shift) & 0o7;
1139
+ s.push(if bits & 4 != 0 { 'r' } else { '-' });
1140
+ s.push(if bits & 2 != 0 { 'w' } else { '-' });
1141
+ s.push(if bits & 1 != 0 { 'x' } else { '-' });
1142
+ }
1143
+ s
1144
+ }
1145
+
1146
+ fn format_time(epoch: u64) -> String {
1147
+ let dt = chrono::DateTime::from_timestamp(epoch as i64, 0);
1148
+ match dt {
1149
+ Some(d) => d.format("%b %d %H:%M").to_string(),
1150
+ None => "???".to_string(),
1151
+ }
1152
+ }
src/cmd/parser.rs ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /// Tokenize a command line, respecting quotes.
2
+ pub fn tokenize(input: &str) -> Vec<String> {
3
+ let mut tokens = Vec::new();
4
+ let mut current = String::new();
5
+ let mut in_single_quote = false;
6
+ let mut in_double_quote = false;
7
+ let mut escape_next = false;
8
+
9
+ for ch in input.chars() {
10
+ if escape_next {
11
+ current.push(ch);
12
+ escape_next = false;
13
+ continue;
14
+ }
15
+
16
+ match ch {
17
+ '\\' if !in_single_quote => {
18
+ escape_next = true;
19
+ }
20
+ '\'' if !in_double_quote => {
21
+ in_single_quote = !in_single_quote;
22
+ }
23
+ '"' if !in_single_quote => {
24
+ in_double_quote = !in_double_quote;
25
+ }
26
+ ' ' | '\t' if !in_single_quote && !in_double_quote => {
27
+ if !current.is_empty() {
28
+ tokens.push(std::mem::take(&mut current));
29
+ }
30
+ }
31
+ _ => {
32
+ current.push(ch);
33
+ }
34
+ }
35
+ }
36
+
37
+ if !current.is_empty() {
38
+ tokens.push(current);
39
+ }
40
+
41
+ tokens
42
+ }
43
+
44
+ #[derive(Debug)]
45
+ pub struct ParsedCommand {
46
+ pub program: String,
47
+ pub args: Vec<String>,
48
+ }
49
+
50
+ #[derive(Debug)]
51
+ pub struct Pipeline {
52
+ pub commands: Vec<ParsedCommand>,
53
+ }
54
+
55
+ pub fn parse_pipeline(input: &str) -> Pipeline {
56
+ let segments: Vec<&str> = split_on_pipes(input);
57
+ let commands = segments
58
+ .into_iter()
59
+ .filter_map(|seg| {
60
+ let tokens = tokenize(seg.trim());
61
+ if tokens.is_empty() {
62
+ return None;
63
+ }
64
+ Some(ParsedCommand {
65
+ program: tokens[0].clone(),
66
+ args: tokens[1..].to_vec(),
67
+ })
68
+ })
69
+ .collect();
70
+ Pipeline { commands }
71
+ }
72
+
73
+ fn split_on_pipes(input: &str) -> Vec<&str> {
74
+ let mut segments = Vec::new();
75
+ let mut start = 0;
76
+ let mut in_single = false;
77
+ let mut in_double = false;
78
+
79
+ for (i, ch) in input.char_indices() {
80
+ match ch {
81
+ '\'' if !in_double => in_single = !in_single,
82
+ '"' if !in_single => in_double = !in_double,
83
+ '|' if !in_single && !in_double => {
84
+ segments.push(&input[start..i]);
85
+ start = i + 1;
86
+ }
87
+ _ => {}
88
+ }
89
+ }
90
+ segments.push(&input[start..]);
91
+ segments
92
+ }
93
+
94
+ #[cfg(test)]
95
+ mod tests {
96
+ use super::*;
97
+
98
+ #[test]
99
+ fn test_tokenize_simple() {
100
+ assert_eq!(tokenize("ls -la /foo"), vec!["ls", "-la", "/foo"]);
101
+ }
102
+
103
+ #[test]
104
+ fn test_tokenize_quotes() {
105
+ assert_eq!(
106
+ tokenize(r#"grep "hello world" file.md"#),
107
+ vec!["grep", "hello world", "file.md"]
108
+ );
109
+ }
110
+
111
+ #[test]
112
+ fn test_pipeline() {
113
+ let pipeline = parse_pipeline("grep TODO notes/ | head -5 | wc -l");
114
+ assert_eq!(pipeline.commands.len(), 3);
115
+ assert_eq!(pipeline.commands[0].program, "grep");
116
+ assert_eq!(pipeline.commands[1].program, "head");
117
+ assert_eq!(pipeline.commands[2].program, "wc");
118
+ }
119
+ }
src/config.rs ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use serde::{Deserialize, Serialize};
2
+ use std::path::{Path, PathBuf};
3
+
4
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
5
+ pub enum CompatibilityTarget {
6
+ Markdown,
7
+ Posix,
8
+ }
9
+
10
+ impl CompatibilityTarget {
11
+ pub fn from_env_value(value: &str) -> Option<Self> {
12
+ match value.trim().to_ascii_lowercase().as_str() {
13
+ "markdown" | "markdown-only" | "markdown_only" => Some(Self::Markdown),
14
+ "posix" | "mount" | "fuse" => Some(Self::Posix),
15
+ _ => None,
16
+ }
17
+ }
18
+
19
+ pub fn as_str(self) -> &'static str {
20
+ match self {
21
+ Self::Markdown => "markdown",
22
+ Self::Posix => "posix",
23
+ }
24
+ }
25
+ }
26
+
27
+ #[derive(Debug, Clone)]
28
+ pub struct Config {
29
+ pub data_dir: PathBuf,
30
+ pub listen_addr: String,
31
+ pub auto_save_interval_secs: u64,
32
+ pub auto_save_write_threshold: u64,
33
+ pub max_file_size: usize,
34
+ pub max_inodes: usize,
35
+ pub max_dir_depth: usize,
36
+ pub compatibility_target: CompatibilityTarget,
37
+ }
38
+
39
+ impl Config {
40
+ pub fn from_env() -> Self {
41
+ let data_dir = std::env::var("MARKDOWNFS_DATA_DIR")
42
+ .map(PathBuf::from)
43
+ .unwrap_or_else(|_| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
44
+
45
+ let listen_addr = std::env::var("MARKDOWNFS_LISTEN")
46
+ .unwrap_or_else(|_| "127.0.0.1:3000".to_string());
47
+
48
+ let auto_save_interval_secs = std::env::var("MARKDOWNFS_AUTOSAVE_SECS")
49
+ .ok()
50
+ .and_then(|v| v.parse().ok())
51
+ .unwrap_or(5);
52
+
53
+ let auto_save_write_threshold = std::env::var("MARKDOWNFS_AUTOSAVE_WRITES")
54
+ .ok()
55
+ .and_then(|v| v.parse().ok())
56
+ .unwrap_or(100);
57
+
58
+ let max_file_size = std::env::var("MARKDOWNFS_MAX_FILE_SIZE")
59
+ .ok()
60
+ .and_then(|v| v.parse().ok())
61
+ .unwrap_or(10 * 1024 * 1024); // 10MB
62
+
63
+ let max_inodes = std::env::var("MARKDOWNFS_MAX_INODES")
64
+ .ok()
65
+ .and_then(|v| v.parse().ok())
66
+ .unwrap_or(1_000_000);
67
+
68
+ let max_dir_depth = std::env::var("MARKDOWNFS_MAX_DEPTH")
69
+ .ok()
70
+ .and_then(|v| v.parse().ok())
71
+ .unwrap_or(256);
72
+
73
+ let compatibility_target = std::env::var("MARKDOWNFS_COMPAT_TARGET")
74
+ .ok()
75
+ .and_then(|value| CompatibilityTarget::from_env_value(&value))
76
+ .unwrap_or(CompatibilityTarget::Markdown);
77
+
78
+ Config {
79
+ data_dir,
80
+ listen_addr,
81
+ auto_save_interval_secs,
82
+ auto_save_write_threshold,
83
+ max_file_size,
84
+ max_inodes,
85
+ max_dir_depth,
86
+ compatibility_target,
87
+ }
88
+ }
89
+
90
+ pub fn with_data_dir(mut self, dir: impl AsRef<Path>) -> Self {
91
+ self.data_dir = dir.as_ref().to_path_buf();
92
+ self
93
+ }
94
+
95
+ pub fn with_listen_addr(mut self, addr: impl Into<String>) -> Self {
96
+ self.listen_addr = addr.into();
97
+ self
98
+ }
99
+
100
+ pub fn with_compatibility_target(mut self, target: CompatibilityTarget) -> Self {
101
+ self.compatibility_target = target;
102
+ self
103
+ }
104
+ }
105
+
106
+ impl Default for Config {
107
+ fn default() -> Self {
108
+ Self::from_env()
109
+ }
110
+ }
src/db.rs ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::sync::Arc;
2
+ use std::sync::atomic::{AtomicU64, Ordering};
3
+ use tokio::sync::{Notify, RwLock};
4
+
5
+ use crate::auth::session::Session;
6
+ use crate::auth::{Gid, Uid};
7
+ use crate::config::Config;
8
+ use crate::error::VfsError;
9
+ use crate::fs::{FsOptions, GrepResult, HandleId, LsEntry, StatInfo, VirtualFs};
10
+ use crate::persist::{
11
+ LocalStateBackend, MemoryPersistenceBackend, PersistenceBackend, PersistenceInfo,
12
+ };
13
+ use crate::store::commit::CommitObject;
14
+ use crate::vcs::Vcs;
15
+
16
+ struct DbInner {
17
+ fs: VirtualFs,
18
+ vcs: Vcs,
19
+ }
20
+
21
+ /// Thread-safe, concurrent markdown database.
22
+ ///
23
+ /// All methods take `&self` (not `&mut self`). The struct is `Clone`
24
+ /// via the inner `Arc`, so it can be shared across threads cheaply.
25
+ #[derive(Clone)]
26
+ pub struct MarkdownDb {
27
+ inner: Arc<RwLock<DbInner>>,
28
+ persist: Arc<dyn PersistenceBackend>,
29
+ config: Arc<Config>,
30
+ write_count: Arc<AtomicU64>,
31
+ save_notify: Arc<Notify>,
32
+ }
33
+
34
+ impl MarkdownDb {
35
+ pub fn open(config: Config) -> Result<Self, VfsError> {
36
+ let persist: Arc<dyn PersistenceBackend> = Arc::new(LocalStateBackend::new(&config.data_dir));
37
+ Ok(Self::open_with_backend(config, persist))
38
+ }
39
+
40
+ pub fn open_with_backend(config: Config, persist: Arc<dyn PersistenceBackend>) -> Self {
41
+ let options = FsOptions {
42
+ compatibility_target: config.compatibility_target,
43
+ };
44
+ let (fs, vcs) = persist
45
+ .load()
46
+ .ok()
47
+ .flatten()
48
+ .map(|state| (state.fs, state.vcs))
49
+ .unwrap_or_else(|| (VirtualFs::new_with_options(options), Vcs::new()));
50
+
51
+ MarkdownDb {
52
+ inner: Arc::new(RwLock::new(DbInner { fs, vcs })),
53
+ persist,
54
+ config: Arc::new(config),
55
+ write_count: Arc::new(AtomicU64::new(0)),
56
+ save_notify: Arc::new(Notify::new()),
57
+ }
58
+ }
59
+
60
+ pub fn open_memory() -> Self {
61
+ let config = Config::from_env();
62
+ let options = FsOptions {
63
+ compatibility_target: config.compatibility_target,
64
+ };
65
+ MarkdownDb {
66
+ inner: Arc::new(RwLock::new(DbInner {
67
+ fs: VirtualFs::new_with_options(options),
68
+ vcs: Vcs::new(),
69
+ })),
70
+ persist: Arc::new(MemoryPersistenceBackend),
71
+ config: Arc::new(config),
72
+ write_count: Arc::new(AtomicU64::new(0)),
73
+ save_notify: Arc::new(Notify::new()),
74
+ }
75
+ }
76
+
77
+ fn mark_dirty(&self) {
78
+ let count = self.write_count.fetch_add(1, Ordering::Relaxed);
79
+ if count + 1 >= self.config.auto_save_write_threshold {
80
+ self.save_notify.notify_one();
81
+ }
82
+ }
83
+
84
+ /// Spawn a background auto-save task. Returns a handle that can be aborted on shutdown.
85
+ pub fn spawn_auto_save(&self) -> tokio::task::JoinHandle<()> {
86
+ let db = self.clone();
87
+ tokio::spawn(async move {
88
+ loop {
89
+ tokio::select! {
90
+ _ = tokio::time::sleep(std::time::Duration::from_secs(
91
+ db.config.auto_save_interval_secs,
92
+ )) => {}
93
+ _ = db.save_notify.notified() => {}
94
+ }
95
+
96
+ let prev = db.write_count.swap(0, Ordering::Relaxed);
97
+ if prev > 0 {
98
+ if let Err(e) = db.save().await {
99
+ tracing::error!("auto-save failed: {e}");
100
+ } else {
101
+ tracing::debug!("auto-saved after {prev} writes");
102
+ }
103
+ }
104
+ }
105
+ })
106
+ }
107
+
108
+ pub async fn save(&self) -> Result<(), VfsError> {
109
+ let guard = self.inner.read().await;
110
+ self.persist.save(&guard.fs, &guard.vcs)
111
+ }
112
+
113
+ pub fn config(&self) -> &Config {
114
+ &self.config
115
+ }
116
+
117
+ pub fn persist_info(&self) -> PersistenceInfo {
118
+ self.persist.info()
119
+ }
120
+
121
+ // ─── Read operations (take read lock) ───
122
+
123
+ pub async fn cat(&self, path: &str) -> Result<Vec<u8>, VfsError> {
124
+ let guard = self.inner.read().await;
125
+ guard.fs.cat_owned(path)
126
+ }
127
+
128
+ pub async fn ls(&self, path: Option<&str>) -> Result<Vec<LsEntry>, VfsError> {
129
+ let guard = self.inner.read().await;
130
+ guard.fs.ls(path)
131
+ }
132
+
133
+ pub async fn stat(&self, path: &str) -> Result<StatInfo, VfsError> {
134
+ let guard = self.inner.read().await;
135
+ guard.fs.stat(path)
136
+ }
137
+
138
+ pub async fn pwd(&self) -> String {
139
+ let guard = self.inner.read().await;
140
+ guard.fs.pwd()
141
+ }
142
+
143
+ pub async fn tree(
144
+ &self,
145
+ path: Option<&str>,
146
+ session: Option<&Session>,
147
+ ) -> Result<String, VfsError> {
148
+ let guard = self.inner.read().await;
149
+ guard.fs.tree(path, "", session)
150
+ }
151
+
152
+ pub async fn find(
153
+ &self,
154
+ path: Option<&str>,
155
+ pattern: Option<&str>,
156
+ session: Option<&Session>,
157
+ ) -> Result<Vec<String>, VfsError> {
158
+ let guard = self.inner.read().await;
159
+ guard.fs.find(path, pattern, session)
160
+ }
161
+
162
+ pub async fn grep(
163
+ &self,
164
+ pattern: &str,
165
+ path: Option<&str>,
166
+ recursive: bool,
167
+ session: Option<&Session>,
168
+ ) -> Result<Vec<GrepResult>, VfsError> {
169
+ let guard = self.inner.read().await;
170
+ guard.fs.grep(pattern, path, recursive, session)
171
+ }
172
+
173
+ pub async fn vcs_log(&self) -> Vec<CommitObject> {
174
+ let guard = self.inner.read().await;
175
+ guard.vcs.log().into_iter().cloned().collect()
176
+ }
177
+
178
+ pub async fn vcs_status(&self) -> Result<String, VfsError> {
179
+ let guard = self.inner.read().await;
180
+ let inner = &*guard;
181
+ inner.vcs.status(&inner.fs)
182
+ }
183
+
184
+ // ─── Write operations (take write lock) ───
185
+
186
+ pub async fn touch(&self, path: &str, uid: Uid, gid: Gid) -> Result<(), VfsError> {
187
+ let mut guard = self.inner.write().await;
188
+ guard.fs.touch(path, uid, gid)?;
189
+ drop(guard);
190
+ self.mark_dirty();
191
+ Ok(())
192
+ }
193
+
194
+ pub async fn write_file(&self, path: &str, content: Vec<u8>) -> Result<(), VfsError> {
195
+ if content.len() > self.config.max_file_size {
196
+ return Err(VfsError::InvalidArgs {
197
+ message: format!(
198
+ "file size {} exceeds max {}",
199
+ content.len(),
200
+ self.config.max_file_size
201
+ ),
202
+ });
203
+ }
204
+ let mut guard = self.inner.write().await;
205
+ guard.fs.write_file(path, content)?;
206
+ drop(guard);
207
+ self.mark_dirty();
208
+ Ok(())
209
+ }
210
+
211
+ pub async fn mkdir(&self, path: &str, uid: Uid, gid: Gid) -> Result<(), VfsError> {
212
+ let mut guard = self.inner.write().await;
213
+ guard.fs.mkdir(path, uid, gid)?;
214
+ drop(guard);
215
+ self.mark_dirty();
216
+ Ok(())
217
+ }
218
+
219
+ pub async fn mkdir_p(&self, path: &str, uid: Uid, gid: Gid) -> Result<(), VfsError> {
220
+ let mut guard = self.inner.write().await;
221
+ guard.fs.mkdir_p(path, uid, gid)?;
222
+ drop(guard);
223
+ self.mark_dirty();
224
+ Ok(())
225
+ }
226
+
227
+ pub async fn rm(&self, path: &str) -> Result<(), VfsError> {
228
+ let mut guard = self.inner.write().await;
229
+ guard.fs.rm(path)?;
230
+ drop(guard);
231
+ self.mark_dirty();
232
+ Ok(())
233
+ }
234
+
235
+ pub async fn rm_rf(&self, path: &str) -> Result<(), VfsError> {
236
+ let mut guard = self.inner.write().await;
237
+ guard.fs.rm_rf(path)?;
238
+ drop(guard);
239
+ self.mark_dirty();
240
+ Ok(())
241
+ }
242
+
243
+ pub async fn mv(&self, src: &str, dst: &str) -> Result<(), VfsError> {
244
+ let mut guard = self.inner.write().await;
245
+ guard.fs.mv(src, dst)?;
246
+ drop(guard);
247
+ self.mark_dirty();
248
+ Ok(())
249
+ }
250
+
251
+ pub async fn cp(
252
+ &self,
253
+ src: &str,
254
+ dst: &str,
255
+ uid: Uid,
256
+ gid: Gid,
257
+ ) -> Result<(), VfsError> {
258
+ let mut guard = self.inner.write().await;
259
+ guard.fs.cp(src, dst, uid, gid)?;
260
+ drop(guard);
261
+ self.mark_dirty();
262
+ Ok(())
263
+ }
264
+
265
+ pub async fn chmod(&self, path: &str, mode: u16) -> Result<(), VfsError> {
266
+ let mut guard = self.inner.write().await;
267
+ guard.fs.chmod(path, mode)?;
268
+ drop(guard);
269
+ self.mark_dirty();
270
+ Ok(())
271
+ }
272
+
273
+ pub async fn chown(&self, path: &str, uid: Uid, gid: Gid) -> Result<(), VfsError> {
274
+ let mut guard = self.inner.write().await;
275
+ guard.fs.chown(path, uid, gid)?;
276
+ drop(guard);
277
+ self.mark_dirty();
278
+ Ok(())
279
+ }
280
+
281
+ pub async fn ln_s(
282
+ &self,
283
+ target: &str,
284
+ link_path: &str,
285
+ uid: Uid,
286
+ gid: Gid,
287
+ ) -> Result<(), VfsError> {
288
+ let mut guard = self.inner.write().await;
289
+ guard.fs.ln_s(target, link_path, uid, gid)?;
290
+ drop(guard);
291
+ self.mark_dirty();
292
+ Ok(())
293
+ }
294
+
295
+ pub async fn link(&self, target: &str, link_path: &str) -> Result<(), VfsError> {
296
+ let mut guard = self.inner.write().await;
297
+ guard.fs.link(target, link_path)?;
298
+ drop(guard);
299
+ self.mark_dirty();
300
+ Ok(())
301
+ }
302
+
303
+ pub async fn readlink(&self, path: &str) -> Result<String, VfsError> {
304
+ let guard = self.inner.read().await;
305
+ guard.fs.readlink(path)
306
+ }
307
+
308
+ pub async fn truncate(&self, path: &str, size: usize) -> Result<(), VfsError> {
309
+ let mut guard = self.inner.write().await;
310
+ guard.fs.truncate(path, size)?;
311
+ drop(guard);
312
+ self.mark_dirty();
313
+ Ok(())
314
+ }
315
+
316
+ pub async fn read_file_at(
317
+ &self,
318
+ path: &str,
319
+ offset: usize,
320
+ size: usize,
321
+ ) -> Result<Vec<u8>, VfsError> {
322
+ let mut guard = self.inner.write().await;
323
+ guard.fs.read_file_at(path, offset, size)
324
+ }
325
+
326
+ pub async fn write_file_at(
327
+ &self,
328
+ path: &str,
329
+ offset: usize,
330
+ data: &[u8],
331
+ ) -> Result<usize, VfsError> {
332
+ let end = offset.saturating_add(data.len());
333
+ if end > self.config.max_file_size {
334
+ return Err(VfsError::InvalidArgs {
335
+ message: format!("write exceeds max file size {}", self.config.max_file_size),
336
+ });
337
+ }
338
+ let mut guard = self.inner.write().await;
339
+ let written = guard.fs.write_file_at(path, offset, data)?;
340
+ drop(guard);
341
+ self.mark_dirty();
342
+ Ok(written)
343
+ }
344
+
345
+ pub async fn open_file(&self, path: &str, writable: bool) -> Result<HandleId, VfsError> {
346
+ let mut guard = self.inner.write().await;
347
+ guard.fs.open(path, writable)
348
+ }
349
+
350
+ pub async fn open_dir(&self, path: &str) -> Result<HandleId, VfsError> {
351
+ let mut guard = self.inner.write().await;
352
+ guard.fs.opendir(path)
353
+ }
354
+
355
+ pub async fn read_handle(&self, handle: HandleId, size: usize) -> Result<Vec<u8>, VfsError> {
356
+ let mut guard = self.inner.write().await;
357
+ guard.fs.read_handle(handle, size)
358
+ }
359
+
360
+ pub async fn write_handle(&self, handle: HandleId, data: &[u8]) -> Result<usize, VfsError> {
361
+ let mut guard = self.inner.write().await;
362
+ let written = guard.fs.write_handle(handle, data)?;
363
+ drop(guard);
364
+ self.mark_dirty();
365
+ Ok(written)
366
+ }
367
+
368
+ pub async fn release_handle(&self, handle: HandleId) -> Result<(), VfsError> {
369
+ let mut guard = self.inner.write().await;
370
+ guard.fs.release_handle(handle)
371
+ }
372
+
373
+ pub async fn commit(&self, message: &str, author: &str) -> Result<String, VfsError> {
374
+ let mut guard = self.inner.write().await;
375
+ let inner = &mut *guard;
376
+ let id = inner.vcs.commit(&inner.fs, message, author)?;
377
+ drop(guard);
378
+ self.mark_dirty();
379
+ Ok(id.short_hex())
380
+ }
381
+
382
+ pub async fn revert(&self, hash_prefix: &str) -> Result<(), VfsError> {
383
+ let mut guard = self.inner.write().await;
384
+ let inner = &mut *guard;
385
+ inner.vcs.revert(&mut inner.fs, hash_prefix)?;
386
+ drop(guard);
387
+ self.mark_dirty();
388
+ Ok(())
389
+ }
390
+
391
+ // ─── Command execution (write lock — dispatches through cmd module) ───
392
+
393
+ pub async fn execute_command(
394
+ &self,
395
+ line: &str,
396
+ session: &mut Session,
397
+ ) -> Result<String, VfsError> {
398
+ use crate::cmd;
399
+ use crate::cmd::parser;
400
+
401
+ let pipeline = parser::parse_pipeline(line);
402
+ if pipeline.commands.is_empty() {
403
+ return Ok(String::new());
404
+ }
405
+
406
+ if let Some(first) = pipeline.commands.first() {
407
+ match first.program.as_str() {
408
+ "commit" => {
409
+ let msg = if first.args.is_empty() {
410
+ "snapshot"
411
+ } else {
412
+ &first.args.join(" ")
413
+ };
414
+ let hash = self.commit(msg, &session.username).await?;
415
+ return Ok(format!("[{hash}] {msg}\n"));
416
+ }
417
+ "log" => {
418
+ let commits = self.vcs_log().await;
419
+ if commits.is_empty() {
420
+ return Ok("No commits yet.\n".to_string());
421
+ }
422
+ let mut output = String::new();
423
+ for c in &commits {
424
+ let time = chrono::DateTime::from_timestamp(c.timestamp as i64, 0)
425
+ .map(|d| d.format("%Y-%m-%d %H:%M:%S").to_string())
426
+ .unwrap_or_else(|| "???".to_string());
427
+ output.push_str(&format!(
428
+ "{} {} {} {}\n",
429
+ c.id.short_hex(),
430
+ time,
431
+ c.author,
432
+ c.message
433
+ ));
434
+ }
435
+ return Ok(output);
436
+ }
437
+ "revert" => {
438
+ if first.args.is_empty() {
439
+ return Err(VfsError::InvalidArgs {
440
+ message: "revert: need commit hash prefix".to_string(),
441
+ });
442
+ }
443
+ self.revert(&first.args[0]).await?;
444
+ return Ok(format!("Reverted to {}\n", first.args[0]));
445
+ }
446
+ "status" => {
447
+ return self.vcs_status().await;
448
+ }
449
+ _ => {}
450
+ }
451
+ }
452
+
453
+ let mut guard = self.inner.write().await;
454
+ let inner = &mut *guard;
455
+ let result = cmd::execute_pipeline(&pipeline, &mut inner.fs, session);
456
+ let is_write = pipeline.commands.iter().any(|c| {
457
+ matches!(
458
+ c.program.as_str(),
459
+ "touch"
460
+ | "write"
461
+ | "mkdir"
462
+ | "rm"
463
+ | "rmdir"
464
+ | "mv"
465
+ | "cp"
466
+ | "chmod"
467
+ | "chown"
468
+ | "ln"
469
+ | "adduser"
470
+ | "addagent"
471
+ | "deluser"
472
+ | "addgroup"
473
+ | "delgroup"
474
+ | "usermod"
475
+ )
476
+ });
477
+ drop(guard);
478
+ if is_write {
479
+ self.mark_dirty();
480
+ }
481
+ result
482
+ }
483
+
484
+ // ─── Auth helpers ───
485
+
486
+ pub async fn login(&self, username: &str) -> Result<Session, VfsError> {
487
+ let mut guard = self.inner.write().await;
488
+ let uid = guard
489
+ .registry_lookup_uid(username)
490
+ .ok_or_else(|| VfsError::AuthError {
491
+ message: format!("unknown user: {username}"),
492
+ })?;
493
+ let user = guard
494
+ .registry_get_user(uid)
495
+ .ok_or_else(|| VfsError::AuthError {
496
+ message: format!("user uid={uid} not found"),
497
+ })?;
498
+ let session = Session::new(
499
+ user.uid,
500
+ user.groups.first().copied().unwrap_or(0),
501
+ user.groups.clone(),
502
+ user.name.clone(),
503
+ );
504
+
505
+ let home_path = format!("/home/{username}");
506
+ if guard.fs.stat(&home_path).is_ok() {
507
+ let _ = guard.fs.cd(&home_path);
508
+ }
509
+
510
+ Ok(session)
511
+ }
512
+
513
+ pub async fn authenticate_token(&self, raw_token: &str) -> Result<Session, VfsError> {
514
+ let guard = self.inner.read().await;
515
+ let uid = guard
516
+ .fs
517
+ .registry
518
+ .authenticate_token(raw_token)
519
+ .ok_or_else(|| VfsError::AuthError {
520
+ message: "invalid token".to_string(),
521
+ })?;
522
+ let user = guard
523
+ .fs
524
+ .registry
525
+ .get_user(uid)
526
+ .ok_or_else(|| VfsError::AuthError {
527
+ message: "token user not found".to_string(),
528
+ })?;
529
+ Ok(Session::new(
530
+ user.uid,
531
+ user.groups.first().copied().unwrap_or(0),
532
+ user.groups.clone(),
533
+ user.name.clone(),
534
+ ))
535
+ }
536
+
537
+ pub async fn has_users(&self) -> bool {
538
+ let guard = self.inner.read().await;
539
+ guard
540
+ .fs
541
+ .registry
542
+ .list_users()
543
+ .iter()
544
+ .any(|u| u.uid != crate::auth::ROOT_UID)
545
+ }
546
+
547
+ pub async fn create_admin(&self, name: &str) -> Result<Session, VfsError> {
548
+ let mut guard = self.inner.write().await;
549
+ let (uid, _) = guard.fs.registry.add_user(name, false)?;
550
+ let _ = guard.fs.registry.usermod_add_group(name, "wheel");
551
+ let user = guard.fs.registry.get_user(uid).unwrap();
552
+ let gid = user.groups.first().copied().unwrap_or(0);
553
+ let session = Session::new(uid, gid, user.groups.clone(), user.name.clone());
554
+
555
+ let _ = guard.fs.mkdir_p(
556
+ "/home",
557
+ crate::auth::ROOT_UID,
558
+ crate::auth::ROOT_GID,
559
+ );
560
+ let home_path = format!("/home/{name}");
561
+ let _ = guard.fs.mkdir(&home_path, uid, gid);
562
+ let _ = guard.fs.cd(&home_path);
563
+
564
+ drop(guard);
565
+ self.mark_dirty();
566
+ Ok(session)
567
+ }
568
+
569
+ pub async fn commit_count(&self) -> usize {
570
+ let guard = self.inner.read().await;
571
+ guard.vcs.commits.len()
572
+ }
573
+
574
+ pub async fn object_count(&self) -> usize {
575
+ let guard = self.inner.read().await;
576
+ guard.vcs.store.object_count()
577
+ }
578
+
579
+ pub async fn inode_count(&self) -> usize {
580
+ let guard = self.inner.read().await;
581
+ guard.fs.all_inodes().len()
582
+ }
583
+
584
+ pub fn snapshot_fs(&self) -> VirtualFs {
585
+ self.inner.blocking_read().fs.clone()
586
+ }
587
+ }
588
+
589
+ impl DbInner {
590
+ fn registry_lookup_uid(&self, name: &str) -> Option<Uid> {
591
+ self.fs.registry.lookup_uid(name)
592
+ }
593
+
594
+ fn registry_get_user(&self, uid: Uid) -> Option<crate::auth::User> {
595
+ self.fs.registry.get_user(uid).cloned()
596
+ }
597
+ }
src/error.rs ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::fmt;
2
+
3
+ #[derive(Debug)]
4
+ pub enum VfsError {
5
+ InvalidExtension { name: String },
6
+ InvalidHandle { handle: u64 },
7
+ NotFound { path: String },
8
+ IsDirectory { path: String },
9
+ NotDirectory { path: String },
10
+ AlreadyExists { path: String },
11
+ NotEmpty { path: String },
12
+ InvalidPath { path: String },
13
+ IoError(std::io::Error),
14
+ UnknownCommand { name: String },
15
+ InvalidArgs { message: String },
16
+ SymlinkLoop { path: String },
17
+ ObjectNotFound { id: String },
18
+ CorruptStore { message: String },
19
+ NoCommits,
20
+ DirtyWorkingTree,
21
+ PermissionDenied { path: String },
22
+ AuthError { message: String },
23
+ NotSupported { message: String },
24
+ }
25
+
26
+ impl fmt::Display for VfsError {
27
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28
+ match self {
29
+ VfsError::InvalidExtension { name } => {
30
+ write!(f, "markdownfs: only .md files are supported: '{name}'")
31
+ }
32
+ VfsError::InvalidHandle { handle } => write!(f, "markdownfs: invalid handle: {handle}"),
33
+ VfsError::NotFound { path } => write!(f, "markdownfs: no such file or directory: '{path}'"),
34
+ VfsError::IsDirectory { path } => write!(f, "markdownfs: is a directory: '{path}'"),
35
+ VfsError::NotDirectory { path } => write!(f, "markdownfs: not a directory: '{path}'"),
36
+ VfsError::AlreadyExists { path } => write!(f, "markdownfs: already exists: '{path}'"),
37
+ VfsError::NotEmpty { path } => write!(f, "markdownfs: directory not empty: '{path}'"),
38
+ VfsError::InvalidPath { path } => write!(f, "markdownfs: invalid path: '{path}'"),
39
+ VfsError::IoError(e) => write!(f, "markdownfs: I/O error: {e}"),
40
+ VfsError::UnknownCommand { name } => write!(f, "markdownfs: unknown command: '{name}'"),
41
+ VfsError::InvalidArgs { message } => write!(f, "markdownfs: {message}"),
42
+ VfsError::SymlinkLoop { path } => write!(f, "markdownfs: symlink loop: '{path}'"),
43
+ VfsError::ObjectNotFound { id } => write!(f, "markdownfs: object not found: {id}"),
44
+ VfsError::CorruptStore { message } => write!(f, "markdownfs: corrupt store: {message}"),
45
+ VfsError::NoCommits => write!(f, "markdownfs: no commits yet"),
46
+ VfsError::DirtyWorkingTree => {
47
+ write!(f, "markdownfs: working tree has uncommitted changes")
48
+ }
49
+ VfsError::PermissionDenied { path } => {
50
+ write!(f, "markdownfs: permission denied: '{path}'")
51
+ }
52
+ VfsError::AuthError { message } => write!(f, "markdownfs: {message}"),
53
+ VfsError::NotSupported { message } => write!(f, "markdownfs: operation not supported: {message}"),
54
+ }
55
+ }
56
+ }
57
+
58
+ impl std::error::Error for VfsError {}
59
+
60
+ impl From<std::io::Error> for VfsError {
61
+ fn from(e: std::io::Error) -> Self {
62
+ VfsError::IoError(e)
63
+ }
64
+ }
src/fs/inode.rs ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use serde::{Deserialize, Serialize};
2
+ use std::collections::BTreeMap;
3
+ use std::time::{SystemTime, UNIX_EPOCH};
4
+
5
+ pub type InodeId = u64;
6
+
7
+ #[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
8
+ pub struct Timestamp {
9
+ pub secs: u64,
10
+ pub nanos: u32,
11
+ }
12
+
13
+ impl Timestamp {
14
+ pub fn now() -> Self {
15
+ let duration = SystemTime::now()
16
+ .duration_since(UNIX_EPOCH)
17
+ .unwrap_or_default();
18
+ Self {
19
+ secs: duration.as_secs(),
20
+ nanos: duration.subsec_nanos(),
21
+ }
22
+ }
23
+ }
24
+
25
+ #[derive(Debug, Clone, Serialize, Deserialize)]
26
+ pub struct Inode {
27
+ pub id: InodeId,
28
+ pub kind: InodeKind,
29
+ pub mode: u16,
30
+ pub uid: u32,
31
+ pub gid: u32,
32
+ #[serde(default = "default_nlink")]
33
+ pub nlink: u64,
34
+ #[serde(default = "default_block_size")]
35
+ pub block_size: u64,
36
+ #[serde(default)]
37
+ pub created_at: Timestamp,
38
+ #[serde(default)]
39
+ pub modified_at: Timestamp,
40
+ #[serde(default)]
41
+ pub accessed_at: Timestamp,
42
+ #[serde(default)]
43
+ pub changed_at: Timestamp,
44
+ #[serde(default)]
45
+ pub created: u64,
46
+ #[serde(default)]
47
+ pub modified: u64,
48
+ }
49
+
50
+ #[derive(Debug, Clone, Serialize, Deserialize)]
51
+ pub enum InodeKind {
52
+ File { content: Vec<u8> },
53
+ Directory { entries: BTreeMap<String, InodeId> },
54
+ Symlink { target: String },
55
+ }
56
+
57
+ impl Inode {
58
+ pub fn new_dir(id: InodeId, uid: u32, gid: u32) -> Self {
59
+ let now = Timestamp::now();
60
+ Inode {
61
+ id,
62
+ kind: InodeKind::Directory {
63
+ entries: BTreeMap::new(),
64
+ },
65
+ mode: 0o755,
66
+ uid,
67
+ gid,
68
+ nlink: 2,
69
+ block_size: 4096,
70
+ created_at: now,
71
+ modified_at: now,
72
+ accessed_at: now,
73
+ changed_at: now,
74
+ created: now.secs,
75
+ modified: now.secs,
76
+ }
77
+ }
78
+
79
+ pub fn new_file(id: InodeId, uid: u32, gid: u32) -> Self {
80
+ let now = Timestamp::now();
81
+ Inode {
82
+ id,
83
+ kind: InodeKind::File {
84
+ content: Vec::new(),
85
+ },
86
+ mode: 0o644,
87
+ uid,
88
+ gid,
89
+ nlink: 1,
90
+ block_size: 4096,
91
+ created_at: now,
92
+ modified_at: now,
93
+ accessed_at: now,
94
+ changed_at: now,
95
+ created: now.secs,
96
+ modified: now.secs,
97
+ }
98
+ }
99
+
100
+ pub fn new_symlink(id: InodeId, target: String, uid: u32, gid: u32) -> Self {
101
+ let now = Timestamp::now();
102
+ Inode {
103
+ id,
104
+ kind: InodeKind::Symlink { target },
105
+ mode: 0o777,
106
+ uid,
107
+ gid,
108
+ nlink: 1,
109
+ block_size: 4096,
110
+ created_at: now,
111
+ modified_at: now,
112
+ accessed_at: now,
113
+ changed_at: now,
114
+ created: now.secs,
115
+ modified: now.secs,
116
+ }
117
+ }
118
+
119
+ pub fn is_dir(&self) -> bool {
120
+ matches!(self.kind, InodeKind::Directory { .. })
121
+ }
122
+
123
+ pub fn is_file(&self) -> bool {
124
+ matches!(self.kind, InodeKind::File { .. })
125
+ }
126
+
127
+ pub fn size(&self) -> u64 {
128
+ match &self.kind {
129
+ InodeKind::File { content } => content.len() as u64,
130
+ InodeKind::Directory { entries } => entries.len() as u64,
131
+ InodeKind::Symlink { target } => target.len() as u64,
132
+ }
133
+ }
134
+
135
+ pub fn blocks(&self) -> u64 {
136
+ let size = self.size();
137
+ if size == 0 {
138
+ 0
139
+ } else {
140
+ size.div_ceil(512)
141
+ }
142
+ }
143
+
144
+ pub fn touch_access(&mut self) {
145
+ let now = Timestamp::now();
146
+ self.accessed_at = now;
147
+ }
148
+
149
+ pub fn touch_modify(&mut self) {
150
+ let now = Timestamp::now();
151
+ self.modified_at = now;
152
+ self.changed_at = now;
153
+ self.modified = now.secs;
154
+ }
155
+
156
+ pub fn touch_change(&mut self) {
157
+ let now = Timestamp::now();
158
+ self.changed_at = now;
159
+ }
160
+ }
161
+
162
+ fn default_nlink() -> u64 {
163
+ 1
164
+ }
165
+
166
+ fn default_block_size() -> u64 {
167
+ 4096
168
+ }
src/fs/mod.rs ADDED
@@ -0,0 +1,1362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pub mod inode;
2
+
3
+ use crate::auth::perms::{has_setgid, Access};
4
+ use crate::auth::registry::UserRegistry;
5
+ use crate::auth::session::Session;
6
+ use crate::auth::{Gid, Uid, ROOT_GID, ROOT_UID};
7
+ use crate::config::CompatibilityTarget;
8
+ use crate::error::VfsError;
9
+ use inode::{Inode, InodeId, InodeKind};
10
+ use std::collections::BTreeMap;
11
+ use std::collections::{HashMap, HashSet};
12
+
13
+ pub type HandleId = u64;
14
+
15
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16
+ pub struct FsOptions {
17
+ pub compatibility_target: CompatibilityTarget,
18
+ }
19
+
20
+ impl Default for FsOptions {
21
+ fn default() -> Self {
22
+ Self {
23
+ compatibility_target: CompatibilityTarget::Markdown,
24
+ }
25
+ }
26
+ }
27
+
28
+ #[derive(Debug, Clone)]
29
+ struct OpenHandle {
30
+ inode_id: InodeId,
31
+ cursor: usize,
32
+ writable: bool,
33
+ directory: bool,
34
+ }
35
+
36
+ #[derive(Clone)]
37
+ pub struct VirtualFs {
38
+ inodes: HashMap<InodeId, Inode>,
39
+ root: InodeId,
40
+ cwd: InodeId,
41
+ next_id: InodeId,
42
+ cwd_path: Vec<(String, InodeId)>,
43
+ options: FsOptions,
44
+ next_handle: HandleId,
45
+ handles: HashMap<HandleId, OpenHandle>,
46
+ pending_delete: HashSet<InodeId>,
47
+ pub registry: UserRegistry,
48
+ }
49
+
50
+ impl VirtualFs {
51
+ pub fn new() -> Self {
52
+ Self::new_with_options(FsOptions::default())
53
+ }
54
+
55
+ pub fn new_posix() -> Self {
56
+ Self::new_with_options(FsOptions {
57
+ compatibility_target: CompatibilityTarget::Posix,
58
+ })
59
+ }
60
+
61
+ pub fn new_with_options(options: FsOptions) -> Self {
62
+ let root_id = 0;
63
+ let root = Inode::new_dir(root_id, ROOT_UID, ROOT_GID);
64
+ let mut inodes = HashMap::new();
65
+ inodes.insert(root_id, root);
66
+ VirtualFs {
67
+ inodes,
68
+ root: root_id,
69
+ cwd: root_id,
70
+ next_id: 1,
71
+ cwd_path: Vec::new(),
72
+ options,
73
+ next_handle: 1,
74
+ handles: HashMap::new(),
75
+ pending_delete: HashSet::new(),
76
+ registry: UserRegistry::new(),
77
+ }
78
+ }
79
+
80
+ fn alloc_id(&mut self) -> InodeId {
81
+ let id = self.next_id;
82
+ self.next_id += 1;
83
+ id
84
+ }
85
+
86
+ fn alloc_handle_id(&mut self) -> HandleId {
87
+ let id = self.next_handle;
88
+ self.next_handle += 1;
89
+ id
90
+ }
91
+
92
+ pub fn options(&self) -> FsOptions {
93
+ self.options
94
+ }
95
+
96
+ pub fn compatibility_target(&self) -> CompatibilityTarget {
97
+ self.options.compatibility_target
98
+ }
99
+
100
+ pub fn pwd(&self) -> String {
101
+ if self.cwd_path.is_empty() {
102
+ "/".to_string()
103
+ } else {
104
+ let mut path = String::new();
105
+ for (name, _) in &self.cwd_path {
106
+ path.push('/');
107
+ path.push_str(name);
108
+ }
109
+ path
110
+ }
111
+ }
112
+
113
+ pub fn get_inode(&self, id: InodeId) -> Result<&Inode, VfsError> {
114
+ self.inodes.get(&id).ok_or_else(|| VfsError::NotFound {
115
+ path: format!("<inode {id}>"),
116
+ })
117
+ }
118
+
119
+ fn get_inode_mut(&mut self, id: InodeId) -> Result<&mut Inode, VfsError> {
120
+ self.inodes.get_mut(&id).ok_or_else(|| VfsError::NotFound {
121
+ path: format!("<inode {id}>"),
122
+ })
123
+ }
124
+
125
+ fn dir_entries(&self, id: InodeId) -> Result<&BTreeMap<String, InodeId>, VfsError> {
126
+ match &self.get_inode(id)?.kind {
127
+ InodeKind::Directory { entries } => Ok(entries),
128
+ _ => Err(VfsError::NotDirectory {
129
+ path: format!("<inode {id}>"),
130
+ }),
131
+ }
132
+ }
133
+
134
+ fn dir_entries_mut(
135
+ &mut self,
136
+ id: InodeId,
137
+ ) -> Result<&mut BTreeMap<String, InodeId>, VfsError> {
138
+ match &mut self.get_inode_mut(id)?.kind {
139
+ InodeKind::Directory { entries } => Ok(entries),
140
+ _ => Err(VfsError::NotDirectory {
141
+ path: format!("<inode {id}>"),
142
+ }),
143
+ }
144
+ }
145
+
146
+ /// Resolve a path without permission checks (for internal/VCS use).
147
+ pub fn resolve_path(&self, path: &str) -> Result<InodeId, VfsError> {
148
+ let (start, components) = self.parse_path(path);
149
+ let mut current = start;
150
+ for component in &components {
151
+ match component.as_str() {
152
+ "." => {}
153
+ ".." => {
154
+ current = self.parent_of(current);
155
+ }
156
+ name => {
157
+ let entries = self.dir_entries(current)?;
158
+ current = *entries.get(name).ok_or_else(|| VfsError::NotFound {
159
+ path: path.to_string(),
160
+ })?;
161
+ }
162
+ }
163
+ }
164
+ Ok(current)
165
+ }
166
+
167
+ /// Resolve a path with Execute permission checks on every directory.
168
+ pub fn resolve_path_checked(
169
+ &self,
170
+ path: &str,
171
+ session: &Session,
172
+ ) -> Result<InodeId, VfsError> {
173
+ let (start, components) = self.parse_path(path);
174
+ let mut current = start;
175
+
176
+ // Check execute on starting directory
177
+ let start_inode = self.get_inode(current)?;
178
+ if !session.has_permission(start_inode, Access::Execute) {
179
+ return Err(VfsError::PermissionDenied {
180
+ path: path.to_string(),
181
+ });
182
+ }
183
+
184
+ for component in &components {
185
+ match component.as_str() {
186
+ "." => {}
187
+ ".." => {
188
+ current = self.parent_of(current);
189
+ }
190
+ name => {
191
+ let entries = self.dir_entries(current)?;
192
+ current = *entries.get(name).ok_or_else(|| VfsError::NotFound {
193
+ path: path.to_string(),
194
+ })?;
195
+ // Check execute on intermediate directories
196
+ let inode = self.get_inode(current)?;
197
+ if inode.is_dir() && !session.has_permission(inode, Access::Execute) {
198
+ return Err(VfsError::PermissionDenied {
199
+ path: path.to_string(),
200
+ });
201
+ }
202
+ }
203
+ }
204
+ }
205
+ Ok(current)
206
+ }
207
+
208
+ /// Resolve parent with permission checks.
209
+ pub fn resolve_parent_checked(
210
+ &self,
211
+ path: &str,
212
+ session: &Session,
213
+ ) -> Result<(InodeId, String), VfsError> {
214
+ let (start, components) = self.parse_path(path);
215
+ if components.is_empty() {
216
+ return Err(VfsError::InvalidPath {
217
+ path: path.to_string(),
218
+ });
219
+ }
220
+ let name = components.last().unwrap().clone();
221
+ let parent_path = if components.len() == 1 {
222
+ if path.starts_with('/') {
223
+ "/".to_string()
224
+ } else {
225
+ ".".to_string()
226
+ }
227
+ } else {
228
+ let parent_components = &components[..components.len() - 1];
229
+ if path.starts_with('/') {
230
+ format!("/{}", parent_components.join("/"))
231
+ } else {
232
+ parent_components.join("/")
233
+ }
234
+ };
235
+ let _ = start; // used via parse_path in resolve_path_checked
236
+ let parent_id = self.resolve_path_checked(&parent_path, session)?;
237
+ Ok((parent_id, name))
238
+ }
239
+
240
+ fn resolve_parent(&self, path: &str) -> Result<(InodeId, String), VfsError> {
241
+ let (start, components) = self.parse_path(path);
242
+ if components.is_empty() {
243
+ return Err(VfsError::InvalidPath {
244
+ path: path.to_string(),
245
+ });
246
+ }
247
+ let name = components.last().unwrap().clone();
248
+ let mut current = start;
249
+ for component in &components[..components.len() - 1] {
250
+ match component.as_str() {
251
+ "." => {}
252
+ ".." => {
253
+ current = self.parent_of(current);
254
+ }
255
+ n => {
256
+ let entries = self.dir_entries(current)?;
257
+ current = *entries.get(n).ok_or_else(|| VfsError::NotFound {
258
+ path: path.to_string(),
259
+ })?;
260
+ }
261
+ }
262
+ }
263
+ Ok((current, name))
264
+ }
265
+
266
+ fn parse_path(&self, path: &str) -> (InodeId, Vec<String>) {
267
+ let (start, path_str) = if path.starts_with('/') {
268
+ (self.root, &path[1..])
269
+ } else {
270
+ (self.cwd, path)
271
+ };
272
+ let components: Vec<String> = path_str
273
+ .split('/')
274
+ .filter(|s| !s.is_empty())
275
+ .map(String::from)
276
+ .collect();
277
+ (start, components)
278
+ }
279
+
280
+ fn parent_of(&self, id: InodeId) -> InodeId {
281
+ if id == self.root {
282
+ return self.root;
283
+ }
284
+ for i in (0..self.cwd_path.len()).rev() {
285
+ if self.cwd_path[i].1 == id && i > 0 {
286
+ return self.cwd_path[i - 1].1;
287
+ }
288
+ }
289
+ for inode in self.inodes.values() {
290
+ if let InodeKind::Directory { entries } = &inode.kind {
291
+ if entries.values().any(|&child| child == id) {
292
+ return inode.id;
293
+ }
294
+ }
295
+ }
296
+ self.root
297
+ }
298
+
299
+ /// Determine the gid for a new child in this directory.
300
+ /// If the parent has setgid, inherit parent's gid; otherwise use caller's gid.
301
+ fn effective_gid(&self, parent_id: InodeId, caller_gid: Gid) -> Gid {
302
+ if let Ok(parent) = self.get_inode(parent_id) {
303
+ if has_setgid(parent.mode) {
304
+ return parent.gid;
305
+ }
306
+ }
307
+ caller_gid
308
+ }
309
+
310
+ fn validate_regular_path(&self, path: &str) -> Result<(), VfsError> {
311
+ if self.compatibility_target() == CompatibilityTarget::Posix {
312
+ return Ok(());
313
+ }
314
+ validate_markdown_filename(path)
315
+ }
316
+
317
+ fn mark_accessed(&mut self, id: InodeId) -> Result<(), VfsError> {
318
+ let inode = self.get_inode_mut(id)?;
319
+ inode.touch_access();
320
+ Ok(())
321
+ }
322
+
323
+ fn unlink_inode_if_needed(&mut self, id: InodeId) {
324
+ let open = self
325
+ .handles
326
+ .values()
327
+ .any(|handle| handle.inode_id == id);
328
+ if let Some(inode) = self.inodes.get(&id) {
329
+ if inode.nlink == 0 {
330
+ if open {
331
+ self.pending_delete.insert(id);
332
+ } else {
333
+ self.pending_delete.remove(&id);
334
+ self.inodes.remove(&id);
335
+ }
336
+ }
337
+ }
338
+ }
339
+
340
+ fn release_orphan_if_needed(&mut self, id: InodeId) {
341
+ if !self.pending_delete.contains(&id) {
342
+ return;
343
+ }
344
+ let still_open = self
345
+ .handles
346
+ .values()
347
+ .any(|handle| handle.inode_id == id);
348
+ if !still_open {
349
+ self.pending_delete.remove(&id);
350
+ self.inodes.remove(&id);
351
+ }
352
+ }
353
+
354
+ // ───── Commands ─────
355
+
356
+ pub fn ls(&self, path: Option<&str>) -> Result<Vec<LsEntry>, VfsError> {
357
+ let id = match path {
358
+ Some(p) => self.resolve_path(p)?,
359
+ None => self.cwd,
360
+ };
361
+ let inode = self.get_inode(id)?;
362
+ match &inode.kind {
363
+ InodeKind::Directory { entries } => {
364
+ let mut result = Vec::with_capacity(entries.len());
365
+ for (name, &child_id) in entries {
366
+ let child = self.get_inode(child_id)?;
367
+ result.push(LsEntry {
368
+ name: name.clone(),
369
+ is_dir: child.is_dir(),
370
+ is_symlink: matches!(child.kind, InodeKind::Symlink { .. }),
371
+ size: child.size(),
372
+ mode: child.mode,
373
+ uid: child.uid,
374
+ gid: child.gid,
375
+ modified: child.modified,
376
+ });
377
+ }
378
+ Ok(result)
379
+ }
380
+ InodeKind::File { .. } => Ok(vec![LsEntry {
381
+ name: path.unwrap_or("").to_string(),
382
+ is_dir: false,
383
+ is_symlink: false,
384
+ size: inode.size(),
385
+ mode: inode.mode,
386
+ uid: inode.uid,
387
+ gid: inode.gid,
388
+ modified: inode.modified,
389
+ }]),
390
+ InodeKind::Symlink { .. } => Ok(vec![LsEntry {
391
+ name: path.unwrap_or("").to_string(),
392
+ is_dir: false,
393
+ is_symlink: true,
394
+ size: inode.size(),
395
+ mode: inode.mode,
396
+ uid: inode.uid,
397
+ gid: inode.gid,
398
+ modified: inode.modified,
399
+ }]),
400
+ }
401
+ }
402
+
403
+ pub fn cd(&mut self, path: &str) -> Result<(), VfsError> {
404
+ if path == "/" {
405
+ self.cwd = self.root;
406
+ self.cwd_path.clear();
407
+ return Ok(());
408
+ }
409
+
410
+ let target = self.resolve_path(path)?;
411
+ let inode = self.get_inode(target)?;
412
+ if !inode.is_dir() {
413
+ return Err(VfsError::NotDirectory {
414
+ path: path.to_string(),
415
+ });
416
+ }
417
+
418
+ if path.starts_with('/') {
419
+ self.cwd_path.clear();
420
+ }
421
+
422
+ for component in path.split('/').filter(|s| !s.is_empty()) {
423
+ match component {
424
+ "." => {}
425
+ ".." => {
426
+ self.cwd_path.pop();
427
+ }
428
+ name => {
429
+ let current_dir = self
430
+ .cwd_path
431
+ .last()
432
+ .map(|(_, id)| *id)
433
+ .unwrap_or(self.root);
434
+ let entries = self.dir_entries(current_dir)?;
435
+ if let Some(&child_id) = entries.get(name) {
436
+ self.cwd_path.push((name.to_string(), child_id));
437
+ }
438
+ }
439
+ }
440
+ }
441
+
442
+ self.cwd = target;
443
+ Ok(())
444
+ }
445
+
446
+ pub fn mkdir(&mut self, path: &str, uid: Uid, gid: Gid) -> Result<(), VfsError> {
447
+ let (parent_id, name) = self.resolve_parent(path)?;
448
+
449
+ let entries = self.dir_entries(parent_id)?;
450
+ if entries.contains_key(&name) {
451
+ return Err(VfsError::AlreadyExists {
452
+ path: path.to_string(),
453
+ });
454
+ }
455
+
456
+ let effective_gid = self.effective_gid(parent_id, gid);
457
+ let new_id = self.alloc_id();
458
+ let mut new_dir = Inode::new_dir(new_id, uid, effective_gid);
459
+
460
+ // Inherit setgid bit from parent
461
+ if let Ok(parent) = self.get_inode(parent_id) {
462
+ if has_setgid(parent.mode) {
463
+ new_dir.mode |= 0o2000;
464
+ }
465
+ }
466
+
467
+ self.inodes.insert(new_id, new_dir);
468
+ self.dir_entries_mut(parent_id)?.insert(name, new_id);
469
+ let parent = self.get_inode_mut(parent_id)?;
470
+ parent.nlink += 1;
471
+ parent.touch_change();
472
+ Ok(())
473
+ }
474
+
475
+ pub fn mkdir_p(&mut self, path: &str, uid: Uid, gid: Gid) -> Result<(), VfsError> {
476
+ let (start, components) = self.parse_path(path);
477
+ let mut current = start;
478
+ for component in &components {
479
+ match component.as_str() {
480
+ "." => {}
481
+ ".." => {
482
+ current = self.parent_of(current);
483
+ }
484
+ name => {
485
+ let entries = self.dir_entries(current)?;
486
+ if let Some(&existing) = entries.get(name) {
487
+ if !self.get_inode(existing)?.is_dir() {
488
+ return Err(VfsError::NotDirectory {
489
+ path: name.to_string(),
490
+ });
491
+ }
492
+ current = existing;
493
+ } else {
494
+ let effective_gid = self.effective_gid(current, gid);
495
+ let new_id = self.alloc_id();
496
+ let new_dir = Inode::new_dir(new_id, uid, effective_gid);
497
+ self.inodes.insert(new_id, new_dir);
498
+ self.dir_entries_mut(current)?
499
+ .insert(name.to_string(), new_id);
500
+ let parent = self.get_inode_mut(current)?;
501
+ parent.nlink += 1;
502
+ parent.touch_change();
503
+ current = new_id;
504
+ }
505
+ }
506
+ }
507
+ }
508
+ Ok(())
509
+ }
510
+
511
+ pub fn touch(&mut self, path: &str, uid: Uid, gid: Gid) -> Result<(), VfsError> {
512
+ self.validate_regular_path(path)?;
513
+
514
+ if let Ok(id) = self.resolve_path(path) {
515
+ let inode = self.get_inode_mut(id)?;
516
+ inode.touch_modify();
517
+ return Ok(());
518
+ }
519
+
520
+ let (parent_id, name) = self.resolve_parent(path)?;
521
+ let effective_gid = self.effective_gid(parent_id, gid);
522
+ let new_id = self.alloc_id();
523
+ let new_file = Inode::new_file(new_id, uid, effective_gid);
524
+ self.inodes.insert(new_id, new_file);
525
+ self.dir_entries_mut(parent_id)?.insert(name, new_id);
526
+ Ok(())
527
+ }
528
+
529
+ pub fn create_file(
530
+ &mut self,
531
+ path: &str,
532
+ uid: Uid,
533
+ gid: Gid,
534
+ mode: Option<u16>,
535
+ ) -> Result<InodeId, VfsError> {
536
+ self.validate_regular_path(path)?;
537
+ if self.resolve_path(path).is_ok() {
538
+ return Err(VfsError::AlreadyExists {
539
+ path: path.to_string(),
540
+ });
541
+ }
542
+
543
+ let (parent_id, name) = self.resolve_parent(path)?;
544
+ let effective_gid = self.effective_gid(parent_id, gid);
545
+ let new_id = self.alloc_id();
546
+ let mut new_file = Inode::new_file(new_id, uid, effective_gid);
547
+ if let Some(mode) = mode {
548
+ new_file.mode = mode;
549
+ }
550
+ self.inodes.insert(new_id, new_file);
551
+ self.dir_entries_mut(parent_id)?.insert(name, new_id);
552
+ Ok(new_id)
553
+ }
554
+
555
+ pub fn cat(&self, path: &str) -> Result<&[u8], VfsError> {
556
+ let id = self.resolve_path(path)?;
557
+ let inode = self.get_inode(id)?;
558
+ match &inode.kind {
559
+ InodeKind::File { content } => Ok(content),
560
+ InodeKind::Directory { .. } => Err(VfsError::IsDirectory {
561
+ path: path.to_string(),
562
+ }),
563
+ InodeKind::Symlink { target } => self.cat(target),
564
+ }
565
+ }
566
+
567
+ pub fn cat_owned(&self, path: &str) -> Result<Vec<u8>, VfsError> {
568
+ self.cat(path).map(|b| b.to_vec())
569
+ }
570
+
571
+ pub fn write_file(&mut self, path: &str, content: Vec<u8>) -> Result<(), VfsError> {
572
+ self.validate_regular_path(path)?;
573
+ let id = self.resolve_path(path)?;
574
+ let inode = self.get_inode_mut(id)?;
575
+ match &mut inode.kind {
576
+ InodeKind::File { content: c, .. } => {
577
+ *c = content;
578
+ inode.touch_modify();
579
+ Ok(())
580
+ }
581
+ InodeKind::Directory { .. } => Err(VfsError::IsDirectory {
582
+ path: path.to_string(),
583
+ }),
584
+ InodeKind::Symlink { target } => {
585
+ let target = target.clone();
586
+ self.write_file(&target, content)
587
+ }
588
+ }
589
+ }
590
+
591
+ pub fn read_file_at(
592
+ &mut self,
593
+ path: &str,
594
+ offset: usize,
595
+ size: usize,
596
+ ) -> Result<Vec<u8>, VfsError> {
597
+ let id = self.resolve_path(path)?;
598
+ self.read_inode_at(id, offset, size)
599
+ }
600
+
601
+ pub fn write_file_at(
602
+ &mut self,
603
+ path: &str,
604
+ offset: usize,
605
+ data: &[u8],
606
+ ) -> Result<usize, VfsError> {
607
+ self.validate_regular_path(path)?;
608
+ let id = self.resolve_path(path)?;
609
+ let inode = self.get_inode_mut(id)?;
610
+ match &mut inode.kind {
611
+ InodeKind::File { content } => {
612
+ if offset > content.len() {
613
+ content.resize(offset, 0);
614
+ }
615
+ let end = offset.saturating_add(data.len());
616
+ if end > content.len() {
617
+ content.resize(end, 0);
618
+ }
619
+ content[offset..end].copy_from_slice(data);
620
+ inode.touch_modify();
621
+ Ok(data.len())
622
+ }
623
+ InodeKind::Directory { .. } => Err(VfsError::IsDirectory {
624
+ path: path.to_string(),
625
+ }),
626
+ InodeKind::Symlink { target } => {
627
+ let target = target.clone();
628
+ self.write_file_at(&target, offset, data)
629
+ }
630
+ }
631
+ }
632
+
633
+ pub fn truncate(&mut self, path: &str, size: usize) -> Result<(), VfsError> {
634
+ let id = self.resolve_path(path)?;
635
+ let inode = self.get_inode_mut(id)?;
636
+ match &mut inode.kind {
637
+ InodeKind::File { content } => {
638
+ content.resize(size, 0);
639
+ inode.touch_modify();
640
+ Ok(())
641
+ }
642
+ InodeKind::Directory { .. } => Err(VfsError::IsDirectory {
643
+ path: path.to_string(),
644
+ }),
645
+ InodeKind::Symlink { target } => {
646
+ let target = target.clone();
647
+ self.truncate(&target, size)
648
+ }
649
+ }
650
+ }
651
+
652
+ pub fn rm(&mut self, path: &str) -> Result<(), VfsError> {
653
+ let id = self.resolve_path(path)?;
654
+ let inode = self.get_inode(id)?;
655
+ if inode.is_dir() {
656
+ return Err(VfsError::IsDirectory {
657
+ path: path.to_string(),
658
+ });
659
+ }
660
+
661
+ let (parent_id, name) = self.resolve_parent(path)?;
662
+ self.dir_entries_mut(parent_id)?.remove(&name);
663
+ let inode = self.get_inode_mut(id)?;
664
+ inode.nlink = inode.nlink.saturating_sub(1);
665
+ inode.touch_change();
666
+ self.unlink_inode_if_needed(id);
667
+ Ok(())
668
+ }
669
+
670
+ pub fn rmdir(&mut self, path: &str) -> Result<(), VfsError> {
671
+ let id = self.resolve_path(path)?;
672
+ let inode = self.get_inode(id)?;
673
+ match &inode.kind {
674
+ InodeKind::Directory { entries } => {
675
+ if !entries.is_empty() {
676
+ return Err(VfsError::NotEmpty {
677
+ path: path.to_string(),
678
+ });
679
+ }
680
+ }
681
+ _ => {
682
+ return Err(VfsError::NotDirectory {
683
+ path: path.to_string(),
684
+ })
685
+ }
686
+ }
687
+
688
+ if id == self.root {
689
+ return Err(VfsError::InvalidPath {
690
+ path: "cannot remove root".to_string(),
691
+ });
692
+ }
693
+
694
+ let (parent_id, name) = self.resolve_parent(path)?;
695
+ self.dir_entries_mut(parent_id)?.remove(&name);
696
+ let parent = self.get_inode_mut(parent_id)?;
697
+ parent.nlink = parent.nlink.saturating_sub(1);
698
+ parent.touch_change();
699
+ self.inodes.remove(&id);
700
+ Ok(())
701
+ }
702
+
703
+ pub fn rm_rf(&mut self, path: &str) -> Result<(), VfsError> {
704
+ let id = self.resolve_path(path)?;
705
+ if id == self.root {
706
+ return Err(VfsError::InvalidPath {
707
+ path: "cannot remove root".to_string(),
708
+ });
709
+ }
710
+
711
+ let (parent_id, name) = self.resolve_parent(path)?;
712
+ self.dir_entries_mut(parent_id)?.remove(&name);
713
+ self.remove_inode_recursive(id)?;
714
+ let parent = self.get_inode_mut(parent_id)?;
715
+ parent.touch_change();
716
+ Ok(())
717
+ }
718
+
719
+ fn remove_inode_recursive(&mut self, id: InodeId) -> Result<(), VfsError> {
720
+ let child_entries = match &self.get_inode(id)?.kind {
721
+ InodeKind::Directory { entries } => entries.values().copied().collect::<Vec<_>>(),
722
+ _ => Vec::new(),
723
+ };
724
+
725
+ for child_id in child_entries {
726
+ self.remove_inode_recursive(child_id)?;
727
+ }
728
+
729
+ let nlink = self.get_inode(id)?.nlink;
730
+ if nlink > 0 {
731
+ let inode = self.get_inode_mut(id)?;
732
+ inode.nlink = inode.nlink.saturating_sub(1);
733
+ inode.touch_change();
734
+ }
735
+ self.unlink_inode_if_needed(id);
736
+ Ok(())
737
+ }
738
+
739
+ pub fn mv(&mut self, src: &str, dst: &str) -> Result<(), VfsError> {
740
+ self.rename(src, dst)
741
+ }
742
+
743
+ pub fn rename(&mut self, src: &str, dst: &str) -> Result<(), VfsError> {
744
+ let src_id = self.resolve_path(src)?;
745
+ if src_id == self.root {
746
+ return Err(VfsError::InvalidPath {
747
+ path: "cannot rename root".to_string(),
748
+ });
749
+ }
750
+
751
+ if self.get_inode(src_id)?.is_file() {
752
+ let dst_name = dst.rsplit('/').next().unwrap_or(dst);
753
+ self.validate_regular_path(dst_name)?;
754
+ }
755
+
756
+ let (src_parent, src_name) = self.resolve_parent(src)?;
757
+
758
+ if let Ok(dst_id) = self.resolve_path(dst) {
759
+ if self.get_inode(dst_id)?.is_dir() {
760
+ self.dir_entries_mut(src_parent)?.remove(&src_name);
761
+ self.dir_entries_mut(dst_id)?.insert(src_name, src_id);
762
+ let inode = self.get_inode_mut(src_id)?;
763
+ inode.touch_change();
764
+ return Ok(());
765
+ } else {
766
+ self.rm(dst)?;
767
+ }
768
+ }
769
+
770
+ let (dst_parent, dst_name) = self.resolve_parent(dst)?;
771
+ self.dir_entries_mut(src_parent)?.remove(&src_name);
772
+ self.dir_entries_mut(dst_parent)?.insert(dst_name, src_id);
773
+ let inode = self.get_inode_mut(src_id)?;
774
+ inode.touch_change();
775
+ Ok(())
776
+ }
777
+
778
+ pub fn cp(&mut self, src: &str, dst: &str, uid: Uid, gid: Gid) -> Result<(), VfsError> {
779
+ let src_id = self.resolve_path(src)?;
780
+ let src_inode = self.get_inode(src_id)?.clone();
781
+
782
+ if src_inode.is_dir() {
783
+ return Err(VfsError::IsDirectory {
784
+ path: src.to_string(),
785
+ });
786
+ }
787
+
788
+ let dst_name = dst.rsplit('/').next().unwrap_or(dst);
789
+ if src_inode.is_file() {
790
+ self.validate_regular_path(dst_name)?;
791
+ }
792
+
793
+ let (parent_id, name) = if let Ok(dst_id) = self.resolve_path(dst) {
794
+ if self.get_inode(dst_id)?.is_dir() {
795
+ let src_name = src.rsplit('/').next().unwrap_or(src);
796
+ (dst_id, src_name.to_string())
797
+ } else {
798
+ self.resolve_parent(dst)?
799
+ }
800
+ } else {
801
+ self.resolve_parent(dst)?
802
+ };
803
+
804
+ let new_id = self.alloc_id();
805
+ let mut new_inode = src_inode;
806
+ new_inode.id = new_id;
807
+ new_inode.uid = uid; // Copy is owned by the caller
808
+ new_inode.gid = self.effective_gid(parent_id, gid);
809
+ new_inode.nlink = 1;
810
+ new_inode.touch_change();
811
+ self.inodes.insert(new_id, new_inode);
812
+ self.dir_entries_mut(parent_id)?.insert(name, new_id);
813
+ Ok(())
814
+ }
815
+
816
+ pub fn stat(&self, path: &str) -> Result<StatInfo, VfsError> {
817
+ let id = self.resolve_path(path)?;
818
+ let inode = self.get_inode(id)?;
819
+ Ok(StatInfo {
820
+ inode_id: id,
821
+ kind: match &inode.kind {
822
+ InodeKind::File { .. } => "file",
823
+ InodeKind::Directory { .. } => "directory",
824
+ InodeKind::Symlink { .. } => "symlink",
825
+ },
826
+ size: inode.size(),
827
+ mode: inode.mode,
828
+ uid: inode.uid,
829
+ gid: inode.gid,
830
+ nlink: inode.nlink,
831
+ block_size: inode.block_size,
832
+ blocks: inode.blocks(),
833
+ created: inode.created_at.secs,
834
+ modified: inode.modified_at.secs,
835
+ accessed: inode.accessed_at.secs,
836
+ changed: inode.changed_at.secs,
837
+ created_nanos: inode.created_at.nanos,
838
+ modified_nanos: inode.modified_at.nanos,
839
+ accessed_nanos: inode.accessed_at.nanos,
840
+ changed_nanos: inode.changed_at.nanos,
841
+ })
842
+ }
843
+
844
+ pub fn chmod(&mut self, path: &str, mode: u16) -> Result<(), VfsError> {
845
+ let id = self.resolve_path(path)?;
846
+ let inode = self.get_inode_mut(id)?;
847
+ inode.mode = mode;
848
+ inode.touch_change();
849
+ Ok(())
850
+ }
851
+
852
+ pub fn chown(&mut self, path: &str, uid: Uid, gid: Gid) -> Result<(), VfsError> {
853
+ let id = self.resolve_path(path)?;
854
+ let inode = self.get_inode_mut(id)?;
855
+ inode.uid = uid;
856
+ inode.gid = gid;
857
+ inode.touch_change();
858
+ Ok(())
859
+ }
860
+
861
+ pub fn ln_s(&mut self, target: &str, link_path: &str, uid: Uid, gid: Gid) -> Result<(), VfsError> {
862
+ let (parent_id, name) = self.resolve_parent(link_path)?;
863
+ let entries = self.dir_entries(parent_id)?;
864
+ if entries.contains_key(&name) {
865
+ return Err(VfsError::AlreadyExists {
866
+ path: link_path.to_string(),
867
+ });
868
+ }
869
+
870
+ let effective_gid = self.effective_gid(parent_id, gid);
871
+ let new_id = self.alloc_id();
872
+ let symlink = Inode::new_symlink(new_id, target.to_string(), uid, effective_gid);
873
+ self.inodes.insert(new_id, symlink);
874
+ self.dir_entries_mut(parent_id)?.insert(name, new_id);
875
+ Ok(())
876
+ }
877
+
878
+ pub fn link(&mut self, target: &str, link_path: &str) -> Result<(), VfsError> {
879
+ let target_id = self.resolve_path(target)?;
880
+ if self.get_inode(target_id)?.is_dir() {
881
+ return Err(VfsError::NotSupported {
882
+ message: "hard links to directories".to_string(),
883
+ });
884
+ }
885
+ let (parent_id, name) = self.resolve_parent(link_path)?;
886
+ if self.dir_entries(parent_id)?.contains_key(&name) {
887
+ return Err(VfsError::AlreadyExists {
888
+ path: link_path.to_string(),
889
+ });
890
+ }
891
+ self.dir_entries_mut(parent_id)?.insert(name, target_id);
892
+ let inode = self.get_inode_mut(target_id)?;
893
+ inode.nlink += 1;
894
+ inode.touch_change();
895
+ Ok(())
896
+ }
897
+
898
+ pub fn readlink(&self, path: &str) -> Result<String, VfsError> {
899
+ let id = self.resolve_path(path)?;
900
+ let inode = self.get_inode(id)?;
901
+ match &inode.kind {
902
+ InodeKind::Symlink { target } => Ok(target.clone()),
903
+ _ => Err(VfsError::InvalidArgs {
904
+ message: format!("not a symlink: {path}"),
905
+ }),
906
+ }
907
+ }
908
+
909
+ pub fn open(&mut self, path: &str, writable: bool) -> Result<HandleId, VfsError> {
910
+ let inode_id = self.resolve_path(path)?;
911
+ let directory = self.get_inode(inode_id)?.is_dir();
912
+ let handle_id = self.alloc_handle_id();
913
+ self.handles.insert(
914
+ handle_id,
915
+ OpenHandle {
916
+ inode_id,
917
+ cursor: 0,
918
+ writable,
919
+ directory,
920
+ },
921
+ );
922
+ self.mark_accessed(inode_id)?;
923
+ Ok(handle_id)
924
+ }
925
+
926
+ pub fn opendir(&mut self, path: &str) -> Result<HandleId, VfsError> {
927
+ let inode_id = self.resolve_path(path)?;
928
+ if !self.get_inode(inode_id)?.is_dir() {
929
+ return Err(VfsError::NotDirectory {
930
+ path: path.to_string(),
931
+ });
932
+ }
933
+ self.open(path, false)
934
+ }
935
+
936
+ pub fn release_handle(&mut self, handle: HandleId) -> Result<(), VfsError> {
937
+ let open = self
938
+ .handles
939
+ .remove(&handle)
940
+ .ok_or(VfsError::InvalidHandle { handle })?;
941
+ self.release_orphan_if_needed(open.inode_id);
942
+ Ok(())
943
+ }
944
+
945
+ pub fn read_handle(&mut self, handle: HandleId, size: usize) -> Result<Vec<u8>, VfsError> {
946
+ let (inode_id, cursor) = {
947
+ let open = self
948
+ .handles
949
+ .get(&handle)
950
+ .ok_or(VfsError::InvalidHandle { handle })?;
951
+ if open.directory {
952
+ return Err(VfsError::IsDirectory {
953
+ path: format!("<handle {handle}>"),
954
+ });
955
+ }
956
+ (open.inode_id, open.cursor)
957
+ };
958
+
959
+ let data = self.read_inode_at(inode_id, cursor, size)?;
960
+ if let Some(open) = self.handles.get_mut(&handle) {
961
+ open.cursor = open.cursor.saturating_add(data.len());
962
+ }
963
+ Ok(data)
964
+ }
965
+
966
+ pub fn write_handle(&mut self, handle: HandleId, data: &[u8]) -> Result<usize, VfsError> {
967
+ let (inode_id, cursor, writable) = {
968
+ let open = self
969
+ .handles
970
+ .get(&handle)
971
+ .ok_or(VfsError::InvalidHandle { handle })?;
972
+ (open.inode_id, open.cursor, open.writable)
973
+ };
974
+ if !writable {
975
+ return Err(VfsError::PermissionDenied {
976
+ path: format!("<handle {handle}>"),
977
+ });
978
+ }
979
+ let written = self.write_inode_at(inode_id, cursor, data)?;
980
+ if let Some(open) = self.handles.get_mut(&handle) {
981
+ open.cursor = open.cursor.saturating_add(written);
982
+ }
983
+ Ok(written)
984
+ }
985
+
986
+ fn write_inode_at(
987
+ &mut self,
988
+ inode_id: InodeId,
989
+ offset: usize,
990
+ data: &[u8],
991
+ ) -> Result<usize, VfsError> {
992
+ let inode = self.get_inode_mut(inode_id)?;
993
+ match &mut inode.kind {
994
+ InodeKind::File { content } => {
995
+ if offset > content.len() {
996
+ content.resize(offset, 0);
997
+ }
998
+ let end = offset.saturating_add(data.len());
999
+ if end > content.len() {
1000
+ content.resize(end, 0);
1001
+ }
1002
+ content[offset..end].copy_from_slice(data);
1003
+ inode.touch_modify();
1004
+ Ok(data.len())
1005
+ }
1006
+ InodeKind::Directory { .. } => Err(VfsError::IsDirectory {
1007
+ path: format!("<inode {inode_id}>"),
1008
+ }),
1009
+ InodeKind::Symlink { target } => {
1010
+ let target = target.clone();
1011
+ self.write_file_at(&target, offset, data)
1012
+ }
1013
+ }
1014
+ }
1015
+
1016
+ fn read_inode_at(
1017
+ &mut self,
1018
+ inode_id: InodeId,
1019
+ offset: usize,
1020
+ size: usize,
1021
+ ) -> Result<Vec<u8>, VfsError> {
1022
+ let inode = self.get_inode_mut(inode_id)?;
1023
+ match &mut inode.kind {
1024
+ InodeKind::File { content } => {
1025
+ let start = offset.min(content.len());
1026
+ let end = start.saturating_add(size).min(content.len());
1027
+ let out = content[start..end].to_vec();
1028
+ inode.touch_access();
1029
+ Ok(out)
1030
+ }
1031
+ InodeKind::Directory { .. } => Err(VfsError::IsDirectory {
1032
+ path: format!("<inode {inode_id}>"),
1033
+ }),
1034
+ InodeKind::Symlink { target } => {
1035
+ let target = target.clone();
1036
+ self.read_file_at(&target, offset, size)
1037
+ }
1038
+ }
1039
+ }
1040
+
1041
+ pub fn tree(
1042
+ &self,
1043
+ path: Option<&str>,
1044
+ prefix: &str,
1045
+ session: Option<&Session>,
1046
+ ) -> Result<String, VfsError> {
1047
+ let id = match path {
1048
+ Some(p) => self.resolve_path(p)?,
1049
+ None => self.cwd,
1050
+ };
1051
+ let mut output = String::new();
1052
+ if prefix.is_empty() {
1053
+ output.push_str(".\n");
1054
+ }
1055
+ self.tree_recursive(id, prefix, &mut output, session)?;
1056
+ Ok(output)
1057
+ }
1058
+
1059
+ fn tree_recursive(
1060
+ &self,
1061
+ id: InodeId,
1062
+ prefix: &str,
1063
+ output: &mut String,
1064
+ session: Option<&Session>,
1065
+ ) -> Result<(), VfsError> {
1066
+ let entries = self.dir_entries(id)?;
1067
+ // Filter entries by read permission
1068
+ let visible: Vec<_> = entries
1069
+ .iter()
1070
+ .filter(|&(_, child_id)| self.is_visible(*child_id, session))
1071
+ .collect();
1072
+ let count = visible.len();
1073
+ for (i, (name, child_id)) in visible.iter().enumerate() {
1074
+ let is_last = i == count - 1;
1075
+ let connector = if is_last {
1076
+ "\u{2514}\u{2500}\u{2500} "
1077
+ } else {
1078
+ "\u{251c}\u{2500}\u{2500} "
1079
+ };
1080
+ let child = self.get_inode(**child_id)?;
1081
+
1082
+ output.push_str(prefix);
1083
+ output.push_str(connector);
1084
+ output.push_str(name);
1085
+ if child.is_dir() {
1086
+ output.push('/');
1087
+ }
1088
+ output.push('\n');
1089
+
1090
+ if child.is_dir() {
1091
+ let new_prefix = if is_last {
1092
+ format!("{prefix} ")
1093
+ } else {
1094
+ format!("{prefix}\u{2502} ")
1095
+ };
1096
+ self.tree_recursive(**child_id, &new_prefix, output, session)?;
1097
+ }
1098
+ }
1099
+ Ok(())
1100
+ }
1101
+
1102
+ pub fn find(
1103
+ &self,
1104
+ path: Option<&str>,
1105
+ pattern: Option<&str>,
1106
+ session: Option<&Session>,
1107
+ ) -> Result<Vec<String>, VfsError> {
1108
+ let id = match path {
1109
+ Some(p) => self.resolve_path(p)?,
1110
+ None => self.cwd,
1111
+ };
1112
+ let base = match path {
1113
+ Some(p) => p.to_string(),
1114
+ None => ".".to_string(),
1115
+ };
1116
+ let mut results = Vec::new();
1117
+ self.find_recursive(id, &base, pattern, &mut results, session)?;
1118
+ Ok(results)
1119
+ }
1120
+
1121
+ fn find_recursive(
1122
+ &self,
1123
+ id: InodeId,
1124
+ current_path: &str,
1125
+ pattern: Option<&str>,
1126
+ results: &mut Vec<String>,
1127
+ session: Option<&Session>,
1128
+ ) -> Result<(), VfsError> {
1129
+ let entries = self.dir_entries(id)?;
1130
+ for (name, &child_id) in entries {
1131
+ if !self.is_visible(child_id, session) {
1132
+ continue;
1133
+ }
1134
+
1135
+ let child_path = if current_path == "." {
1136
+ format!("./{name}")
1137
+ } else {
1138
+ format!("{current_path}/{name}")
1139
+ };
1140
+ let child = self.get_inode(child_id)?;
1141
+
1142
+ let matches = match pattern {
1143
+ Some(pat) => glob_match(pat, name),
1144
+ None => true,
1145
+ };
1146
+
1147
+ if matches {
1148
+ results.push(child_path.clone());
1149
+ }
1150
+
1151
+ if child.is_dir() {
1152
+ self.find_recursive(child_id, &child_path, pattern, results, session)?;
1153
+ }
1154
+ }
1155
+ Ok(())
1156
+ }
1157
+
1158
+ pub fn grep(
1159
+ &self,
1160
+ pattern: &str,
1161
+ path: Option<&str>,
1162
+ recursive: bool,
1163
+ session: Option<&Session>,
1164
+ ) -> Result<Vec<GrepResult>, VfsError> {
1165
+ let re = regex::Regex::new(pattern).map_err(|e| VfsError::InvalidArgs {
1166
+ message: format!("invalid regex: {e}"),
1167
+ })?;
1168
+
1169
+ let id = match path {
1170
+ Some(p) => self.resolve_path(p)?,
1171
+ None => self.cwd,
1172
+ };
1173
+ let base = path.unwrap_or(".");
1174
+ let mut results = Vec::new();
1175
+ let inode = self.get_inode(id)?;
1176
+
1177
+ match &inode.kind {
1178
+ InodeKind::File { content } => {
1179
+ let text = String::from_utf8_lossy(content);
1180
+ for (line_num, line) in text.lines().enumerate() {
1181
+ if re.is_match(line) {
1182
+ results.push(GrepResult {
1183
+ file: base.to_string(),
1184
+ line_num: line_num + 1,
1185
+ line: line.to_string(),
1186
+ });
1187
+ }
1188
+ }
1189
+ }
1190
+ InodeKind::Directory { .. } if recursive => {
1191
+ self.grep_recursive(id, base, &re, &mut results, session)?;
1192
+ }
1193
+ InodeKind::Directory { .. } => {
1194
+ return Err(VfsError::IsDirectory {
1195
+ path: base.to_string(),
1196
+ });
1197
+ }
1198
+ _ => {}
1199
+ }
1200
+ Ok(results)
1201
+ }
1202
+
1203
+ fn grep_recursive(
1204
+ &self,
1205
+ id: InodeId,
1206
+ base: &str,
1207
+ re: &regex::Regex,
1208
+ results: &mut Vec<GrepResult>,
1209
+ session: Option<&Session>,
1210
+ ) -> Result<(), VfsError> {
1211
+ let entries = self.dir_entries(id)?;
1212
+ for (name, &child_id) in entries {
1213
+ if !self.is_visible(child_id, session) {
1214
+ continue;
1215
+ }
1216
+
1217
+ let child_path = if base == "." {
1218
+ format!("./{name}")
1219
+ } else {
1220
+ format!("{base}/{name}")
1221
+ };
1222
+ let child = self.get_inode(child_id)?;
1223
+ match &child.kind {
1224
+ InodeKind::File { content } => {
1225
+ let text = String::from_utf8_lossy(content);
1226
+ for (line_num, line) in text.lines().enumerate() {
1227
+ if re.is_match(line) {
1228
+ results.push(GrepResult {
1229
+ file: child_path.clone(),
1230
+ line_num: line_num + 1,
1231
+ line: line.to_string(),
1232
+ });
1233
+ }
1234
+ }
1235
+ }
1236
+ InodeKind::Directory { .. } => {
1237
+ self.grep_recursive(child_id, &child_path, re, results, session)?;
1238
+ }
1239
+ _ => {}
1240
+ }
1241
+ }
1242
+ Ok(())
1243
+ }
1244
+
1245
+ /// Check if a user can see this inode (has read permission).
1246
+ /// If session is None, everything is visible (internal/root use).
1247
+ /// Respects delegation: both principal and delegate must have read access.
1248
+ fn is_visible(&self, id: InodeId, session: Option<&Session>) -> bool {
1249
+ let session = match session {
1250
+ Some(s) => s,
1251
+ None => return true,
1252
+ };
1253
+ let inode = match self.get_inode(id) {
1254
+ Ok(i) => i,
1255
+ Err(_) => return false,
1256
+ };
1257
+ session.has_permission(inode, Access::Read)
1258
+ }
1259
+
1260
+ pub fn all_inodes(&self) -> &HashMap<InodeId, Inode> {
1261
+ &self.inodes
1262
+ }
1263
+
1264
+ pub fn root_id(&self) -> InodeId {
1265
+ self.root
1266
+ }
1267
+
1268
+ pub fn cwd_id(&self) -> InodeId {
1269
+ self.cwd
1270
+ }
1271
+
1272
+ pub fn next_inode_id(&self) -> InodeId {
1273
+ self.next_id
1274
+ }
1275
+
1276
+ pub fn cwd_path_clone(&self) -> Vec<(String, InodeId)> {
1277
+ self.cwd_path.clone()
1278
+ }
1279
+
1280
+ pub fn from_persisted(
1281
+ inodes: HashMap<InodeId, Inode>,
1282
+ root: InodeId,
1283
+ cwd: InodeId,
1284
+ next_id: InodeId,
1285
+ cwd_path: Vec<(String, InodeId)>,
1286
+ options: FsOptions,
1287
+ registry: UserRegistry,
1288
+ ) -> Self {
1289
+ VirtualFs {
1290
+ inodes,
1291
+ root,
1292
+ cwd,
1293
+ next_id,
1294
+ cwd_path,
1295
+ options,
1296
+ next_handle: 1,
1297
+ handles: HashMap::new(),
1298
+ pending_delete: HashSet::new(),
1299
+ registry,
1300
+ }
1301
+ }
1302
+ }
1303
+
1304
+ fn glob_match(pattern: &str, name: &str) -> bool {
1305
+ let pat = pattern
1306
+ .replace('.', "\\.")
1307
+ .replace('*', ".*")
1308
+ .replace('?', ".");
1309
+ regex::Regex::new(&format!("^{pat}$"))
1310
+ .map(|re| re.is_match(name))
1311
+ .unwrap_or(false)
1312
+ }
1313
+
1314
+ fn validate_markdown_filename(path: &str) -> Result<(), VfsError> {
1315
+ let filename = path.rsplit('/').next().unwrap_or(path);
1316
+ if !filename.ends_with(".md") {
1317
+ return Err(VfsError::InvalidExtension {
1318
+ name: filename.to_string(),
1319
+ });
1320
+ }
1321
+ Ok(())
1322
+ }
1323
+
1324
+ #[derive(Debug)]
1325
+ pub struct LsEntry {
1326
+ pub name: String,
1327
+ pub is_dir: bool,
1328
+ pub is_symlink: bool,
1329
+ pub size: u64,
1330
+ pub mode: u16,
1331
+ pub uid: u32,
1332
+ pub gid: u32,
1333
+ pub modified: u64,
1334
+ }
1335
+
1336
+ #[derive(Debug, Clone)]
1337
+ pub struct StatInfo {
1338
+ pub inode_id: InodeId,
1339
+ pub kind: &'static str,
1340
+ pub size: u64,
1341
+ pub mode: u16,
1342
+ pub uid: u32,
1343
+ pub gid: u32,
1344
+ pub nlink: u64,
1345
+ pub block_size: u64,
1346
+ pub blocks: u64,
1347
+ pub created: u64,
1348
+ pub modified: u64,
1349
+ pub accessed: u64,
1350
+ pub changed: u64,
1351
+ pub created_nanos: u32,
1352
+ pub modified_nanos: u32,
1353
+ pub accessed_nanos: u32,
1354
+ pub changed_nanos: u32,
1355
+ }
1356
+
1357
+ #[derive(Debug, Clone)]
1358
+ pub struct GrepResult {
1359
+ pub file: String,
1360
+ pub line_num: usize,
1361
+ pub line: String,
1362
+ }
src/fuse_mount.rs ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![cfg(feature = "fuser")]
2
+
3
+ use crate::auth::session::Session;
4
+ use crate::fs::inode::InodeKind;
5
+ use crate::fs::VirtualFs;
6
+ use crate::posix::{PosixFs, PosixSetAttr};
7
+ use fuser::{
8
+ BsdFileFlags, Config, Errno, FileAttr, FileHandle, FileType, Filesystem, FopenFlags,
9
+ Generation, INodeNo, KernelConfig, MountOption, OpenAccMode, OpenFlags, RenameFlags,
10
+ ReplyAttr, ReplyCreate, ReplyData, ReplyDirectory, ReplyEmpty, ReplyEntry, ReplyOpen,
11
+ ReplyWrite, Request, TimeOrNow, WriteFlags,
12
+ };
13
+ use std::ffi::OsStr;
14
+ use std::io;
15
+ use std::path::{Path, PathBuf};
16
+ use std::sync::{Arc, Mutex};
17
+ use std::time::{Duration, SystemTime, UNIX_EPOCH};
18
+
19
+ const TTL: Duration = Duration::from_secs(1);
20
+
21
+ pub struct MarkdownFsFuse {
22
+ fs: Arc<Mutex<VirtualFs>>,
23
+ }
24
+
25
+ impl MarkdownFsFuse {
26
+ pub fn new(fs: Arc<Mutex<VirtualFs>>) -> Self {
27
+ Self { fs }
28
+ }
29
+
30
+ pub fn mount_config(read_only: bool) -> Config {
31
+ let mut mount_options = vec![
32
+ MountOption::FSName("markdownfs".to_string()),
33
+ MountOption::Subtype("markdownfs".to_string()),
34
+ MountOption::DefaultPermissions,
35
+ ];
36
+ if read_only {
37
+ mount_options.push(MountOption::RO);
38
+ } else {
39
+ mount_options.push(MountOption::RW);
40
+ }
41
+ let mut config = Config::default();
42
+ config.mount_options = mount_options;
43
+ config
44
+ }
45
+
46
+ fn session_for(req: &Request) -> Session {
47
+ Session::new(req.uid(), req.gid(), vec![req.gid()], format!("uid-{}", req.uid()))
48
+ }
49
+
50
+ fn path_for_inode(fs: &VirtualFs, ino: INodeNo) -> Option<String> {
51
+ if ino.0 == fs.root_id() {
52
+ return Some("/".to_string());
53
+ }
54
+ fn walk(
55
+ fs: &VirtualFs,
56
+ current: u64,
57
+ current_path: &str,
58
+ target: INodeNo,
59
+ ) -> Option<String> {
60
+ let inode = fs.get_inode(current).ok()?;
61
+ let InodeKind::Directory { entries } = &inode.kind else {
62
+ return None;
63
+ };
64
+
65
+ for (name, child) in entries {
66
+ let child_path = if current_path == "/" {
67
+ format!("/{name}")
68
+ } else {
69
+ format!("{current_path}/{name}")
70
+ };
71
+ if *child == target.0 {
72
+ return Some(child_path);
73
+ }
74
+ if let Some(found) = walk(fs, *child, &child_path, target) {
75
+ return Some(found);
76
+ }
77
+ }
78
+ None
79
+ }
80
+
81
+ walk(fs, fs.root_id(), "/", ino)
82
+ }
83
+
84
+ fn child_path(fs: &VirtualFs, parent: INodeNo, name: &OsStr) -> Option<String> {
85
+ let parent_path = Self::path_for_inode(fs, parent)?;
86
+ let name = name.to_str()?;
87
+ Some(if parent_path == "/" {
88
+ format!("/{name}")
89
+ } else {
90
+ format!("{parent_path}/{name}")
91
+ })
92
+ }
93
+
94
+ }
95
+
96
+ impl Filesystem for MarkdownFsFuse {
97
+ fn init(&mut self, _req: &Request, _config: &mut KernelConfig) -> io::Result<()> {
98
+ Ok(())
99
+ }
100
+
101
+ fn lookup(&self, req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEntry) {
102
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
103
+ let Some(path) = Self::child_path(&guard, parent, name) else {
104
+ reply.error(Errno::ENOENT);
105
+ return;
106
+ };
107
+ let session = Self::session_for(req);
108
+ let posix = PosixFs::new(&mut guard, &session);
109
+ match posix.lookup(&path).map(|stat| stat_to_attr(&stat)) {
110
+ Ok(attr) => reply.entry(&TTL, &attr, Generation(0)),
111
+ Err(err) => reply.error(map_error(err)),
112
+ }
113
+ }
114
+
115
+ fn getattr(&self, req: &Request, ino: INodeNo, _fh: Option<FileHandle>, reply: ReplyAttr) {
116
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
117
+ let Some(path) = Self::path_for_inode(&guard, ino) else {
118
+ reply.error(Errno::ENOENT);
119
+ return;
120
+ };
121
+ let session = Self::session_for(req);
122
+ let posix = PosixFs::new(&mut guard, &session);
123
+ match posix.getattr(&path).map(|stat| stat_to_attr(&stat)) {
124
+ Ok(attr) => reply.attr(&TTL, &attr),
125
+ Err(err) => reply.error(map_error(err)),
126
+ }
127
+ }
128
+
129
+ fn readlink(&self, req: &Request, ino: INodeNo, reply: ReplyData) {
130
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
131
+ let Some(path) = Self::path_for_inode(&guard, ino) else {
132
+ reply.error(Errno::ENOENT);
133
+ return;
134
+ };
135
+ let session = Self::session_for(req);
136
+ let posix = PosixFs::new(&mut guard, &session);
137
+ match posix.readlink(&path) {
138
+ Ok(target) => reply.data(target.as_bytes()),
139
+ Err(err) => reply.error(map_error(err)),
140
+ }
141
+ }
142
+
143
+ fn mkdir(
144
+ &self,
145
+ req: &Request,
146
+ parent: INodeNo,
147
+ name: &OsStr,
148
+ mode: u32,
149
+ _umask: u32,
150
+ reply: ReplyEntry,
151
+ ) {
152
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
153
+ let Some(path) = Self::child_path(&guard, parent, name) else {
154
+ reply.error(Errno::EINVAL);
155
+ return;
156
+ };
157
+ let session = Self::session_for(req);
158
+ let mut posix = PosixFs::new(&mut guard, &session);
159
+ match posix
160
+ .mkdir(&path, mode as u16)
161
+ .and_then(|_| posix.getattr(&path))
162
+ .map(|stat| stat_to_attr(&stat))
163
+ {
164
+ Ok(attr) => reply.entry(&TTL, &attr, Generation(0)),
165
+ Err(err) => reply.error(map_error(err)),
166
+ }
167
+ }
168
+
169
+ fn create(
170
+ &self,
171
+ req: &Request,
172
+ parent: INodeNo,
173
+ name: &OsStr,
174
+ mode: u32,
175
+ _umask: u32,
176
+ _flags: i32,
177
+ reply: ReplyCreate,
178
+ ) {
179
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
180
+ let Some(path) = Self::child_path(&guard, parent, name) else {
181
+ reply.error(Errno::EINVAL);
182
+ return;
183
+ };
184
+ let session = Self::session_for(req);
185
+ let mut posix = PosixFs::new(&mut guard, &session);
186
+ match posix.create(&path, mode as u16).and_then(|_| posix.getattr(&path)) {
187
+ Ok(stat) => reply.created(
188
+ &TTL,
189
+ &stat_to_attr(&stat),
190
+ Generation(0),
191
+ FileHandle(0),
192
+ FopenFlags::empty(),
193
+ ),
194
+ Err(err) => reply.error(map_error(err)),
195
+ }
196
+ }
197
+
198
+ fn open(&self, req: &Request, ino: INodeNo, flags: OpenFlags, reply: ReplyOpen) {
199
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
200
+ let Some(path) = Self::path_for_inode(&guard, ino) else {
201
+ reply.error(Errno::ENOENT);
202
+ return;
203
+ };
204
+ let writable = matches!(flags.acc_mode(), OpenAccMode::O_WRONLY | OpenAccMode::O_RDWR);
205
+ let session = Self::session_for(req);
206
+ let mut posix = PosixFs::new(&mut guard, &session);
207
+ match posix.open(&path, writable) {
208
+ Ok(_fh) => reply.opened(FileHandle(0), FopenFlags::empty()),
209
+ Err(err) => reply.error(map_error(err)),
210
+ }
211
+ }
212
+
213
+ fn read(
214
+ &self,
215
+ req: &Request,
216
+ ino: INodeNo,
217
+ _fh: FileHandle,
218
+ offset: u64,
219
+ size: u32,
220
+ _flags: OpenFlags,
221
+ _lock_owner: Option<fuser::LockOwner>,
222
+ reply: ReplyData,
223
+ ) {
224
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
225
+ let Some(path) = Self::path_for_inode(&guard, ino) else {
226
+ reply.error(Errno::ENOENT);
227
+ return;
228
+ };
229
+ let session = Self::session_for(req);
230
+ let mut posix = PosixFs::new(&mut guard, &session);
231
+ match posix.read(&path, offset as usize, size as usize) {
232
+ Ok(data) => reply.data(&data),
233
+ Err(err) => reply.error(map_error(err)),
234
+ }
235
+ }
236
+
237
+ fn write(
238
+ &self,
239
+ req: &Request,
240
+ ino: INodeNo,
241
+ _fh: FileHandle,
242
+ offset: u64,
243
+ data: &[u8],
244
+ _write_flags: WriteFlags,
245
+ _flags: OpenFlags,
246
+ _lock_owner: Option<fuser::LockOwner>,
247
+ reply: ReplyWrite,
248
+ ) {
249
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
250
+ let Some(path) = Self::path_for_inode(&guard, ino) else {
251
+ reply.error(Errno::ENOENT);
252
+ return;
253
+ };
254
+ let session = Self::session_for(req);
255
+ let mut posix = PosixFs::new(&mut guard, &session);
256
+ match posix.write(&path, offset as usize, data) {
257
+ Ok(written) => reply.written(written as u32),
258
+ Err(err) => reply.error(map_error(err)),
259
+ }
260
+ }
261
+
262
+ fn release(
263
+ &self,
264
+ _req: &Request,
265
+ _ino: INodeNo,
266
+ _fh: FileHandle,
267
+ _flags: OpenFlags,
268
+ _lock_owner: Option<fuser::LockOwner>,
269
+ _flush: bool,
270
+ reply: ReplyEmpty,
271
+ ) {
272
+ reply.ok();
273
+ }
274
+
275
+ fn unlink(&self, req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {
276
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
277
+ let Some(path) = Self::child_path(&guard, parent, name) else {
278
+ reply.error(Errno::EINVAL);
279
+ return;
280
+ };
281
+ let session = Self::session_for(req);
282
+ let mut posix = PosixFs::new(&mut guard, &session);
283
+ match posix.unlink(&path) {
284
+ Ok(()) => reply.ok(),
285
+ Err(err) => reply.error(map_error(err)),
286
+ }
287
+ }
288
+
289
+ fn rmdir(&self, req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {
290
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
291
+ let Some(path) = Self::child_path(&guard, parent, name) else {
292
+ reply.error(Errno::EINVAL);
293
+ return;
294
+ };
295
+ let session = Self::session_for(req);
296
+ let mut posix = PosixFs::new(&mut guard, &session);
297
+ match posix.rmdir(&path) {
298
+ Ok(()) => reply.ok(),
299
+ Err(err) => reply.error(map_error(err)),
300
+ }
301
+ }
302
+
303
+ fn rename(
304
+ &self,
305
+ req: &Request,
306
+ parent: INodeNo,
307
+ name: &OsStr,
308
+ newparent: INodeNo,
309
+ newname: &OsStr,
310
+ _flags: RenameFlags,
311
+ reply: ReplyEmpty,
312
+ ) {
313
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
314
+ let Some(src) = Self::child_path(&guard, parent, name) else {
315
+ reply.error(Errno::EINVAL);
316
+ return;
317
+ };
318
+ let Some(dst) = Self::child_path(&guard, newparent, newname) else {
319
+ reply.error(Errno::EINVAL);
320
+ return;
321
+ };
322
+ let session = Self::session_for(req);
323
+ let mut posix = PosixFs::new(&mut guard, &session);
324
+ match posix.rename(&src, &dst) {
325
+ Ok(()) => reply.ok(),
326
+ Err(err) => reply.error(map_error(err)),
327
+ }
328
+ }
329
+
330
+ fn symlink(
331
+ &self,
332
+ req: &Request,
333
+ parent: INodeNo,
334
+ link_name: &OsStr,
335
+ target: &Path,
336
+ reply: ReplyEntry,
337
+ ) {
338
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
339
+ let Some(path) = Self::child_path(&guard, parent, link_name) else {
340
+ reply.error(Errno::EINVAL);
341
+ return;
342
+ };
343
+ let target = target.to_string_lossy().into_owned();
344
+ let session = Self::session_for(req);
345
+ let mut posix = PosixFs::new(&mut guard, &session);
346
+ match posix
347
+ .symlink(&target, &path)
348
+ .and_then(|_| posix.getattr(&path))
349
+ .map(|stat| stat_to_attr(&stat))
350
+ {
351
+ Ok(attr) => reply.entry(&TTL, &attr, Generation(0)),
352
+ Err(err) => reply.error(map_error(err)),
353
+ }
354
+ }
355
+
356
+ fn link(
357
+ &self,
358
+ req: &Request,
359
+ ino: INodeNo,
360
+ newparent: INodeNo,
361
+ newname: &OsStr,
362
+ reply: ReplyEntry,
363
+ ) {
364
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
365
+ let Some(target) = Self::path_for_inode(&guard, ino) else {
366
+ reply.error(Errno::ENOENT);
367
+ return;
368
+ };
369
+ let Some(path) = Self::child_path(&guard, newparent, newname) else {
370
+ reply.error(Errno::EINVAL);
371
+ return;
372
+ };
373
+ let session = Self::session_for(req);
374
+ let mut posix = PosixFs::new(&mut guard, &session);
375
+ match posix
376
+ .link(&target, &path)
377
+ .and_then(|_| posix.getattr(&path))
378
+ .map(|stat| stat_to_attr(&stat))
379
+ {
380
+ Ok(attr) => reply.entry(&TTL, &attr, Generation(0)),
381
+ Err(err) => reply.error(map_error(err)),
382
+ }
383
+ }
384
+
385
+ fn setattr(
386
+ &self,
387
+ req: &Request,
388
+ ino: INodeNo,
389
+ mode: Option<u32>,
390
+ uid: Option<u32>,
391
+ gid: Option<u32>,
392
+ size: Option<u64>,
393
+ _atime: Option<TimeOrNow>,
394
+ _mtime: Option<TimeOrNow>,
395
+ _ctime: Option<SystemTime>,
396
+ _fh: Option<FileHandle>,
397
+ _crtime: Option<SystemTime>,
398
+ _chgtime: Option<SystemTime>,
399
+ _bkuptime: Option<SystemTime>,
400
+ _flags: Option<BsdFileFlags>,
401
+ reply: ReplyAttr,
402
+ ) {
403
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
404
+ let Some(path) = Self::path_for_inode(&guard, ino) else {
405
+ reply.error(Errno::ENOENT);
406
+ return;
407
+ };
408
+ let session = Self::session_for(req);
409
+ let mut posix = PosixFs::new(&mut guard, &session);
410
+ match posix
411
+ .setattr(
412
+ &path,
413
+ PosixSetAttr {
414
+ mode: mode.map(|mode| mode as u16),
415
+ uid,
416
+ gid,
417
+ size: size.map(|size| size as usize),
418
+ },
419
+ )
420
+ .map(|stat| stat_to_attr(&stat))
421
+ {
422
+ Ok(attr) => reply.attr(&TTL, &attr),
423
+ Err(err) => reply.error(map_error(err)),
424
+ }
425
+ }
426
+
427
+ fn readdir(
428
+ &self,
429
+ req: &Request,
430
+ ino: INodeNo,
431
+ _fh: FileHandle,
432
+ offset: u64,
433
+ mut reply: ReplyDirectory,
434
+ ) {
435
+ let mut guard = self.fs.lock().expect("fuse mutex poisoned");
436
+ let Some(path) = Self::path_for_inode(&guard, ino) else {
437
+ reply.error(Errno::ENOENT);
438
+ return;
439
+ };
440
+ let session = Self::session_for(req);
441
+ let posix = PosixFs::new(&mut guard, &session);
442
+ match posix.readdir(&path) {
443
+ Ok(entries) => {
444
+ if offset == 0 {
445
+ let _ = reply.add(ino, 1, FileType::Directory, ".");
446
+ let parent_ino = if path == "/" {
447
+ ino
448
+ } else {
449
+ let parent_path = Path::new(&path)
450
+ .parent()
451
+ .map(|p| p.to_string_lossy().into_owned())
452
+ .unwrap_or_else(|| "/".to_string());
453
+ let parent_path = if parent_path.is_empty() {
454
+ "/".to_string()
455
+ } else {
456
+ parent_path
457
+ };
458
+ guard
459
+ .stat(&parent_path)
460
+ .map(|stat| INodeNo(stat.inode_id))
461
+ .unwrap_or(ino)
462
+ };
463
+ let _ = reply.add(parent_ino, 2, FileType::Directory, "..");
464
+ }
465
+ let start = offset.saturating_sub(2) as usize;
466
+ for (entry_index, entry) in entries.into_iter().enumerate().skip(start) {
467
+ let full = (entry_index + 3) as u64;
468
+ let full_type = file_type(entry.stat.kind);
469
+ if reply.add(INodeNo(entry.stat.inode_id), full, full_type, entry.name) {
470
+ break;
471
+ }
472
+ }
473
+ reply.ok();
474
+ }
475
+ Err(err) => reply.error(map_error(err)),
476
+ }
477
+ }
478
+ }
479
+
480
+ fn stat_to_attr(stat: &crate::fs::StatInfo) -> FileAttr {
481
+ let atime = UNIX_EPOCH + Duration::new(stat.accessed, stat.accessed_nanos);
482
+ let mtime = UNIX_EPOCH + Duration::new(stat.modified, stat.modified_nanos);
483
+ let ctime = UNIX_EPOCH + Duration::new(stat.changed, stat.changed_nanos);
484
+ let crtime = UNIX_EPOCH + Duration::new(stat.created, stat.created_nanos);
485
+
486
+ FileAttr {
487
+ ino: INodeNo(stat.inode_id),
488
+ size: stat.size,
489
+ blocks: stat.blocks,
490
+ atime,
491
+ mtime,
492
+ ctime,
493
+ crtime,
494
+ kind: file_type(stat.kind),
495
+ perm: stat.mode,
496
+ nlink: stat.nlink as u32,
497
+ uid: stat.uid,
498
+ gid: stat.gid,
499
+ rdev: 0,
500
+ blksize: stat.block_size as u32,
501
+ flags: 0,
502
+ }
503
+ }
504
+
505
+ fn file_type(kind: &str) -> FileType {
506
+ match kind {
507
+ "directory" => FileType::Directory,
508
+ "symlink" => FileType::Symlink,
509
+ _ => FileType::RegularFile,
510
+ }
511
+ }
512
+
513
+ fn map_error(err: crate::error::VfsError) -> Errno {
514
+ match err {
515
+ crate::error::VfsError::NotFound { .. } => Errno::ENOENT,
516
+ crate::error::VfsError::PermissionDenied { .. } => Errno::EACCES,
517
+ crate::error::VfsError::AlreadyExists { .. } => Errno::EEXIST,
518
+ crate::error::VfsError::NotDirectory { .. } => Errno::ENOTDIR,
519
+ crate::error::VfsError::IsDirectory { .. } => Errno::EISDIR,
520
+ crate::error::VfsError::NotEmpty { .. } => Errno::ENOTEMPTY,
521
+ _ => Errno::EINVAL,
522
+ }
523
+ }
524
+
525
+ pub fn mount(fs: Arc<Mutex<VirtualFs>>, mountpoint: PathBuf, read_only: bool) -> Result<(), std::io::Error> {
526
+ let config = MarkdownFsFuse::mount_config(read_only);
527
+ fuser::mount2(MarkdownFsFuse::new(fs), mountpoint, &config)
528
+ }
src/io/mmap_reader.rs ADDED
@@ -0,0 +1 @@
 
 
1
+ // Memory-mapped reader — Phase 3 implementation.
src/io/mod.rs ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ pub mod mmap_reader;
2
+ pub mod writer;
3
+
4
+ // I/O module — will be fleshed out in Phase 3 with mmap-backed storage.
src/io/writer.rs ADDED
@@ -0,0 +1 @@
 
 
1
+ // Buffered append writer — Phase 3 implementation.
src/lib.rs ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pub mod auth;
2
+ pub mod cmd;
3
+ pub mod config;
4
+ pub mod db;
5
+ pub mod error;
6
+ pub mod fs;
7
+ pub mod io;
8
+ pub mod persist;
9
+ pub mod posix;
10
+ pub mod server;
11
+ pub mod store;
12
+ pub mod vcs;
13
+
14
+ #[cfg(feature = "fuser")]
15
+ pub mod fuse_mount;
src/main.rs ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use markdownfs::auth::session::Session;
2
+ use markdownfs::config::{CompatibilityTarget, Config};
3
+ use markdownfs::db::MarkdownDb;
4
+ use rustyline::error::ReadlineError;
5
+ use rustyline::DefaultEditor;
6
+
7
+ #[tokio::main]
8
+ async fn main() {
9
+ let config = Config::from_env();
10
+ let db = match MarkdownDb::open(config) {
11
+ Ok(db) => {
12
+ let commits = db.commit_count().await;
13
+ let objects = db.object_count().await;
14
+ if commits > 0 {
15
+ println!(
16
+ "markdownfs v{} — Loaded from disk ({commits} commits, {objects} objects)",
17
+ env!("CARGO_PKG_VERSION")
18
+ );
19
+ } else {
20
+ println!(
21
+ "markdownfs v{} — Markdown Virtual File System",
22
+ env!("CARGO_PKG_VERSION")
23
+ );
24
+ }
25
+ db
26
+ }
27
+ Err(e) => {
28
+ eprintln!("Warning: failed to load state: {e}");
29
+ eprintln!("Starting fresh.\n");
30
+ MarkdownDb::open_memory()
31
+ }
32
+ };
33
+
34
+ let _save_handle = db.spawn_auto_save();
35
+
36
+ let mut rl = DefaultEditor::new().expect("failed to initialize readline");
37
+ let history_path = std::env::var("HOME")
38
+ .ok()
39
+ .map(|h| format!("{h}/.markdownfs_history"));
40
+
41
+ if let Some(ref path) = history_path {
42
+ let _ = rl.load_history(path);
43
+ }
44
+
45
+ let mut session = login_flow(&db, &mut rl).await;
46
+ println!("\nType 'help' for available commands, 'exit' to quit.\n");
47
+
48
+ loop {
49
+ let pwd = db.pwd().await;
50
+ let home_prefix = format!("/home/{}", session.username);
51
+ let display_pwd = if pwd == home_prefix {
52
+ "~".to_string()
53
+ } else if let Some(rest) = pwd.strip_prefix(&home_prefix) {
54
+ format!("~{rest}")
55
+ } else {
56
+ pwd
57
+ };
58
+ let prompt = format!("{}@markdownfs:{display_pwd} $ ", session.username);
59
+ match rl.readline(&prompt) {
60
+ Ok(line) => {
61
+ let line = line.trim();
62
+ if line.is_empty() {
63
+ continue;
64
+ }
65
+
66
+ let _ = rl.add_history_entry(line);
67
+
68
+ match line {
69
+ "exit" | "quit" => break,
70
+ _ if line.starts_with("edit ") => {
71
+ handle_edit(line, &db, &mut rl, &session).await;
72
+ }
73
+ _ => match db.execute_command(line, &mut session).await {
74
+ Ok(output) => {
75
+ if !output.is_empty() {
76
+ print!("{output}");
77
+ }
78
+ }
79
+ Err(e) => eprintln!("{e}"),
80
+ },
81
+ }
82
+ }
83
+ Err(ReadlineError::Interrupted) => {
84
+ println!("^C");
85
+ }
86
+ Err(ReadlineError::Eof) => break,
87
+ Err(e) => {
88
+ eprintln!("readline error: {e}");
89
+ break;
90
+ }
91
+ }
92
+ }
93
+
94
+ match db.save().await {
95
+ Ok(()) => {
96
+ let info = db.persist_info();
97
+ match info.location {
98
+ Some(dir) => println!("State saved via {} to {}/", info.backend, dir.display()),
99
+ None => println!("State saved via {}", info.backend),
100
+ }
101
+ }
102
+ Err(e) => eprintln!("Warning: failed to save state: {e}"),
103
+ }
104
+
105
+ if let Some(ref path) = history_path {
106
+ let _ = rl.save_history(path);
107
+ }
108
+
109
+ println!("Goodbye!");
110
+ }
111
+
112
+ async fn login_flow(db: &MarkdownDb, rl: &mut DefaultEditor) -> Session {
113
+ let has_users = db.has_users().await;
114
+
115
+ if !has_users {
116
+ println!("\nWelcome! Let's set up your account.");
117
+ loop {
118
+ match rl.readline("Admin username: ") {
119
+ Ok(name) => {
120
+ let name = name.trim().to_string();
121
+ if name.is_empty() {
122
+ eprintln!("Username cannot be empty.");
123
+ continue;
124
+ }
125
+ match db.create_admin(&name).await {
126
+ Ok(session) => {
127
+ println!(
128
+ "\nCreated admin '{}' (uid={}, groups=[{}, wheel])",
129
+ session.username, session.uid, session.username
130
+ );
131
+ println!("Home directory: /home/{}", session.username);
132
+ return session;
133
+ }
134
+ Err(e) => eprintln!("{e}"),
135
+ }
136
+ }
137
+ Err(ReadlineError::Interrupted | ReadlineError::Eof) => {
138
+ return Session::root();
139
+ }
140
+ Err(e) => {
141
+ eprintln!("readline error: {e}");
142
+ return Session::root();
143
+ }
144
+ }
145
+ }
146
+ } else {
147
+ loop {
148
+ match rl.readline("Login as: ") {
149
+ Ok(name) => {
150
+ let name = name.trim().to_string();
151
+ if name.is_empty() {
152
+ continue;
153
+ }
154
+ match db.login(&name).await {
155
+ Ok(session) => {
156
+ println!(
157
+ "Logged in as '{}' (uid={}, gid={})",
158
+ session.username, session.uid, session.gid
159
+ );
160
+ return session;
161
+ }
162
+ Err(_) => eprintln!("Unknown user: {name}"),
163
+ }
164
+ }
165
+ Err(ReadlineError::Interrupted | ReadlineError::Eof) => {
166
+ return Session::root();
167
+ }
168
+ Err(e) => {
169
+ eprintln!("readline error: {e}");
170
+ return Session::root();
171
+ }
172
+ }
173
+ }
174
+ }
175
+ }
176
+
177
+ async fn handle_edit(
178
+ line: &str,
179
+ db: &MarkdownDb,
180
+ rl: &mut DefaultEditor,
181
+ session: &Session,
182
+ ) {
183
+ let path = line.strip_prefix("edit ").unwrap().trim();
184
+
185
+ if path.is_empty() {
186
+ eprintln!("markdownfs: edit: missing file path");
187
+ return;
188
+ }
189
+
190
+ if db.config().compatibility_target != CompatibilityTarget::Posix && !path.ends_with(".md") {
191
+ eprintln!("markdownfs: only .md files are supported: '{path}'");
192
+ return;
193
+ }
194
+
195
+ if let Ok(content) = db.cat(path).await {
196
+ let text = String::from_utf8_lossy(&content);
197
+ if !text.is_empty() {
198
+ println!("--- Current content of {path} ---");
199
+ for (i, line) in text.lines().enumerate() {
200
+ println!("{:>4} | {line}", i + 1);
201
+ }
202
+ println!("--- End ---");
203
+ }
204
+ }
205
+
206
+ println!("Enter new content (type EOF on a blank line to finish, CANCEL to abort):");
207
+
208
+ let mut content = String::new();
209
+ let mut line_num = 1;
210
+ loop {
211
+ match rl.readline(&format!("{line_num:>4} | ")) {
212
+ Ok(input) => {
213
+ if input.trim() == "EOF" {
214
+ break;
215
+ }
216
+ if input.trim() == "CANCEL" {
217
+ println!("Edit cancelled.");
218
+ return;
219
+ }
220
+ content.push_str(&input);
221
+ content.push('\n');
222
+ line_num += 1;
223
+ }
224
+ Err(ReadlineError::Interrupted) => {
225
+ println!("\nEdit cancelled.");
226
+ return;
227
+ }
228
+ Err(ReadlineError::Eof) => break,
229
+ Err(e) => {
230
+ eprintln!("readline error: {e}");
231
+ return;
232
+ }
233
+ }
234
+ }
235
+
236
+ if content.ends_with('\n') {
237
+ content.pop();
238
+ }
239
+
240
+ if db.stat(path).await.is_err() {
241
+ if let Err(e) = db.touch(path, session.uid, session.gid).await {
242
+ eprintln!("{e}");
243
+ return;
244
+ }
245
+ }
246
+
247
+ if let Err(e) = db.write_file(path, content.into_bytes()).await {
248
+ eprintln!("{e}");
249
+ return;
250
+ }
251
+
252
+ match db.commit(&format!("edit {path}"), &session.username).await {
253
+ Ok(hash) => println!("[{hash}] edit {path}"),
254
+ Err(e) => eprintln!("auto-commit failed: {e}"),
255
+ }
256
+ }
src/persist.rs ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::auth::registry::UserRegistry;
2
+ use crate::config::CompatibilityTarget;
3
+ use crate::error::VfsError;
4
+ use crate::fs::inode::{Inode, InodeId};
5
+ use crate::fs::{FsOptions, VirtualFs};
6
+ use crate::store::blob::BlobStore;
7
+ use crate::store::commit::CommitObject;
8
+ use crate::store::ObjectId;
9
+ use crate::vcs::Vcs;
10
+ use serde::{Deserialize, Serialize};
11
+ use std::collections::HashMap;
12
+ use std::fs;
13
+ use std::path::{Path, PathBuf};
14
+
15
+ const VFS_DIR: &str = ".vfs";
16
+ const STATE_FILE: &str = "state.bin";
17
+ const VERSION: u32 = 3;
18
+
19
+ /// Complete persisted state of the VFS + VCS.
20
+ #[derive(Serialize, Deserialize)]
21
+ struct PersistedState {
22
+ version: u32,
23
+ fs_state: FsState,
24
+ vcs_state: VcsState,
25
+ }
26
+
27
+ #[derive(Serialize, Deserialize)]
28
+ struct FsState {
29
+ inodes: HashMap<InodeId, Inode>,
30
+ root: InodeId,
31
+ cwd: InodeId,
32
+ next_id: InodeId,
33
+ cwd_path: Vec<(String, InodeId)>,
34
+ compatibility_target: CompatibilityTarget,
35
+ registry: UserRegistry,
36
+ }
37
+
38
+ #[derive(Serialize, Deserialize)]
39
+ struct VcsState {
40
+ /// All objects in the blob store: (ObjectId bytes, kind byte, data)
41
+ objects: Vec<(Vec<u8>, u8, Vec<u8>)>,
42
+ head: Option<Vec<u8>>,
43
+ commits: Vec<CommitObject>,
44
+ }
45
+
46
+ // ─── V1 legacy types for migration ───
47
+
48
+ #[derive(Deserialize)]
49
+ struct PersistedStateV1 {
50
+ version: u32,
51
+ fs_state: FsStateV1,
52
+ vcs_state: VcsState,
53
+ }
54
+
55
+ #[derive(Deserialize)]
56
+ struct FsStateV1 {
57
+ inodes: HashMap<InodeId, Inode>,
58
+ root: InodeId,
59
+ cwd: InodeId,
60
+ next_id: InodeId,
61
+ cwd_path: Vec<(String, InodeId)>,
62
+ // No registry in V1
63
+ }
64
+
65
+ #[derive(Deserialize)]
66
+ struct PersistedStateV2 {
67
+ version: u32,
68
+ fs_state: FsStateV2,
69
+ vcs_state: VcsState,
70
+ }
71
+
72
+ #[derive(Deserialize)]
73
+ struct FsStateV2 {
74
+ inodes: HashMap<InodeId, Inode>,
75
+ root: InodeId,
76
+ cwd: InodeId,
77
+ next_id: InodeId,
78
+ cwd_path: Vec<(String, InodeId)>,
79
+ registry: UserRegistry,
80
+ }
81
+
82
+ pub struct PersistManager {
83
+ base_dir: PathBuf,
84
+ }
85
+
86
+ pub struct LoadedState {
87
+ pub fs: VirtualFs,
88
+ pub vcs: Vcs,
89
+ }
90
+
91
+ #[derive(Debug, Clone)]
92
+ pub struct PersistenceInfo {
93
+ pub backend: &'static str,
94
+ pub location: Option<PathBuf>,
95
+ }
96
+
97
+ pub trait PersistenceBackend: Send + Sync {
98
+ fn load(&self) -> Result<Option<LoadedState>, VfsError>;
99
+ fn save(&self, vfs: &VirtualFs, vcs: &Vcs) -> Result<(), VfsError>;
100
+ fn info(&self) -> PersistenceInfo;
101
+ }
102
+
103
+ pub struct LocalStateBackend {
104
+ manager: PersistManager,
105
+ }
106
+
107
+ impl LocalStateBackend {
108
+ pub fn new(base_dir: &Path) -> Self {
109
+ Self {
110
+ manager: PersistManager::new(base_dir),
111
+ }
112
+ }
113
+ }
114
+
115
+ pub struct MemoryPersistenceBackend;
116
+
117
+ impl PersistenceBackend for LocalStateBackend {
118
+ fn load(&self) -> Result<Option<LoadedState>, VfsError> {
119
+ if !self.manager.state_exists() {
120
+ return Ok(None);
121
+ }
122
+ let (fs, vcs) = self.manager.load()?;
123
+ Ok(Some(LoadedState { fs, vcs }))
124
+ }
125
+
126
+ fn save(&self, vfs: &VirtualFs, vcs: &Vcs) -> Result<(), VfsError> {
127
+ self.manager.save(vfs, vcs)
128
+ }
129
+
130
+ fn info(&self) -> PersistenceInfo {
131
+ PersistenceInfo {
132
+ backend: "local-state-file",
133
+ location: Some(self.manager.data_dir().to_path_buf()),
134
+ }
135
+ }
136
+ }
137
+
138
+ impl PersistenceBackend for MemoryPersistenceBackend {
139
+ fn load(&self) -> Result<Option<LoadedState>, VfsError> {
140
+ Ok(None)
141
+ }
142
+
143
+ fn save(&self, _vfs: &VirtualFs, _vcs: &Vcs) -> Result<(), VfsError> {
144
+ Ok(())
145
+ }
146
+
147
+ fn info(&self) -> PersistenceInfo {
148
+ PersistenceInfo {
149
+ backend: "memory",
150
+ location: None,
151
+ }
152
+ }
153
+ }
154
+
155
+ impl PersistManager {
156
+ pub fn new(base_dir: &Path) -> Self {
157
+ PersistManager {
158
+ base_dir: base_dir.join(VFS_DIR),
159
+ }
160
+ }
161
+
162
+ pub fn state_exists(&self) -> bool {
163
+ self.base_dir.join(STATE_FILE).exists()
164
+ }
165
+
166
+ pub fn save(&self, vfs: &VirtualFs, vcs: &Vcs) -> Result<(), VfsError> {
167
+ fs::create_dir_all(&self.base_dir)?;
168
+
169
+ let fs_state = FsState {
170
+ inodes: vfs.all_inodes().clone(),
171
+ root: vfs.root_id(),
172
+ cwd: vfs.cwd_id(),
173
+ next_id: vfs.next_inode_id(),
174
+ cwd_path: vfs.cwd_path_clone(),
175
+ compatibility_target: vfs.compatibility_target(),
176
+ registry: vfs.registry.clone(),
177
+ };
178
+
179
+ let vcs_state = VcsState {
180
+ objects: vcs.store.export_all(),
181
+ head: vcs.head.map(|id| id.as_bytes().to_vec()),
182
+ commits: vcs.commits.clone(),
183
+ };
184
+
185
+ let state = PersistedState {
186
+ version: VERSION,
187
+ fs_state,
188
+ vcs_state,
189
+ };
190
+
191
+ let data = bincode::serialize(&state).map_err(|e| VfsError::CorruptStore {
192
+ message: format!("serialization failed: {e}"),
193
+ })?;
194
+
195
+ let tmp_path = self.base_dir.join("state.tmp");
196
+ let final_path = self.base_dir.join(STATE_FILE);
197
+
198
+ // Atomic write: write to tmp, then rename
199
+ fs::write(&tmp_path, &data)?;
200
+ fs::rename(&tmp_path, &final_path)?;
201
+
202
+ Ok(())
203
+ }
204
+
205
+ pub fn load(&self) -> Result<(VirtualFs, Vcs), VfsError> {
206
+ let path = self.base_dir.join(STATE_FILE);
207
+ let data = fs::read(&path)?;
208
+
209
+ // Try V3 first
210
+ if let Ok(state) = bincode::deserialize::<PersistedState>(&data) {
211
+ if state.version == VERSION {
212
+ return Self::load_v3(state);
213
+ }
214
+ }
215
+
216
+ // Try V2 migration
217
+ if let Ok(state) = bincode::deserialize::<PersistedStateV2>(&data) {
218
+ if state.version == 2 {
219
+ return Self::load_v2(state);
220
+ }
221
+ }
222
+
223
+ // Try V1 migration
224
+ if let Ok(state) = bincode::deserialize::<PersistedStateV1>(&data) {
225
+ if state.version == 1 {
226
+ return Self::load_v1(state);
227
+ }
228
+ }
229
+
230
+ Err(VfsError::CorruptStore {
231
+ message: "failed to deserialize state (unknown version or corrupt data)".to_string(),
232
+ })
233
+ }
234
+
235
+ fn load_v3(state: PersistedState) -> Result<(VirtualFs, Vcs), VfsError> {
236
+ let vfs = VirtualFs::from_persisted(
237
+ state.fs_state.inodes,
238
+ state.fs_state.root,
239
+ state.fs_state.cwd,
240
+ state.fs_state.next_id,
241
+ state.fs_state.cwd_path,
242
+ FsOptions {
243
+ compatibility_target: state.fs_state.compatibility_target,
244
+ },
245
+ state.fs_state.registry,
246
+ );
247
+
248
+ let vcs = Self::load_vcs(state.vcs_state)?;
249
+ Ok((vfs, vcs))
250
+ }
251
+
252
+ fn load_v2(state: PersistedStateV2) -> Result<(VirtualFs, Vcs), VfsError> {
253
+ let vfs = VirtualFs::from_persisted(
254
+ state.fs_state.inodes,
255
+ state.fs_state.root,
256
+ state.fs_state.cwd,
257
+ state.fs_state.next_id,
258
+ state.fs_state.cwd_path,
259
+ FsOptions::default(),
260
+ state.fs_state.registry,
261
+ );
262
+
263
+ let vcs = Self::load_vcs(state.vcs_state)?;
264
+ Ok((vfs, vcs))
265
+ }
266
+
267
+ fn load_v1(state: PersistedStateV1) -> Result<(VirtualFs, Vcs), VfsError> {
268
+ // V1 inodes already have uid/gid=0 defaults from serde (they were added with defaults)
269
+ // Create a fresh registry (root user only)
270
+ let registry = UserRegistry::new();
271
+
272
+ let vfs = VirtualFs::from_persisted(
273
+ state.fs_state.inodes,
274
+ state.fs_state.root,
275
+ state.fs_state.cwd,
276
+ state.fs_state.next_id,
277
+ state.fs_state.cwd_path,
278
+ FsOptions::default(),
279
+ registry,
280
+ );
281
+
282
+ let vcs = Self::load_vcs(state.vcs_state)?;
283
+ Ok((vfs, vcs))
284
+ }
285
+
286
+ fn load_vcs(vcs_state: VcsState) -> Result<Vcs, VfsError> {
287
+ let mut store = BlobStore::new();
288
+ store.import_all(vcs_state.objects)?;
289
+
290
+ let head = match vcs_state.head {
291
+ Some(bytes) => {
292
+ let mut arr = [0u8; 32];
293
+ arr.copy_from_slice(&bytes);
294
+ Some(ObjectId::from_raw(arr))
295
+ }
296
+ None => None,
297
+ };
298
+
299
+ Ok(Vcs {
300
+ store,
301
+ head,
302
+ commits: vcs_state.commits,
303
+ })
304
+ }
305
+
306
+ pub fn data_dir(&self) -> &Path {
307
+ &self.base_dir
308
+ }
309
+ }
src/posix.rs ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::auth::perms::Access;
2
+ use crate::auth::session::Session;
3
+ use crate::auth::{Gid, Uid};
4
+ use crate::error::VfsError;
5
+ use crate::fs::{HandleId, LsEntry, StatInfo, VirtualFs};
6
+
7
+ #[derive(Debug, Clone)]
8
+ pub struct PosixDirEntry {
9
+ pub name: String,
10
+ pub stat: StatInfo,
11
+ }
12
+
13
+ #[derive(Debug, Default, Clone, Copy)]
14
+ pub struct PosixSetAttr {
15
+ pub mode: Option<u16>,
16
+ pub uid: Option<Uid>,
17
+ pub gid: Option<Gid>,
18
+ pub size: Option<usize>,
19
+ }
20
+
21
+ pub struct PosixFs<'a> {
22
+ fs: &'a mut VirtualFs,
23
+ session: &'a Session,
24
+ }
25
+
26
+ impl<'a> PosixFs<'a> {
27
+ pub fn new(fs: &'a mut VirtualFs, session: &'a Session) -> Self {
28
+ Self { fs, session }
29
+ }
30
+
31
+ pub fn getattr(&self, path: &str) -> Result<StatInfo, VfsError> {
32
+ let _ = self.fs.resolve_path_checked(path, self.session)?;
33
+ self.fs.stat(path)
34
+ }
35
+
36
+ pub fn lookup(&self, path: &str) -> Result<StatInfo, VfsError> {
37
+ self.getattr(path)
38
+ }
39
+
40
+ pub fn opendir(&mut self, path: &str) -> Result<HandleId, VfsError> {
41
+ let dir_id = self.fs.resolve_path_checked(path, self.session)?;
42
+ require_access(self.fs, dir_id, self.session, Access::Read, path)?;
43
+ require_access(self.fs, dir_id, self.session, Access::Execute, path)?;
44
+ self.fs.opendir(path)
45
+ }
46
+
47
+ pub fn readdir(&self, path: &str) -> Result<Vec<PosixDirEntry>, VfsError> {
48
+ let dir_id = self.fs.resolve_path_checked(path, self.session)?;
49
+ require_access(self.fs, dir_id, self.session, Access::Read, path)?;
50
+ require_access(self.fs, dir_id, self.session, Access::Execute, path)?;
51
+
52
+ let entries = self.fs.ls(Some(path))?;
53
+ let mut results = Vec::new();
54
+ for entry in entries {
55
+ if !self.can_see(&entry) {
56
+ continue;
57
+ }
58
+ let child_path = join_paths(path, &entry.name);
59
+ results.push(PosixDirEntry {
60
+ name: entry.name,
61
+ stat: self.fs.stat(&child_path)?,
62
+ });
63
+ }
64
+ Ok(results)
65
+ }
66
+
67
+ pub fn open(&mut self, path: &str, writable: bool) -> Result<HandleId, VfsError> {
68
+ let inode_id = self.fs.resolve_path_checked(path, self.session)?;
69
+ let access = if writable { Access::Write } else { Access::Read };
70
+ require_access(self.fs, inode_id, self.session, access, path)?;
71
+ self.fs.open(path, writable)
72
+ }
73
+
74
+ pub fn create(&mut self, path: &str, mode: u16) -> Result<HandleId, VfsError> {
75
+ let (parent_id, _) = self.fs.resolve_parent_checked(path, self.session)?;
76
+ require_access(self.fs, parent_id, self.session, Access::Write, path)?;
77
+ require_access(self.fs, parent_id, self.session, Access::Execute, path)?;
78
+ self.fs.create_file(
79
+ path,
80
+ self.session.effective_uid(),
81
+ self.session.effective_gid(),
82
+ Some(mode),
83
+ )?;
84
+ self.fs.open(path, true)
85
+ }
86
+
87
+ pub fn mkdir(&mut self, path: &str, mode: u16) -> Result<(), VfsError> {
88
+ let (parent_id, _) = self.fs.resolve_parent_checked(path, self.session)?;
89
+ require_access(self.fs, parent_id, self.session, Access::Write, path)?;
90
+ require_access(self.fs, parent_id, self.session, Access::Execute, path)?;
91
+ self.fs
92
+ .mkdir(path, self.session.effective_uid(), self.session.effective_gid())?;
93
+ self.fs.chmod(path, mode)
94
+ }
95
+
96
+ pub fn read(&mut self, path: &str, offset: usize, size: usize) -> Result<Vec<u8>, VfsError> {
97
+ let inode_id = self.fs.resolve_path_checked(path, self.session)?;
98
+ require_access(self.fs, inode_id, self.session, Access::Read, path)?;
99
+ self.fs.read_file_at(path, offset, size)
100
+ }
101
+
102
+ pub fn write(&mut self, path: &str, offset: usize, data: &[u8]) -> Result<usize, VfsError> {
103
+ let inode_id = self.fs.resolve_path_checked(path, self.session)?;
104
+ require_access(self.fs, inode_id, self.session, Access::Write, path)?;
105
+ self.fs.write_file_at(path, offset, data)
106
+ }
107
+
108
+ pub fn read_handle(&mut self, handle: HandleId, size: usize) -> Result<Vec<u8>, VfsError> {
109
+ self.fs.read_handle(handle, size)
110
+ }
111
+
112
+ pub fn write_handle(&mut self, handle: HandleId, data: &[u8]) -> Result<usize, VfsError> {
113
+ self.fs.write_handle(handle, data)
114
+ }
115
+
116
+ pub fn release(&mut self, handle: HandleId) -> Result<(), VfsError> {
117
+ self.fs.release_handle(handle)
118
+ }
119
+
120
+ pub fn truncate(&mut self, path: &str, size: usize) -> Result<(), VfsError> {
121
+ let inode_id = self.fs.resolve_path_checked(path, self.session)?;
122
+ require_access(self.fs, inode_id, self.session, Access::Write, path)?;
123
+ self.fs.truncate(path, size)
124
+ }
125
+
126
+ pub fn setattr(&mut self, path: &str, attr: PosixSetAttr) -> Result<StatInfo, VfsError> {
127
+ let inode_id = self.fs.resolve_path_checked(path, self.session)?;
128
+ let (current_uid, current_gid) = {
129
+ let inode = self.fs.get_inode(inode_id)?;
130
+ (inode.uid, inode.gid)
131
+ };
132
+
133
+ if let Some(mode) = attr.mode {
134
+ if !self.session.is_effective_owner(current_uid) {
135
+ return Err(VfsError::PermissionDenied {
136
+ path: path.to_string(),
137
+ });
138
+ }
139
+ self.fs.chmod(path, mode)?;
140
+ }
141
+
142
+ if let Some(uid) = attr.uid {
143
+ if !self.session.is_effectively_root() {
144
+ return Err(VfsError::PermissionDenied {
145
+ path: path.to_string(),
146
+ });
147
+ }
148
+ let gid = attr.gid.unwrap_or(current_gid);
149
+ self.fs.chown(path, uid, gid)?;
150
+ } else if let Some(gid) = attr.gid {
151
+ if !self.session.is_effective_owner(current_uid) && !self.session.is_effectively_root() {
152
+ return Err(VfsError::PermissionDenied {
153
+ path: path.to_string(),
154
+ });
155
+ }
156
+ self.fs.chown(path, current_uid, gid)?;
157
+ }
158
+
159
+ if let Some(size) = attr.size {
160
+ require_access(self.fs, inode_id, self.session, Access::Write, path)?;
161
+ self.fs.truncate(path, size)?;
162
+ }
163
+
164
+ self.fs.stat(path)
165
+ }
166
+
167
+ pub fn unlink(&mut self, path: &str) -> Result<(), VfsError> {
168
+ let (parent_id, _) = self.fs.resolve_parent_checked(path, self.session)?;
169
+ require_access(self.fs, parent_id, self.session, Access::Write, path)?;
170
+ require_access(self.fs, parent_id, self.session, Access::Execute, path)?;
171
+ self.fs.rm(path)
172
+ }
173
+
174
+ pub fn rmdir(&mut self, path: &str) -> Result<(), VfsError> {
175
+ let (parent_id, _) = self.fs.resolve_parent_checked(path, self.session)?;
176
+ require_access(self.fs, parent_id, self.session, Access::Write, path)?;
177
+ require_access(self.fs, parent_id, self.session, Access::Execute, path)?;
178
+ self.fs.rmdir(path)
179
+ }
180
+
181
+ pub fn rename(&mut self, src: &str, dst: &str) -> Result<(), VfsError> {
182
+ let (src_parent, _) = self.fs.resolve_parent_checked(src, self.session)?;
183
+ require_access(self.fs, src_parent, self.session, Access::Write, src)?;
184
+ require_access(self.fs, src_parent, self.session, Access::Execute, src)?;
185
+
186
+ if let Ok((dst_parent, _)) = self.fs.resolve_parent_checked(dst, self.session) {
187
+ require_access(self.fs, dst_parent, self.session, Access::Write, dst)?;
188
+ require_access(self.fs, dst_parent, self.session, Access::Execute, dst)?;
189
+ }
190
+
191
+ self.fs.rename(src, dst)
192
+ }
193
+
194
+ pub fn symlink(&mut self, target: &str, link_path: &str) -> Result<(), VfsError> {
195
+ let (parent_id, _) = self.fs.resolve_parent_checked(link_path, self.session)?;
196
+ require_access(self.fs, parent_id, self.session, Access::Write, link_path)?;
197
+ require_access(self.fs, parent_id, self.session, Access::Execute, link_path)?;
198
+ self.fs.ln_s(
199
+ target,
200
+ link_path,
201
+ self.session.effective_uid(),
202
+ self.session.effective_gid(),
203
+ )
204
+ }
205
+
206
+ pub fn link(&mut self, target: &str, link_path: &str) -> Result<(), VfsError> {
207
+ let target_id = self.fs.resolve_path_checked(target, self.session)?;
208
+ require_access(self.fs, target_id, self.session, Access::Read, target)?;
209
+ let (parent_id, _) = self.fs.resolve_parent_checked(link_path, self.session)?;
210
+ require_access(self.fs, parent_id, self.session, Access::Write, link_path)?;
211
+ require_access(self.fs, parent_id, self.session, Access::Execute, link_path)?;
212
+ self.fs.link(target, link_path)
213
+ }
214
+
215
+ pub fn readlink(&self, path: &str) -> Result<String, VfsError> {
216
+ let inode_id = self.fs.resolve_path_checked(path, self.session)?;
217
+ require_access(self.fs, inode_id, self.session, Access::Read, path)?;
218
+ self.fs.readlink(path)
219
+ }
220
+
221
+ fn can_see(&self, entry: &LsEntry) -> bool {
222
+ self.session
223
+ .has_permission_bits(entry.mode, entry.uid, entry.gid, Access::Read)
224
+ }
225
+ }
226
+
227
+ fn require_access(
228
+ fs: &VirtualFs,
229
+ inode_id: u64,
230
+ session: &Session,
231
+ access: Access,
232
+ path: &str,
233
+ ) -> Result<(), VfsError> {
234
+ let inode = fs.get_inode(inode_id)?;
235
+ if !session.has_permission(inode, access) {
236
+ return Err(VfsError::PermissionDenied {
237
+ path: path.to_string(),
238
+ });
239
+ }
240
+ Ok(())
241
+ }
242
+
243
+ fn join_paths(parent: &str, child: &str) -> String {
244
+ if parent == "/" {
245
+ format!("/{child}")
246
+ } else if parent == "." {
247
+ format!("./{child}")
248
+ } else {
249
+ format!("{}/{}", parent.trim_end_matches('/'), child)
250
+ }
251
+ }
src/server/middleware.rs ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use axum::http::HeaderMap;
2
+
3
+ use crate::auth::session::Session;
4
+ use crate::error::VfsError;
5
+ use crate::server::AppState;
6
+
7
+ pub async fn session_from_headers(
8
+ state: &AppState,
9
+ headers: &HeaderMap,
10
+ ) -> Result<Session, VfsError> {
11
+ if let Some(auth_header) = headers.get("authorization") {
12
+ let header_str = auth_header.to_str().map_err(|_| VfsError::AuthError {
13
+ message: "invalid authorization header".to_string(),
14
+ })?;
15
+
16
+ if let Some(token) = header_str.strip_prefix("Bearer ") {
17
+ return state.db.authenticate_token(token).await;
18
+ }
19
+
20
+ if let Some(username) = header_str.strip_prefix("User ") {
21
+ return state.db.login(username).await;
22
+ }
23
+ }
24
+
25
+ Ok(Session::root())
26
+ }
src/server/mod.rs ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pub mod middleware;
2
+ pub mod routes_auth;
3
+ pub mod routes_fs;
4
+ pub mod routes_vcs;
5
+
6
+ use axum::Router;
7
+ use std::sync::Arc;
8
+ use tower_http::cors::CorsLayer;
9
+ use tower_http::trace::TraceLayer;
10
+
11
+ use crate::db::MarkdownDb;
12
+
13
+ #[derive(Clone)]
14
+ pub struct ServerState {
15
+ pub db: Arc<MarkdownDb>,
16
+ }
17
+
18
+ pub type AppState = Arc<ServerState>;
19
+
20
+ pub fn build_router(db: MarkdownDb) -> Router {
21
+ let state: AppState = Arc::new(ServerState {
22
+ db: Arc::new(db),
23
+ });
24
+
25
+ Router::new()
26
+ .merge(routes_auth::routes())
27
+ .merge(routes_fs::routes())
28
+ .merge(routes_vcs::routes())
29
+ .with_state(state)
30
+ .layer(TraceLayer::new_for_http())
31
+ .layer(CorsLayer::permissive())
32
+ }
src/server/routes_auth.rs ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use axum::extract::State;
2
+ use axum::http::StatusCode;
3
+ use axum::response::IntoResponse;
4
+ use axum::routing::post;
5
+ use axum::{Json, Router};
6
+ use serde::{Deserialize, Serialize};
7
+
8
+ use super::AppState;
9
+
10
+ #[derive(Deserialize)]
11
+ pub struct LoginRequest {
12
+ pub username: String,
13
+ }
14
+
15
+ #[derive(Serialize)]
16
+ pub struct LoginResponse {
17
+ pub username: String,
18
+ pub uid: u32,
19
+ pub gid: u32,
20
+ pub groups: Vec<u32>,
21
+ }
22
+
23
+ #[derive(Serialize)]
24
+ pub struct ErrorResponse {
25
+ pub error: String,
26
+ }
27
+
28
+ pub fn routes() -> Router<AppState> {
29
+ Router::new()
30
+ .route("/auth/login", post(login))
31
+ .route("/health", axum::routing::get(health))
32
+ }
33
+
34
+ async fn login(
35
+ State(state): State<AppState>,
36
+ Json(req): Json<LoginRequest>,
37
+ ) -> impl IntoResponse {
38
+ match state.db.login(&req.username).await {
39
+ Ok(session) => (
40
+ StatusCode::OK,
41
+ Json(LoginResponse {
42
+ username: session.username.clone(),
43
+ uid: session.uid,
44
+ gid: session.gid,
45
+ groups: session.groups.clone(),
46
+ }),
47
+ )
48
+ .into_response(),
49
+ Err(e) => (
50
+ StatusCode::UNAUTHORIZED,
51
+ Json(ErrorResponse {
52
+ error: e.to_string(),
53
+ }),
54
+ )
55
+ .into_response(),
56
+ }
57
+ }
58
+
59
+ async fn health(State(state): State<AppState>) -> impl IntoResponse {
60
+ let commits = state.db.commit_count().await;
61
+ let inodes = state.db.inode_count().await;
62
+ let objects = state.db.object_count().await;
63
+
64
+ Json(serde_json::json!({
65
+ "status": "ok",
66
+ "version": env!("CARGO_PKG_VERSION"),
67
+ "commits": commits,
68
+ "inodes": inodes,
69
+ "objects": objects,
70
+ }))
71
+ }
src/server/routes_fs.rs ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use axum::body::{Body, Bytes};
2
+ use axum::extract::{Path, Query, State};
3
+ use axum::http::{HeaderMap, StatusCode};
4
+ use axum::response::IntoResponse;
5
+ use axum::routing::get;
6
+ use axum::{Json, Router};
7
+ use serde::Deserialize;
8
+
9
+ use super::middleware::session_from_headers;
10
+ use super::AppState;
11
+
12
+ #[derive(Deserialize, Default)]
13
+ pub struct FsQuery {
14
+ pub stat: Option<bool>,
15
+ pub op: Option<String>,
16
+ pub dst: Option<String>,
17
+ pub recursive: Option<bool>,
18
+ }
19
+
20
+ #[derive(Deserialize, Default)]
21
+ pub struct SearchQuery {
22
+ pub pattern: Option<String>,
23
+ pub path: Option<String>,
24
+ pub name: Option<String>,
25
+ pub recursive: Option<bool>,
26
+ }
27
+
28
+ fn err_json(status: StatusCode, msg: impl Into<String>) -> impl IntoResponse {
29
+ (status, Json(serde_json::json!({"error": msg.into()})))
30
+ }
31
+
32
+ fn parent_path(path: &str) -> Option<String> {
33
+ let trimmed = path.trim_end_matches('/');
34
+ let idx = trimmed.rfind('/')?;
35
+ Some(trimmed[..idx].to_string())
36
+ }
37
+
38
+ pub fn routes() -> Router<AppState> {
39
+ Router::new()
40
+ .route("/fs", get(get_fs_root))
41
+ .route("/fs/{*path}", get(get_fs).put(put_fs).delete(delete_fs).post(post_fs))
42
+ .route("/search/grep", get(search_grep))
43
+ .route("/search/find", get(search_find))
44
+ .route("/tree", get(get_tree_root))
45
+ .route("/tree/{*path}", get(get_tree))
46
+ }
47
+
48
+ async fn get_fs_root(
49
+ State(state): State<AppState>,
50
+ headers: HeaderMap,
51
+ ) -> impl IntoResponse {
52
+ let _session = match session_from_headers(&state, &headers).await {
53
+ Ok(s) => s,
54
+ Err(e) => return err_json(StatusCode::UNAUTHORIZED, e.to_string()).into_response(),
55
+ };
56
+
57
+ match state.db.ls(None).await {
58
+ Ok(entries) => Json(ls_to_json(&entries, "/")).into_response(),
59
+ Err(e) => err_json(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
60
+ }
61
+ }
62
+
63
+ async fn get_fs(
64
+ State(state): State<AppState>,
65
+ Path(path): Path<String>,
66
+ Query(query): Query<FsQuery>,
67
+ headers: HeaderMap,
68
+ ) -> impl IntoResponse {
69
+ let _session = match session_from_headers(&state, &headers).await {
70
+ Ok(s) => s,
71
+ Err(e) => return err_json(StatusCode::UNAUTHORIZED, e.to_string()).into_response(),
72
+ };
73
+
74
+ if query.stat.unwrap_or(false) {
75
+ return match state.db.stat(&path).await {
76
+ Ok(info) => Json(serde_json::json!({
77
+ "inode_id": info.inode_id,
78
+ "kind": info.kind,
79
+ "size": info.size,
80
+ "mode": format!("0{:o}", info.mode),
81
+ "uid": info.uid,
82
+ "gid": info.gid,
83
+ "created": info.created,
84
+ "modified": info.modified,
85
+ }))
86
+ .into_response(),
87
+ Err(e) => err_json(StatusCode::NOT_FOUND, e.to_string()).into_response(),
88
+ };
89
+ }
90
+
91
+ match state.db.cat(&path).await {
92
+ Ok(content) => {
93
+ (StatusCode::OK, [("content-type", "text/markdown")], Body::from(content))
94
+ .into_response()
95
+ }
96
+ Err(crate::error::VfsError::IsDirectory { .. }) => {
97
+ match state.db.ls(Some(&path)).await {
98
+ Ok(entries) => Json(ls_to_json(&entries, &path)).into_response(),
99
+ Err(e) => {
100
+ err_json(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
101
+ }
102
+ }
103
+ }
104
+ Err(e) => err_json(StatusCode::NOT_FOUND, e.to_string()).into_response(),
105
+ }
106
+ }
107
+
108
+ async fn put_fs(
109
+ State(state): State<AppState>,
110
+ Path(path): Path<String>,
111
+ headers: HeaderMap,
112
+ body: Bytes,
113
+ ) -> impl IntoResponse {
114
+ let session = match session_from_headers(&state, &headers).await {
115
+ Ok(s) => s,
116
+ Err(e) => return err_json(StatusCode::UNAUTHORIZED, e.to_string()).into_response(),
117
+ };
118
+
119
+ let is_dir = headers
120
+ .get("x-markdownfs-type")
121
+ .and_then(|v| v.to_str().ok())
122
+ .map(|v| v == "directory")
123
+ .unwrap_or(false);
124
+
125
+ if is_dir {
126
+ match state.db.mkdir_p(&path, session.uid, session.gid).await {
127
+ Ok(()) => {
128
+ Json(serde_json::json!({"created": path, "type": "directory"})).into_response()
129
+ }
130
+ Err(e) => err_json(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
131
+ }
132
+ } else {
133
+ if state.db.stat(&path).await.is_err() {
134
+ if let Some(parent) = parent_path(&path) {
135
+ if !parent.is_empty() && state.db.stat(&parent).await.is_err() {
136
+ if let Err(e) = state.db.mkdir_p(&parent, session.uid, session.gid).await {
137
+ return err_json(StatusCode::BAD_REQUEST, e.to_string()).into_response();
138
+ }
139
+ }
140
+ }
141
+ if let Err(e) = state.db.touch(&path, session.uid, session.gid).await {
142
+ return err_json(StatusCode::BAD_REQUEST, e.to_string()).into_response();
143
+ }
144
+ }
145
+
146
+ let size = body.len();
147
+ match state.db.write_file(&path, body.to_vec()).await {
148
+ Ok(()) => Json(serde_json::json!({"written": path, "size": size})).into_response(),
149
+ Err(e) => err_json(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
150
+ }
151
+ }
152
+ }
153
+
154
+ async fn delete_fs(
155
+ State(state): State<AppState>,
156
+ Path(path): Path<String>,
157
+ Query(query): Query<FsQuery>,
158
+ headers: HeaderMap,
159
+ ) -> impl IntoResponse {
160
+ let _session = match session_from_headers(&state, &headers).await {
161
+ Ok(s) => s,
162
+ Err(e) => return err_json(StatusCode::UNAUTHORIZED, e.to_string()).into_response(),
163
+ };
164
+
165
+ let recursive = query.recursive.unwrap_or(false);
166
+ let result = if recursive {
167
+ state.db.rm_rf(&path).await
168
+ } else {
169
+ state.db.rm(&path).await
170
+ };
171
+
172
+ match result {
173
+ Ok(()) => Json(serde_json::json!({"deleted": path})).into_response(),
174
+ Err(e) => err_json(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
175
+ }
176
+ }
177
+
178
+ async fn post_fs(
179
+ State(state): State<AppState>,
180
+ Path(path): Path<String>,
181
+ Query(query): Query<FsQuery>,
182
+ headers: HeaderMap,
183
+ ) -> impl IntoResponse {
184
+ let session = match session_from_headers(&state, &headers).await {
185
+ Ok(s) => s,
186
+ Err(e) => return err_json(StatusCode::UNAUTHORIZED, e.to_string()).into_response(),
187
+ };
188
+
189
+ match query.op.as_deref() {
190
+ Some("copy") => {
191
+ let dst = match &query.dst {
192
+ Some(d) => d.as_str(),
193
+ None => return err_json(StatusCode::BAD_REQUEST, "missing dst parameter").into_response(),
194
+ };
195
+ match state.db.cp(&path, dst, session.uid, session.gid).await {
196
+ Ok(()) => Json(serde_json::json!({"copied": path, "to": dst})).into_response(),
197
+ Err(e) => err_json(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
198
+ }
199
+ }
200
+ Some("move") => {
201
+ let dst = match &query.dst {
202
+ Some(d) => d.as_str(),
203
+ None => return err_json(StatusCode::BAD_REQUEST, "missing dst parameter").into_response(),
204
+ };
205
+ match state.db.mv(&path, dst).await {
206
+ Ok(()) => Json(serde_json::json!({"moved": path, "to": dst})).into_response(),
207
+ Err(e) => err_json(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
208
+ }
209
+ }
210
+ Some(op) => err_json(StatusCode::BAD_REQUEST, format!("unknown op: {op}")).into_response(),
211
+ None => err_json(StatusCode::BAD_REQUEST, "missing op parameter").into_response(),
212
+ }
213
+ }
214
+
215
+ async fn search_grep(
216
+ State(state): State<AppState>,
217
+ Query(query): Query<SearchQuery>,
218
+ headers: HeaderMap,
219
+ ) -> impl IntoResponse {
220
+ let session = match session_from_headers(&state, &headers).await {
221
+ Ok(s) => s,
222
+ Err(e) => return err_json(StatusCode::UNAUTHORIZED, e.to_string()).into_response(),
223
+ };
224
+
225
+ let pattern = match &query.pattern {
226
+ Some(p) => p.clone(),
227
+ None => return err_json(StatusCode::BAD_REQUEST, "missing pattern parameter").into_response(),
228
+ };
229
+
230
+ let path = query.path.as_deref();
231
+ let recursive = query.recursive.unwrap_or(true);
232
+
233
+ match state.db.grep(&pattern, path, recursive, Some(&session)).await {
234
+ Ok(results) => {
235
+ let items: Vec<serde_json::Value> = results
236
+ .iter()
237
+ .map(|r| serde_json::json!({"file": r.file, "line_num": r.line_num, "line": r.line}))
238
+ .collect();
239
+ Json(serde_json::json!({"results": items, "count": items.len()})).into_response()
240
+ }
241
+ Err(e) => err_json(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
242
+ }
243
+ }
244
+
245
+ async fn search_find(
246
+ State(state): State<AppState>,
247
+ Query(query): Query<SearchQuery>,
248
+ headers: HeaderMap,
249
+ ) -> impl IntoResponse {
250
+ let session = match session_from_headers(&state, &headers).await {
251
+ Ok(s) => s,
252
+ Err(e) => return err_json(StatusCode::UNAUTHORIZED, e.to_string()).into_response(),
253
+ };
254
+
255
+ let path = query.path.as_deref();
256
+ let name = query.name.as_deref();
257
+
258
+ match state.db.find(path, name, Some(&session)).await {
259
+ Ok(results) => {
260
+ Json(serde_json::json!({"results": results, "count": results.len()})).into_response()
261
+ }
262
+ Err(e) => err_json(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
263
+ }
264
+ }
265
+
266
+ async fn get_tree_root(
267
+ State(state): State<AppState>,
268
+ headers: HeaderMap,
269
+ ) -> impl IntoResponse {
270
+ let session = match session_from_headers(&state, &headers).await {
271
+ Ok(s) => s,
272
+ Err(e) => return err_json(StatusCode::UNAUTHORIZED, e.to_string()).into_response(),
273
+ };
274
+ match state.db.tree(None, Some(&session)).await {
275
+ Ok(tree) => (StatusCode::OK, tree).into_response(),
276
+ Err(e) => err_json(StatusCode::NOT_FOUND, e.to_string()).into_response(),
277
+ }
278
+ }
279
+
280
+ async fn get_tree(
281
+ State(state): State<AppState>,
282
+ Path(path): Path<String>,
283
+ headers: HeaderMap,
284
+ ) -> impl IntoResponse {
285
+ let session = match session_from_headers(&state, &headers).await {
286
+ Ok(s) => s,
287
+ Err(e) => return err_json(StatusCode::UNAUTHORIZED, e.to_string()).into_response(),
288
+ };
289
+ match state.db.tree(Some(&path), Some(&session)).await {
290
+ Ok(tree) => (StatusCode::OK, tree).into_response(),
291
+ Err(e) => err_json(StatusCode::NOT_FOUND, e.to_string()).into_response(),
292
+ }
293
+ }
294
+
295
+ fn ls_to_json(entries: &[crate::fs::LsEntry], path: &str) -> serde_json::Value {
296
+ let items: Vec<serde_json::Value> = entries
297
+ .iter()
298
+ .map(|e| {
299
+ serde_json::json!({
300
+ "name": e.name,
301
+ "is_dir": e.is_dir,
302
+ "is_symlink": e.is_symlink,
303
+ "size": e.size,
304
+ "mode": format!("0{:o}", e.mode),
305
+ "uid": e.uid,
306
+ "gid": e.gid,
307
+ "modified": e.modified,
308
+ })
309
+ })
310
+ .collect();
311
+ serde_json::json!({"entries": items, "path": path})
312
+ }
src/server/routes_vcs.rs ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use axum::extract::State;
2
+ use axum::http::{HeaderMap, StatusCode};
3
+ use axum::response::IntoResponse;
4
+ use axum::routing::{get, post};
5
+ use axum::{Json, Router};
6
+ use serde::Deserialize;
7
+
8
+ use super::middleware::session_from_headers;
9
+ use super::AppState;
10
+
11
+ #[derive(Deserialize)]
12
+ pub struct CommitRequest {
13
+ pub message: String,
14
+ }
15
+
16
+ #[derive(Deserialize)]
17
+ pub struct RevertRequest {
18
+ pub hash: String,
19
+ }
20
+
21
+ pub fn routes() -> Router<AppState> {
22
+ Router::new()
23
+ .route("/vcs/commit", post(vcs_commit))
24
+ .route("/vcs/log", get(vcs_log))
25
+ .route("/vcs/revert", post(vcs_revert))
26
+ .route("/vcs/status", get(vcs_status))
27
+ }
28
+
29
+ async fn vcs_commit(
30
+ State(state): State<AppState>,
31
+ headers: HeaderMap,
32
+ Json(req): Json<CommitRequest>,
33
+ ) -> impl IntoResponse {
34
+ let session = match session_from_headers(&state, &headers).await {
35
+ Ok(s) => s,
36
+ Err(e) => return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({"error": e.to_string()}))).into_response(),
37
+ };
38
+
39
+ match state.db.commit(&req.message, &session.username).await {
40
+ Ok(hash) => Json(serde_json::json!({
41
+ "hash": hash,
42
+ "message": req.message,
43
+ "author": session.username,
44
+ }))
45
+ .into_response(),
46
+ Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))).into_response(),
47
+ }
48
+ }
49
+
50
+ async fn vcs_log(State(state): State<AppState>) -> impl IntoResponse {
51
+ let commits = state.db.vcs_log().await;
52
+ let items: Vec<serde_json::Value> = commits
53
+ .iter()
54
+ .map(|c| {
55
+ serde_json::json!({
56
+ "hash": c.id.short_hex(),
57
+ "message": c.message,
58
+ "author": c.author,
59
+ "timestamp": c.timestamp,
60
+ })
61
+ })
62
+ .collect();
63
+ Json(serde_json::json!({"commits": items}))
64
+ }
65
+
66
+ async fn vcs_revert(
67
+ State(state): State<AppState>,
68
+ Json(req): Json<RevertRequest>,
69
+ ) -> impl IntoResponse {
70
+ match state.db.revert(&req.hash).await {
71
+ Ok(()) => Json(serde_json::json!({"reverted_to": req.hash})).into_response(),
72
+ Err(e) => (StatusCode::BAD_REQUEST, Json(serde_json::json!({"error": e.to_string()}))).into_response(),
73
+ }
74
+ }
75
+
76
+ async fn vcs_status(State(state): State<AppState>) -> impl IntoResponse {
77
+ match state.db.vcs_status().await {
78
+ Ok(status) => (StatusCode::OK, status).into_response(),
79
+ Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))).into_response(),
80
+ }
81
+ }
src/store/blob.rs ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use super::{ObjectId, ObjectKind};
2
+ use crate::error::VfsError;
3
+ use std::collections::HashMap;
4
+
5
+ /// In-memory content-addressable blob store.
6
+ /// Will be upgraded to mmap-backed pack file in Phase 3.
7
+ pub struct BlobStore {
8
+ objects: HashMap<ObjectId, (ObjectKind, Vec<u8>)>,
9
+ }
10
+
11
+ impl BlobStore {
12
+ pub fn new() -> Self {
13
+ BlobStore {
14
+ objects: HashMap::new(),
15
+ }
16
+ }
17
+
18
+ pub fn put(&mut self, data: &[u8], kind: ObjectKind) -> ObjectId {
19
+ let id = ObjectId::from_bytes(data);
20
+ // Dedup: if already stored, skip
21
+ self.objects.entry(id).or_insert_with(|| (kind, data.to_vec()));
22
+ id
23
+ }
24
+
25
+ pub fn get(&self, id: &ObjectId) -> Result<&[u8], VfsError> {
26
+ self.objects
27
+ .get(id)
28
+ .map(|(_, data)| data.as_slice())
29
+ .ok_or_else(|| VfsError::ObjectNotFound {
30
+ id: id.short_hex(),
31
+ })
32
+ }
33
+
34
+ pub fn contains(&self, id: &ObjectId) -> bool {
35
+ self.objects.contains_key(id)
36
+ }
37
+
38
+ pub fn object_count(&self) -> usize {
39
+ self.objects.len()
40
+ }
41
+
42
+ /// Export all objects for persistence: (ObjectId bytes, kind as u8, data).
43
+ pub fn export_all(&self) -> Vec<(Vec<u8>, u8, Vec<u8>)> {
44
+ self.objects
45
+ .iter()
46
+ .map(|(id, (kind, data))| {
47
+ let kind_byte = match kind {
48
+ ObjectKind::Blob => 0u8,
49
+ ObjectKind::Tree => 1u8,
50
+ ObjectKind::Commit => 2u8,
51
+ };
52
+ (id.as_bytes().to_vec(), kind_byte, data.clone())
53
+ })
54
+ .collect()
55
+ }
56
+
57
+ /// Import objects from persisted state.
58
+ pub fn import_all(&mut self, objects: Vec<(Vec<u8>, u8, Vec<u8>)>) -> Result<(), crate::error::VfsError> {
59
+ for (id_bytes, kind_byte, data) in objects {
60
+ let mut arr = [0u8; 32];
61
+ if id_bytes.len() != 32 {
62
+ return Err(crate::error::VfsError::CorruptStore {
63
+ message: "invalid object ID length".to_string(),
64
+ });
65
+ }
66
+ arr.copy_from_slice(&id_bytes);
67
+ let id = ObjectId::from_raw(arr);
68
+ let kind = match kind_byte {
69
+ 0 => ObjectKind::Blob,
70
+ 1 => ObjectKind::Tree,
71
+ 2 => ObjectKind::Commit,
72
+ _ => {
73
+ return Err(crate::error::VfsError::CorruptStore {
74
+ message: format!("unknown object kind: {kind_byte}"),
75
+ })
76
+ }
77
+ };
78
+ self.objects.insert(id, (kind, data));
79
+ }
80
+ Ok(())
81
+ }
82
+ }
src/store/commit.rs ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use super::ObjectId;
2
+ use serde::{Deserialize, Serialize};
3
+
4
+ #[derive(Debug, Clone, Serialize, Deserialize)]
5
+ pub struct CommitObject {
6
+ pub id: ObjectId,
7
+ pub tree: ObjectId,
8
+ pub parent: Option<ObjectId>,
9
+ pub timestamp: u64,
10
+ pub message: String,
11
+ pub author: String,
12
+ }
13
+
14
+ impl CommitObject {
15
+ pub fn serialize(&self) -> Vec<u8> {
16
+ bincode::serialize(self).expect("commit serialization should not fail")
17
+ }
18
+
19
+ pub fn deserialize(data: &[u8]) -> Result<Self, bincode::Error> {
20
+ bincode::deserialize(data)
21
+ }
22
+ }
src/store/index.rs ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ // Pack index — will be implemented in Phase 3 for disk-backed storage.
2
+ // Currently the BlobStore uses an in-memory HashMap.
src/store/mod.rs ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pub mod blob;
2
+ pub mod commit;
3
+ pub mod index;
4
+ pub mod tree;
5
+
6
+ use crate::error::VfsError;
7
+ use sha2::{Digest, Sha256};
8
+
9
+ #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
10
+ pub struct ObjectId([u8; 32]);
11
+
12
+ impl ObjectId {
13
+ pub fn from_bytes(data: &[u8]) -> Self {
14
+ let mut hasher = Sha256::new();
15
+ hasher.update(data);
16
+ let result = hasher.finalize();
17
+ let mut id = [0u8; 32];
18
+ id.copy_from_slice(&result);
19
+ ObjectId(id)
20
+ }
21
+
22
+ pub fn as_bytes(&self) -> &[u8; 32] {
23
+ &self.0
24
+ }
25
+
26
+ pub fn to_hex(&self) -> String {
27
+ self.0.iter().map(|b| format!("{b:02x}")).collect()
28
+ }
29
+
30
+ pub fn short_hex(&self) -> String {
31
+ self.to_hex()[..8].to_string()
32
+ }
33
+
34
+ pub fn from_raw(bytes: [u8; 32]) -> Self {
35
+ ObjectId(bytes)
36
+ }
37
+
38
+ pub fn from_hex(hex: &str) -> Result<Self, VfsError> {
39
+ if hex.len() != 64 {
40
+ return Err(VfsError::InvalidArgs {
41
+ message: format!("invalid object ID: {hex}"),
42
+ });
43
+ }
44
+ let mut bytes = [0u8; 32];
45
+ for i in 0..32 {
46
+ bytes[i] = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).map_err(|_| {
47
+ VfsError::InvalidArgs {
48
+ message: format!("invalid hex: {hex}"),
49
+ }
50
+ })?;
51
+ }
52
+ Ok(ObjectId(bytes))
53
+ }
54
+ }
55
+
56
+ impl std::fmt::Debug for ObjectId {
57
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58
+ write!(f, "ObjectId({})", self.short_hex())
59
+ }
60
+ }
61
+
62
+ impl std::fmt::Display for ObjectId {
63
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64
+ write!(f, "{}", self.to_hex())
65
+ }
66
+ }
67
+
68
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
69
+ pub enum ObjectKind {
70
+ Blob,
71
+ Tree,
72
+ Commit,
73
+ }
src/store/tree.rs ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use super::ObjectId;
2
+ use serde::{Deserialize, Serialize};
3
+
4
+ #[derive(Debug, Clone, Serialize, Deserialize)]
5
+ pub struct TreeEntry {
6
+ pub name: String,
7
+ pub kind: TreeEntryKind,
8
+ pub id: ObjectId,
9
+ pub mode: u16,
10
+ pub uid: u32,
11
+ pub gid: u32,
12
+ }
13
+
14
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15
+ pub enum TreeEntryKind {
16
+ Blob,
17
+ Tree,
18
+ Symlink,
19
+ }
20
+
21
+ #[derive(Debug, Clone, Serialize, Deserialize)]
22
+ pub struct TreeObject {
23
+ pub entries: Vec<TreeEntry>,
24
+ }
25
+
26
+ impl TreeObject {
27
+ pub fn serialize(&self) -> Vec<u8> {
28
+ bincode::serialize(self).expect("tree serialization should not fail")
29
+ }
30
+
31
+ pub fn deserialize(data: &[u8]) -> Result<Self, bincode::Error> {
32
+ bincode::deserialize(data)
33
+ }
34
+ }
35
+
36
+ // Need serde impls for ObjectId
37
+ impl Serialize for ObjectId {
38
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
39
+ serializer.serialize_bytes(&self.0)
40
+ }
41
+ }
42
+
43
+ impl<'de> Deserialize<'de> for ObjectId {
44
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
45
+ let bytes: Vec<u8> = Deserialize::deserialize(deserializer)?;
46
+ if bytes.len() != 32 {
47
+ return Err(serde::de::Error::custom("expected 32 bytes for ObjectId"));
48
+ }
49
+ let mut arr = [0u8; 32];
50
+ arr.copy_from_slice(&bytes);
51
+ Ok(ObjectId(arr))
52
+ }
53
+ }
src/vcs/mod.rs ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pub mod revert;
2
+ pub mod snapshot;
3
+
4
+ use crate::error::VfsError;
5
+ use crate::fs::inode::{InodeKind, InodeId};
6
+ use crate::fs::VirtualFs;
7
+ use crate::store::blob::BlobStore;
8
+ use crate::store::commit::CommitObject;
9
+ use crate::store::tree::{TreeEntry, TreeEntryKind, TreeObject};
10
+ use crate::store::{ObjectId, ObjectKind};
11
+ use std::time::{SystemTime, UNIX_EPOCH};
12
+
13
+ pub struct Vcs {
14
+ pub store: BlobStore,
15
+ pub head: Option<ObjectId>,
16
+ pub commits: Vec<CommitObject>,
17
+ }
18
+
19
+ impl Vcs {
20
+ pub fn new() -> Self {
21
+ Vcs {
22
+ store: BlobStore::new(),
23
+ head: None,
24
+ commits: Vec::new(),
25
+ }
26
+ }
27
+
28
+ pub fn commit(
29
+ &mut self,
30
+ fs: &VirtualFs,
31
+ message: &str,
32
+ author: &str,
33
+ ) -> Result<ObjectId, VfsError> {
34
+ let root_tree_id = self.snapshot_dir(fs, fs.root_id())?;
35
+
36
+ let timestamp = SystemTime::now()
37
+ .duration_since(UNIX_EPOCH)
38
+ .unwrap_or_default()
39
+ .as_secs();
40
+
41
+ let commit = CommitObject {
42
+ id: ObjectId::from_bytes(&[0; 32]), // placeholder
43
+ tree: root_tree_id,
44
+ parent: self.head,
45
+ timestamp,
46
+ message: message.to_string(),
47
+ author: author.to_string(),
48
+ };
49
+
50
+ let commit_data = commit.serialize();
51
+ let commit_id = self.store.put(&commit_data, ObjectKind::Commit);
52
+
53
+ let final_commit = CommitObject {
54
+ id: commit_id,
55
+ ..commit
56
+ };
57
+
58
+ self.commits.push(final_commit);
59
+ self.head = Some(commit_id);
60
+ Ok(commit_id)
61
+ }
62
+
63
+ fn snapshot_dir(&mut self, fs: &VirtualFs, dir_id: InodeId) -> Result<ObjectId, VfsError> {
64
+ let inode = fs.get_inode(dir_id)?;
65
+ let entries = match &inode.kind {
66
+ InodeKind::Directory { entries } => entries,
67
+ _ => {
68
+ return Err(VfsError::NotDirectory {
69
+ path: format!("<inode {dir_id}>"),
70
+ })
71
+ }
72
+ };
73
+
74
+ let mut tree_entries = Vec::with_capacity(entries.len());
75
+ for (name, &child_id) in entries {
76
+ let child = fs.get_inode(child_id)?;
77
+ let (kind, id) = match &child.kind {
78
+ InodeKind::File { content } => {
79
+ let blob_id = self.store.put(content, ObjectKind::Blob);
80
+ (TreeEntryKind::Blob, blob_id)
81
+ }
82
+ InodeKind::Directory { .. } => {
83
+ let tree_id = self.snapshot_dir(fs, child_id)?;
84
+ (TreeEntryKind::Tree, tree_id)
85
+ }
86
+ InodeKind::Symlink { target } => {
87
+ let blob_id = self.store.put(target.as_bytes(), ObjectKind::Blob);
88
+ (TreeEntryKind::Symlink, blob_id)
89
+ }
90
+ };
91
+
92
+ tree_entries.push(TreeEntry {
93
+ name: name.clone(),
94
+ kind,
95
+ id,
96
+ mode: child.mode,
97
+ uid: child.uid,
98
+ gid: child.gid,
99
+ });
100
+ }
101
+
102
+ let tree = TreeObject {
103
+ entries: tree_entries,
104
+ };
105
+ let tree_data = tree.serialize();
106
+ Ok(self.store.put(&tree_data, ObjectKind::Tree))
107
+ }
108
+
109
+ pub fn log(&self) -> Vec<&CommitObject> {
110
+ self.commits.iter().rev().collect()
111
+ }
112
+
113
+ pub fn revert(&mut self, fs: &mut VirtualFs, hash_prefix: &str) -> Result<(), VfsError> {
114
+ let commit = self.find_commit(hash_prefix)?;
115
+ let tree_id = commit.tree;
116
+ let commit_id = commit.id;
117
+
118
+ // Reconstruct VFS from tree
119
+ revert::restore_from_tree(fs, &self.store, tree_id)?;
120
+
121
+ self.head = Some(commit_id);
122
+ Ok(())
123
+ }
124
+
125
+ pub fn find_commit(&self, hash_prefix: &str) -> Result<&CommitObject, VfsError> {
126
+ let matches: Vec<&CommitObject> = self
127
+ .commits
128
+ .iter()
129
+ .filter(|c| c.id.to_hex().starts_with(hash_prefix))
130
+ .collect();
131
+
132
+ match matches.len() {
133
+ 0 => Err(VfsError::ObjectNotFound {
134
+ id: hash_prefix.to_string(),
135
+ }),
136
+ 1 => Ok(matches[0]),
137
+ _ => Err(VfsError::InvalidArgs {
138
+ message: format!("ambiguous commit prefix: {hash_prefix}"),
139
+ }),
140
+ }
141
+ }
142
+
143
+ pub fn status(&self, fs: &VirtualFs) -> Result<String, VfsError> {
144
+ if self.head.is_none() {
145
+ return Ok("No commits yet.\n".to_string());
146
+ }
147
+
148
+ let mut output = String::new();
149
+ output.push_str(&format!(
150
+ "On commit {}\n",
151
+ self.head.unwrap().short_hex()
152
+ ));
153
+ output.push_str(&format!(
154
+ "Objects in store: {}\n",
155
+ self.store.object_count()
156
+ ));
157
+
158
+ let mut file_count = 0u64;
159
+ let mut total_size = 0u64;
160
+ for inode in fs.all_inodes().values() {
161
+ if let InodeKind::File { content } = &inode.kind {
162
+ file_count += 1;
163
+ total_size += content.len() as u64;
164
+ }
165
+ }
166
+ output.push_str(&format!("Files: {file_count}, Total size: {total_size} bytes\n"));
167
+ Ok(output)
168
+ }
169
+ }
src/vcs/revert.rs ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::error::VfsError;
2
+ use crate::fs::VirtualFs;
3
+ use crate::store::blob::BlobStore;
4
+ use crate::store::tree::{TreeEntryKind, TreeObject};
5
+ use crate::store::ObjectId;
6
+
7
+ /// Reconstruct a VirtualFs from a tree object in the store.
8
+ pub fn restore_from_tree(
9
+ fs: &mut VirtualFs,
10
+ store: &BlobStore,
11
+ root_tree_id: ObjectId,
12
+ ) -> Result<(), VfsError> {
13
+ // Preserve the registry across reverts
14
+ let registry = fs.registry.clone();
15
+ *fs = VirtualFs::new();
16
+ fs.registry = registry;
17
+
18
+ // Recursively restore from root tree
19
+ restore_dir(fs, store, "/", root_tree_id)?;
20
+ Ok(())
21
+ }
22
+
23
+ fn restore_dir(
24
+ fs: &mut VirtualFs,
25
+ store: &BlobStore,
26
+ dir_path: &str,
27
+ tree_id: ObjectId,
28
+ ) -> Result<(), VfsError> {
29
+ let tree_data = store.get(&tree_id)?;
30
+ let tree = TreeObject::deserialize(tree_data).map_err(|e| VfsError::CorruptStore {
31
+ message: format!("failed to deserialize tree: {e}"),
32
+ })?;
33
+
34
+ for entry in &tree.entries {
35
+ let child_path = if dir_path == "/" {
36
+ format!("/{}", entry.name)
37
+ } else {
38
+ format!("{}/{}", dir_path, entry.name)
39
+ };
40
+
41
+ match entry.kind {
42
+ TreeEntryKind::Blob => {
43
+ let content = store.get(&entry.id)?;
44
+ fs.touch(&child_path, entry.uid, entry.gid)?;
45
+ fs.write_file(&child_path, content.to_vec())?;
46
+ fs.chmod(&child_path, entry.mode)?;
47
+ }
48
+ TreeEntryKind::Tree => {
49
+ fs.mkdir(&child_path, entry.uid, entry.gid)?;
50
+ fs.chmod(&child_path, entry.mode)?;
51
+ restore_dir(fs, store, &child_path, entry.id)?;
52
+ }
53
+ TreeEntryKind::Symlink => {
54
+ let target = String::from_utf8_lossy(store.get(&entry.id)?).to_string();
55
+ fs.ln_s(&target, &child_path, entry.uid, entry.gid)?;
56
+ }
57
+ }
58
+ }
59
+
60
+ Ok(())
61
+ }
src/vcs/snapshot.rs ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ // Snapshot logic is in vcs/mod.rs (snapshot_dir method).
2
+ // This file is reserved for future optimization: incremental snapshots
3
+ // that skip unchanged subtrees by comparing tree hashes.
tests/integration/dirs.rs ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use super::*;
2
+
3
+ #[test]
4
+ fn test_mkdir_and_ls() {
5
+ let mut fs = VirtualFs::new();
6
+ exec("mkdir docs", &mut fs);
7
+ exec("mkdir src", &mut fs);
8
+ let output = exec("ls", &mut fs);
9
+ assert!(output.contains("docs/"));
10
+ assert!(output.contains("src/"));
11
+ }
12
+
13
+ #[test]
14
+ fn test_mkdir_duplicate() {
15
+ let mut fs = VirtualFs::new();
16
+ exec("mkdir docs", &mut fs);
17
+ let err = exec_err("mkdir docs", &mut fs);
18
+ assert!(err.contains("already exists"));
19
+ }
20
+
21
+ #[test]
22
+ fn test_mkdir_p_creates_intermediate() {
23
+ let mut fs = VirtualFs::new();
24
+ exec("mkdir -p a/b/c/d/e", &mut fs);
25
+ exec("cd a/b/c/d/e", &mut fs);
26
+ assert_eq!(exec("pwd", &mut fs).trim(), "/a/b/c/d/e");
27
+ }
28
+
29
+ #[test]
30
+ fn test_mkdir_p_idempotent() {
31
+ let mut fs = VirtualFs::new();
32
+ exec("mkdir -p a/b/c", &mut fs);
33
+ exec("mkdir -p a/b/c", &mut fs); // should not error
34
+ exec("cd a/b/c", &mut fs);
35
+ assert_eq!(exec("pwd", &mut fs).trim(), "/a/b/c");
36
+ }
37
+
38
+ #[test]
39
+ fn test_rmdir_empty() {
40
+ let mut fs = VirtualFs::new();
41
+ exec("mkdir empty", &mut fs);
42
+ exec("rmdir empty", &mut fs);
43
+ let ls = exec("ls", &mut fs);
44
+ assert!(!ls.contains("empty"));
45
+ }
46
+
47
+ #[test]
48
+ fn test_rmdir_non_empty_fails() {
49
+ let mut fs = VirtualFs::new();
50
+ exec("mkdir dir", &mut fs);
51
+ exec("cd dir", &mut fs);
52
+ exec("touch file.md", &mut fs);
53
+ exec("cd /", &mut fs);
54
+ let err = exec_err("rmdir dir", &mut fs);
55
+ assert!(err.contains("not empty"));
56
+ }
57
+
58
+ #[test]
59
+ fn test_rmdir_on_file_fails() {
60
+ let mut fs = VirtualFs::new();
61
+ exec("touch file.md", &mut fs);
62
+ let err = exec_err("rmdir file.md", &mut fs);
63
+ assert!(err.contains("not a directory"));
64
+ }
tests/integration/edge_cases.rs ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use super::*;
2
+
3
+ #[test]
4
+ fn test_unknown_command() {
5
+ let mut fs = VirtualFs::new();
6
+ let err = exec_err("foobar", &mut fs);
7
+ assert!(err.contains("unknown command"));
8
+ }
9
+
10
+ #[test]
11
+ fn test_empty_ls_root() {
12
+ let fs = VirtualFs::new();
13
+ let entries = fs.ls(None).unwrap();
14
+ assert!(entries.is_empty());
15
+ }
16
+
17
+ #[test]
18
+ fn test_ls_nonexistent_path() {
19
+ let mut fs = VirtualFs::new();
20
+ let err = exec_err("ls nonexistent", &mut fs);
21
+ assert!(err.contains("no such file"));
22
+ }
23
+
24
+ #[test]
25
+ fn test_touch_in_nonexistent_parent() {
26
+ let mut fs = VirtualFs::new();
27
+ let err = exec_err("touch nonexistent/file.md", &mut fs);
28
+ assert!(err.contains("no such file"));
29
+ }
30
+
31
+ #[test]
32
+ fn test_mkdir_in_nonexistent_parent() {
33
+ let mut fs = VirtualFs::new();
34
+ let err = exec_err("mkdir nonexistent/child", &mut fs);
35
+ assert!(err.contains("no such file"));
36
+ }
37
+
38
+ #[test]
39
+ fn test_mv_nonexistent_src_fails() {
40
+ let mut fs = VirtualFs::new();
41
+ let err = exec_err("mv ghost.md dest.md", &mut fs);
42
+ assert!(err.contains("no such file"));
43
+ }
44
+
45
+ #[test]
46
+ fn test_many_files_same_directory() {
47
+ let mut fs = VirtualFs::new();
48
+ for i in 0..500 {
49
+ fs.touch(&format!("file_{i:04}.md"), 0, 0).unwrap();
50
+ }
51
+ let entries = fs.ls(None).unwrap();
52
+ assert_eq!(entries.len(), 500);
53
+ // BTreeMap should keep them sorted
54
+ assert!(entries[0].name < entries[499].name);
55
+ }
56
+
57
+ #[test]
58
+ fn test_large_file_content() {
59
+ let mut fs = VirtualFs::new();
60
+ let content: String = (0..10_000)
61
+ .map(|i| format!("line {i}: Lorem ipsum dolor sit amet\n"))
62
+ .collect();
63
+ exec("touch big.md", &mut fs);
64
+ fs.write_file("big.md", content.as_bytes().to_vec())
65
+ .unwrap();
66
+ let read_back = fs.cat("big.md").unwrap();
67
+ assert_eq!(read_back.len(), content.len());
68
+ }
69
+
70
+ #[test]
71
+ fn test_deeply_nested_path() {
72
+ let mut fs = VirtualFs::new();
73
+ let mut path = String::new();
74
+ for i in 0..30 {
75
+ if i > 0 {
76
+ path.push('/');
77
+ }
78
+ path.push_str(&format!("d{i}"));
79
+ }
80
+ fs.mkdir_p(&path, 0, 0).unwrap();
81
+ let file_path = format!("{path}/deep.md");
82
+ fs.touch(&file_path, 0, 0).unwrap();
83
+ fs.write_file(&file_path, b"deep content".to_vec())
84
+ .unwrap();
85
+ assert_eq!(fs.cat(&file_path).unwrap(), b"deep content");
86
+ }
87
+
88
+ #[test]
89
+ fn test_stress_create_and_delete_cycle() {
90
+ let mut fs = VirtualFs::new();
91
+ for cycle in 0..20 {
92
+ for i in 0..50 {
93
+ let path = format!("cycle_{cycle}_file_{i}.md");
94
+ fs.touch(&path, 0, 0).unwrap();
95
+ }
96
+ for i in 0..50 {
97
+ let path = format!("cycle_{cycle}_file_{i}.md");
98
+ fs.rm(&path).unwrap();
99
+ }
100
+ }
101
+ let entries = fs.ls(None).unwrap();
102
+ assert!(entries.is_empty(), "all files should be deleted");
103
+ }
104
+
105
+ #[test]
106
+ fn test_stress_rapid_commits() {
107
+ let mut fs = VirtualFs::new();
108
+ let mut vcs = markdownfs::vcs::Vcs::new();
109
+
110
+ exec("touch file.md", &mut fs);
111
+ for i in 0..50 {
112
+ exec(&format!("write file.md version {i}"), &mut fs);
113
+ vcs.commit(&fs, &format!("commit {i}"), "root").unwrap();
114
+ }
115
+
116
+ assert_eq!(vcs.log().len(), 50);
117
+ assert_eq!(exec("cat file.md", &mut fs), "version 49");
118
+ }
119
+
120
+ #[test]
121
+ fn test_stress_deep_pipe_chain() {
122
+ let mut fs = VirtualFs::new();
123
+ exec("touch log.md", &mut fs);
124
+ let mut content = String::new();
125
+ for i in 0..1000 {
126
+ content.push_str(&format!("ERROR line {i}\n"));
127
+ }
128
+ fs.write_file("log.md", content.into_bytes()).unwrap();
129
+ let output = exec("cat log.md | grep ERROR | head -5 | wc -l", &mut fs);
130
+ assert_eq!(output.trim(), "5");
131
+ }
tests/integration/files.rs ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use super::*;
2
+
3
+ #[test]
4
+ fn test_touch_and_cat() {
5
+ let mut fs = VirtualFs::new();
6
+ exec("touch readme.md", &mut fs);
7
+ exec("write readme.md Hello, markdownfs!", &mut fs);
8
+ let output = exec("cat readme.md", &mut fs);
9
+ assert_eq!(output, "Hello, markdownfs!");
10
+ }
11
+
12
+ #[test]
13
+ fn test_only_markdown_files() {
14
+ let mut fs = VirtualFs::new();
15
+ let err = exec_err("touch hello.txt", &mut fs);
16
+ assert!(err.contains("only .md files"));
17
+ }
18
+
19
+ #[test]
20
+ fn test_touch_non_md_extensions_rejected() {
21
+ let mut fs = VirtualFs::new();
22
+ for ext in ["txt", "rs", "py", "json", "yaml", "toml", "html", "css"] {
23
+ let err = exec_err(&format!("touch file.{ext}"), &mut fs);
24
+ assert!(
25
+ err.contains("only .md files"),
26
+ "extension .{ext} should be rejected"
27
+ );
28
+ }
29
+ }
30
+
31
+ #[test]
32
+ fn test_touch_updates_timestamp() {
33
+ let mut fs = VirtualFs::new();
34
+ exec("touch file.md", &mut fs);
35
+ let stat1 = exec("stat file.md", &mut fs);
36
+ std::thread::sleep(std::time::Duration::from_millis(10));
37
+ exec("touch file.md", &mut fs);
38
+ let stat2 = exec("stat file.md", &mut fs);
39
+ // Timestamps should be equal or newer (within test resolution)
40
+ assert!(stat1.contains("file") && stat2.contains("file"));
41
+ }
42
+
43
+ #[test]
44
+ fn test_write_to_nonexistent_dir_fails() {
45
+ let mut fs = VirtualFs::new();
46
+ let err = exec_err("write nonexistent/ghost.md content", &mut fs);
47
+ assert!(err.contains("no such file"));
48
+ }
49
+
50
+ #[test]
51
+ fn test_cat_nonexistent_file() {
52
+ let mut fs = VirtualFs::new();
53
+ let err = exec_err("cat ghost.md", &mut fs);
54
+ assert!(err.contains("no such file"));
55
+ }
56
+
57
+ #[test]
58
+ fn test_cat_directory_fails() {
59
+ let mut fs = VirtualFs::new();
60
+ exec("mkdir dir", &mut fs);
61
+ let err = exec_err("cat dir", &mut fs);
62
+ assert!(err.contains("is a directory"));
63
+ }
64
+
65
+ #[test]
66
+ fn test_write_overwrite() {
67
+ let mut fs = VirtualFs::new();
68
+ exec("touch file.md", &mut fs);
69
+ exec("write file.md first", &mut fs);
70
+ assert_eq!(exec("cat file.md", &mut fs), "first");
71
+ exec("write file.md second", &mut fs);
72
+ assert_eq!(exec("cat file.md", &mut fs), "second");
73
+ }
74
+
75
+ #[test]
76
+ fn test_write_via_pipe_empty() {
77
+ let mut fs = VirtualFs::new();
78
+ exec("touch file.md", &mut fs);
79
+ exec("write file.md initial", &mut fs);
80
+ // Verify the initial write
81
+ assert_eq!(exec("cat file.md", &mut fs), "initial");
82
+ // Overwrite with pipe
83
+ exec("echo replaced | write file.md", &mut fs);
84
+ let content = exec("cat file.md", &mut fs);
85
+ assert!(content.contains("replaced"));
86
+ }
87
+
88
+ #[test]
89
+ fn test_write_multiline() {
90
+ let mut fs = VirtualFs::new();
91
+ exec("touch file.md", &mut fs);
92
+ exec("write file.md # Title\n\nParagraph 1\n\nParagraph 2", &mut fs);
93
+ let content = exec("cat file.md", &mut fs);
94
+ assert!(content.contains("# Title"));
95
+ assert!(content.contains("Paragraph 1"));
96
+ assert!(content.contains("Paragraph 2"));
97
+ }
98
+
99
+ #[test]
100
+ fn test_write_unicode() {
101
+ let mut fs = VirtualFs::new();
102
+ exec("touch unicode.md", &mut fs);
103
+ exec(
104
+ "write unicode.md 你好世界 🌍 café résumé naïve",
105
+ &mut fs,
106
+ );
107
+ let content = exec("cat unicode.md", &mut fs);
108
+ assert!(content.contains("你好世界"));
109
+ assert!(content.contains("🌍"));
110
+ assert!(content.contains("café"));
111
+ }
tests/integration/main.rs ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use markdownfs::auth::session::Session;
2
+ use markdownfs::cmd;
3
+ use markdownfs::cmd::parser;
4
+ use markdownfs::fs::VirtualFs;
5
+
6
+ pub fn exec(line: &str, fs: &mut VirtualFs) -> String {
7
+ let pipeline = parser::parse_pipeline(line);
8
+ let mut session = Session::root();
9
+ cmd::execute_pipeline(&pipeline, fs, &mut session).unwrap()
10
+ }
11
+
12
+ pub fn exec_err(line: &str, fs: &mut VirtualFs) -> String {
13
+ let pipeline = parser::parse_pipeline(line);
14
+ let mut session = Session::root();
15
+ cmd::execute_pipeline(&pipeline, fs, &mut session)
16
+ .unwrap_err()
17
+ .to_string()
18
+ }
19
+
20
+ pub fn exec_s(line: &str, fs: &mut VirtualFs, session: &mut Session) -> String {
21
+ let pipeline = parser::parse_pipeline(line);
22
+ cmd::execute_pipeline(&pipeline, fs, session).unwrap()
23
+ }
24
+
25
+ mod dirs;
26
+ mod files;
27
+ mod nav;
28
+ mod rm_mv_cp;
29
+ mod metadata;
30
+ mod search;
31
+ mod pipes;
32
+ mod symlinks;
33
+ mod vcs;
34
+ mod persist;
35
+ mod permissions;
36
+ mod posix;
37
+ mod edge_cases;
38
+ mod workflows;
tests/integration/metadata.rs ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use super::*;
2
+
3
+ #[test]
4
+ fn test_stat() {
5
+ let mut fs = VirtualFs::new();
6
+ exec("touch info.md", &mut fs);
7
+ let output = exec("stat info.md", &mut fs);
8
+ assert!(output.contains("file"));
9
+ assert!(output.contains("info.md"));
10
+ }
11
+
12
+ #[test]
13
+ fn test_stat_directory() {
14
+ let mut fs = VirtualFs::new();
15
+ exec("mkdir mydir", &mut fs);
16
+ let output = exec("stat mydir", &mut fs);
17
+ assert!(output.contains("directory"));
18
+ }
19
+
20
+ #[test]
21
+ fn test_stat_shows_mode() {
22
+ let mut fs = VirtualFs::new();
23
+ exec("touch secret.md", &mut fs);
24
+ exec("chmod 600 secret.md", &mut fs);
25
+ let output = exec("stat secret.md", &mut fs);
26
+ assert!(output.contains("0600"));
27
+ }
28
+
29
+ #[test]
30
+ fn test_stat_shows_uid_gid() {
31
+ let mut fs = VirtualFs::new();
32
+ exec("touch owned.md", &mut fs);
33
+ let output = exec("stat owned.md", &mut fs);
34
+ assert!(output.contains("Uid:"));
35
+ assert!(output.contains("Gid:"));
36
+ }
37
+
38
+ #[test]
39
+ fn test_tree() {
40
+ let mut fs = VirtualFs::new();
41
+ exec("mkdir docs", &mut fs);
42
+ exec("cd docs", &mut fs);
43
+ exec("touch readme.md", &mut fs);
44
+ exec("cd /", &mut fs);
45
+ let output = exec("tree", &mut fs);
46
+ assert!(output.contains("docs/"));
47
+ assert!(output.contains("readme.md"));
48
+ }
49
+
50
+ #[test]
51
+ fn test_tree_deep_hierarchy() {
52
+ let mut fs = VirtualFs::new();
53
+ exec("mkdir -p a/b/c", &mut fs);
54
+ exec("cd a/b/c", &mut fs);
55
+ exec("touch leaf.md", &mut fs);
56
+ exec("cd /", &mut fs);
57
+ let output = exec("tree", &mut fs);
58
+ assert!(output.contains("a/"));
59
+ assert!(output.contains("b/"));
60
+ assert!(output.contains("c/"));
61
+ assert!(output.contains("leaf.md"));
62
+ }
63
+
64
+ #[test]
65
+ fn test_tree_empty_root() {
66
+ let fs = VirtualFs::new();
67
+ let tree = fs.tree(None, "", None).unwrap();
68
+ assert!(tree.starts_with('.'));
69
+ }
70
+
71
+ #[test]
72
+ fn test_chmod() {
73
+ let mut fs = VirtualFs::new();
74
+ exec("touch secure.md", &mut fs);
75
+ exec("chmod 600 secure.md", &mut fs);
76
+ let output = exec("stat secure.md", &mut fs);
77
+ assert!(output.contains("0600"));
78
+ }
79
+
80
+ #[test]
81
+ fn test_chmod_various_modes() {
82
+ let mut fs = VirtualFs::new();
83
+ exec("touch file.md", &mut fs);
84
+ for mode in ["755", "644", "700", "400", "000", "777"] {
85
+ exec(&format!("chmod {mode} file.md"), &mut fs);
86
+ let stat = exec("stat file.md", &mut fs);
87
+ assert!(
88
+ stat.contains(&format!("0{mode}")),
89
+ "mode {mode} not found in stat output: {stat}"
90
+ );
91
+ }
92
+ }
93
+
94
+ #[test]
95
+ fn test_chmod_directory() {
96
+ let mut fs = VirtualFs::new();
97
+ exec("mkdir restricted", &mut fs);
98
+ exec("chmod 700 restricted", &mut fs);
99
+ let stat = exec("stat restricted", &mut fs);
100
+ assert!(stat.contains("0700"));
101
+ }
102
+
103
+ #[test]
104
+ fn test_ls_long_format() {
105
+ let mut fs = VirtualFs::new();
106
+ exec("mkdir docs", &mut fs);
107
+ exec("touch readme.md", &mut fs);
108
+ let output = exec("ls -l", &mut fs);
109
+ assert!(output.contains("drwx"));
110
+ assert!(output.contains("-rw-"));
111
+ }
112
+
113
+ #[test]
114
+ fn test_ls_long_shows_size() {
115
+ let mut fs = VirtualFs::new();
116
+ exec("touch file.md", &mut fs);
117
+ exec("write file.md hello world", &mut fs);
118
+ let output = exec("ls -l", &mut fs);
119
+ assert!(output.contains("11") || output.contains("file.md"));
120
+ }
121
+
122
+ #[test]
123
+ fn test_ls_empty_dir() {
124
+ let mut fs = VirtualFs::new();
125
+ exec("mkdir empty", &mut fs);
126
+ let output = exec("ls empty", &mut fs);
127
+ assert!(output.trim().is_empty());
128
+ }
tests/integration/nav.rs ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use super::*;
2
+
3
+ #[test]
4
+ fn test_cd_and_pwd() {
5
+ let mut fs = VirtualFs::new();
6
+ exec("mkdir project", &mut fs);
7
+ exec("cd project", &mut fs);
8
+ let pwd = exec("pwd", &mut fs);
9
+ assert_eq!(pwd.trim(), "/project");
10
+ exec("cd /", &mut fs);
11
+ assert_eq!(exec("pwd", &mut fs).trim(), "/");
12
+ }
13
+
14
+ #[test]
15
+ fn test_nested_dirs() {
16
+ let mut fs = VirtualFs::new();
17
+ exec("mkdir -p a/b/c", &mut fs);
18
+ exec("cd a/b/c", &mut fs);
19
+ let pwd = exec("pwd", &mut fs);
20
+ assert_eq!(pwd.trim(), "/a/b/c");
21
+ }
22
+
23
+ #[test]
24
+ fn test_cd_dotdot() {
25
+ let mut fs = VirtualFs::new();
26
+ exec("mkdir -p a/b/c", &mut fs);
27
+ exec("cd a/b/c", &mut fs);
28
+ exec("cd ..", &mut fs);
29
+ assert_eq!(exec("pwd", &mut fs).trim(), "/a/b");
30
+ exec("cd ..", &mut fs);
31
+ assert_eq!(exec("pwd", &mut fs).trim(), "/a");
32
+ exec("cd ..", &mut fs);
33
+ assert_eq!(exec("pwd", &mut fs).trim(), "/");
34
+ }
35
+
36
+ #[test]
37
+ fn test_cd_dotdot_at_root() {
38
+ let mut fs = VirtualFs::new();
39
+ exec("cd ..", &mut fs);
40
+ assert_eq!(exec("pwd", &mut fs).trim(), "/");
41
+ }
42
+
43
+ #[test]
44
+ fn test_cd_absolute_path() {
45
+ let mut fs = VirtualFs::new();
46
+ exec("mkdir -p a/b/c", &mut fs);
47
+ exec("cd a/b/c", &mut fs);
48
+ exec("cd /a", &mut fs);
49
+ assert_eq!(exec("pwd", &mut fs).trim(), "/a");
50
+ }
51
+
52
+ #[test]
53
+ fn test_cd_nonexistent_dir_fails() {
54
+ let mut fs = VirtualFs::new();
55
+ let err = exec_err("cd nowhere", &mut fs);
56
+ assert!(err.contains("no such file"));
57
+ }
58
+
59
+ #[test]
60
+ fn test_cd_to_file_fails() {
61
+ let mut fs = VirtualFs::new();
62
+ exec("touch file.md", &mut fs);
63
+ let err = exec_err("cd file.md", &mut fs);
64
+ assert!(err.contains("not a directory"));
65
+ }
66
+
67
+ #[test]
68
+ fn test_ls_specific_dir() {
69
+ let mut fs = VirtualFs::new();
70
+ exec("mkdir docs", &mut fs);
71
+ exec("cd docs", &mut fs);
72
+ exec("touch a.md", &mut fs);
73
+ exec("touch b.md", &mut fs);
74
+ exec("cd /", &mut fs);
75
+ let output = exec("ls docs", &mut fs);
76
+ assert!(output.contains("a.md"));
77
+ assert!(output.contains("b.md"));
78
+ }