-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotesStorage.cs
More file actions
747 lines (655 loc) · 30.9 KB
/
Copy pathNotesStorage.cs
File metadata and controls
747 lines (655 loc) · 30.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace AgentNotes.Core;
public sealed partial class NotesStorage
{
private const string NotesDirName = ".cascade-ide";
private const string NotesFileName = "agent-notes.md";
private const string EnvNotesFile = "AGENT_NOTES_FILE";
private const string RevisionsDirName = ".revisions";
private const string KnowledgeDirName = "knowledge";
private readonly object _sync = new();
private static readonly Regex SectionRegex = new(
@"<!--\s*section:(?<id>[A-Za-z0-9._-]+)\s*-->\s*(?<content>.*?)\s*<!--\s*/section:\k<id>\s*-->",
RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex MemoryArchitectureManifestRegex = new(
@"(?m)^\s*l0_manifest\s*:\s*(?<path>\S+)\s*$",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
/// <summary>Hot notes path: TOML primary root (<c>--config</c>); else <c>AGENT_NOTES_FILE</c>; else <c>workspace_path/.cascade-ide/agent-notes.md</c>.</summary>
public string GetNotesPath(string workspacePath)
{
if (AgentNotesRuntime.TryGetPrimaryKnowledgeRoot(out var primaryRoot))
return Path.Combine(primaryRoot, NotesFileName);
var globalPath = Environment.GetEnvironmentVariable(EnvNotesFile);
if (!string.IsNullOrWhiteSpace(globalPath))
return Path.GetFullPath(globalPath.Trim());
var root = Path.GetFullPath(workspacePath.Trim());
if (File.Exists(root))
root = Path.GetDirectoryName(root) ?? root;
return Path.Combine(root, NotesDirName, NotesFileName);
}
/// <summary>Resolve knowledge root for reads: <c>knowledge_path</c>, <c>knowledge_root_id</c>, primary from TOML, or legacy inference.</summary>
public static string ResolveKnowledgeRoot(string? knowledgePath, string? knowledgeRootId = null) =>
KnowledgeRootResolution.ResolveForRead(knowledgePath, knowledgeRootId);
/// <summary>Resolve knowledge root for writes (primary only when TOML is loaded).</summary>
public static string ResolveKnowledgeRootForWrite(string? knowledgePath, string? knowledgeRootId = null) =>
KnowledgeRootResolution.ResolveForWrite(knowledgePath, knowledgeRootId);
/// <summary>Legacy fallback when tool omits both <c>knowledge_path</c> and <c>knowledge_root_id</c>.</summary>
internal static string ResolveKnowledgeRootLegacy()
{
if (AgentNotesRuntime.TryGetPrimaryKnowledgeRoot(out var fromSettings))
return fromSettings;
var fromEnvNotes = Environment.GetEnvironmentVariable(EnvNotesFile);
if (!string.IsNullOrWhiteSpace(fromEnvNotes))
{
var inferred = TryInferKnowledgeRootFromAgentNotesFilePath(fromEnvNotes.Trim());
if (inferred is not null)
return inferred;
}
throw new ArgumentException(
"knowledge_path or knowledge_root_id is required when --config is not loaded and AGENT_NOTES_FILE is unset or does not lie under a directory tree that contains knowledge/.");
}
/// <summary>Walks parents from the notes file directory; returns the first directory that contains a <c>knowledge/</c> subfolder (agent-notes repo layout).</summary>
internal static string? TryInferKnowledgeRootFromAgentNotesFilePath(string agentNotesFilePath)
{
var fullPath = Path.GetFullPath(agentNotesFilePath);
var current = Path.GetDirectoryName(fullPath);
while (!string.IsNullOrEmpty(current))
{
if (Directory.Exists(Path.Combine(current, KnowledgeDirName)))
return current;
var parent = Directory.GetParent(current);
current = parent?.FullName;
}
return null;
}
/// <summary>Validate relative path under knowledge/: no "..", no leading slash. Returns normalized relative path.</summary>
private static string ValidateKnowledgeRelativePath(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
throw new ArgumentException("file_path is required.");
if (!TryValidateKnowledgeRelativePath(filePath, out var normalized))
throw new ArgumentException("file_path must be a relative path under knowledge/ (no '..', no absolute path).");
return normalized;
}
/// <summary>Returns false if <paramref name="filePath"/> is empty, rooted, or contains <c>..</c>.</summary>
private static bool TryValidateKnowledgeRelativePath(string filePath, out string normalized)
{
normalized = filePath.Replace('\\', '/').TrimStart('/');
if (string.IsNullOrWhiteSpace(normalized) || normalized.Contains("..", StringComparison.Ordinal) || Path.IsPathRooted(normalized))
{
normalized = "";
return false;
}
return true;
}
/// <summary>Workspace map paths: TOML <c>[workspace]</c> when <c>--config</c> loaded; else embedded defaults from AgentNotes.Core.</summary>
private static (string WorkspaceScopeMapRelative, string ScopeAliasMapRelative) ReadWorkspacePathsOrDefaults(string knowledgeRoot)
{
if (AgentNotesRuntime.IsConfigured)
{
var ws = AgentNotesRuntime.Settings.Workspace;
return (ws.ScopeMapRelative, ws.ScopeAliasMapRelative);
}
_ = knowledgeRoot;
return McpResolvePathsDefaults.DefaultsPair;
}
public string GetKnowledgeFilePath(string? knowledgePath, string filePath, string? knowledgeRootId = null)
{
var root = ResolveKnowledgeRoot(knowledgePath, knowledgeRootId);
return GetKnowledgeFilePathFromRoot(root, filePath);
}
private static string GetKnowledgeFilePathFromRoot(string root, string filePath)
{
var relative = ValidateKnowledgeRelativePath(filePath);
return Path.Combine(root, KnowledgeDirName, relative);
}
public string ReadKnowledgeFile(string? knowledgePath, string filePath, int? firstLine1Based = null, int? maxLineCount = null, string? knowledgeRootId = null)
{
var fullPath = GetKnowledgeFilePath(knowledgePath, filePath, knowledgeRootId);
if (!File.Exists(fullPath)) return "";
var full = File.ReadAllText(fullPath, Encoding.UTF8);
if (firstLine1Based is null && maxLineCount is null) return full;
return SliceTextByLines(full, firstLine1Based ?? 1, maxLineCount);
}
/// <summary>
/// Compact TOC for long KB files: section ids + short previews; prefers full <c>meta</c>/<c>summary</c> body when present.
/// Returns JSON (not raw markdown dump). Missing file → <c>ok:false</c>.
/// </summary>
public string OutlineKnowledgeFile(string? knowledgePath, string filePath, int previewLines = 5, string? knowledgeRootId = null)
{
var fullPath = GetKnowledgeFilePath(knowledgePath, filePath, knowledgeRootId);
if (!File.Exists(fullPath))
{
return JsonSerializer.Serialize(new
{
mode = "outline",
file_path = filePath,
ok = false,
error = "file_not_found",
section_ids = Array.Empty<string>(),
sections = Array.Empty<object>(),
}, JsonOptions);
}
var full = File.ReadAllText(fullPath, Encoding.UTF8);
var previewCap = Math.Clamp(previewLines, 1, 40);
var blocks = SectionMarkup.EnumerateCompleteBlocks(full);
var sectionIds = blocks.Select(b => b.Id).Distinct(StringComparer.Ordinal).ToArray();
object? preferred = null;
foreach (var preferId in new[] { "meta", "summary" })
{
var hit = blocks.FirstOrDefault(b => string.Equals(b.Id, preferId, StringComparison.Ordinal));
if (hit is null)
continue;
preferred = new { id = hit.Id, content = hit.Content };
break;
}
var sections = blocks.Select(b =>
{
var lines = SplitToLines(b.Content);
var preview = lines.Length == 0
? ""
: string.Join("\n", lines, 0, Math.Min(previewCap, lines.Length));
return new
{
id = b.Id,
preview,
line_count = lines.Length,
};
}).ToArray();
return JsonSerializer.Serialize(new
{
mode = "outline",
file_path = filePath,
ok = true,
section_ids = sectionIds,
preferred,
sections,
has_section_markers = blocks.Count > 0,
}, JsonOptions);
}
/// <summary>Return a substring of <paramref name="text"/> by line numbers. <paramref name="firstLine1Based"/> is 1-based. <paramref name="maxLineCount"/>: null = to EOF, 0 = empty, N = at most N lines.</summary>
internal static string SliceTextByLines(string text, int firstLine1Based, int? maxLineCount)
{
if (maxLineCount is 0) return "";
var lines = SplitToLines(text);
var start = Math.Max(0, firstLine1Based - 1);
if (start >= lines.Length) return "";
if (maxLineCount is int cap)
{
if (cap < 0) return "";
var n = Math.Min(cap, lines.Length - start);
if (n <= 0) return "";
return string.Join("\n", lines, start, n);
}
return string.Join("\n", lines, start, lines.Length - start);
}
private static string[] SplitToLines(string text) =>
text.Split(new[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
public string ListKnowledgeFiles(string? knowledgePath, string? subdir, string? knowledgeRootId = null)
{
var root = ResolveKnowledgeRoot(knowledgePath, knowledgeRootId);
var knowledgeRoot = Path.Combine(root, KnowledgeDirName);
var searchDir = string.IsNullOrWhiteSpace(subdir)
? knowledgeRoot
: Path.Combine(knowledgeRoot, ValidateKnowledgeRelativePath(subdir.Trim().Replace('\\', '/')));
if (!Directory.Exists(searchDir))
return JsonSerializer.Serialize(new { path = searchDir, files = Array.Empty<object>(), total = 0 }, JsonOptions);
var baseLen = knowledgeRoot.Length;
var files = Directory.GetFiles(searchDir, "*", SearchOption.AllDirectories)
.Where(p => !p.Contains(RevisionsDirName, StringComparison.Ordinal))
.Select(p =>
{
var rel = p.Substring(baseLen).TrimStart(Path.DirectorySeparatorChar).Replace('\\', '/');
var info = new FileInfo(p);
return new { path = rel, size_bytes = info.Length, modified_utc = info.LastWriteTimeUtc.ToString("O") };
})
.OrderBy(x => x.path, StringComparer.Ordinal)
.ToArray();
return JsonSerializer.Serialize(new { path = searchDir, files, total = files.Length }, JsonOptions);
}
/// <summary>
/// Scan knowledge/**/*.md for <c>**Tags:**</c> lines.
/// <paramref name="tag"/> empty → inventory (tag → count); set → hits for that tag (ssot first).
/// </summary>
public string QueryKnowledgeTags(
string? knowledgePath,
string? tag = null,
string? subdir = null,
string? knowledgeRootId = null,
int limit = 50)
{
var root = ResolveKnowledgeRoot(knowledgePath, knowledgeRootId);
var knowledgeRoot = Path.Combine(root, KnowledgeDirName);
var searchDir = string.IsNullOrWhiteSpace(subdir)
? knowledgeRoot
: Path.Combine(knowledgeRoot, ValidateKnowledgeRelativePath(subdir.Trim().Replace('\\', '/')));
if (!Directory.Exists(searchDir))
{
return JsonSerializer.Serialize(new
{
path = searchDir,
query = tag,
files_scanned = 0,
tags = Array.Empty<object>(),
hits = Array.Empty<object>(),
total = 0
}, JsonOptions);
}
var baseLen = knowledgeRoot.Length;
var want = KnowledgeTags.NormalizeOne(tag);
var lim = Math.Clamp(limit, 1, 500);
var inverted = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var hits = new List<KnowledgeTagHit>();
var taggedPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var scanned = 0;
foreach (var full in Directory.GetFiles(searchDir, "*.md", SearchOption.AllDirectories))
{
if (full.Contains(RevisionsDirName, StringComparison.Ordinal))
continue;
var norm = full.Replace('\\', '/');
if (norm.Contains("/scratch/", StringComparison.OrdinalIgnoreCase))
continue;
scanned++;
string text;
try { text = File.ReadAllText(full, Encoding.UTF8); }
catch { continue; }
var tags = KnowledgeTags.ParseTagsLine(text);
if (tags.Count == 0)
continue;
var rel = full.Substring(baseLen).TrimStart(Path.DirectorySeparatorChar).Replace('\\', '/');
taggedPaths.Add(rel);
var topics = KnowledgeTags.TopicTags(tags);
var roles = KnowledgeTags.RoleTagsOf(tags);
var ssot = roles.Contains(KnowledgeTags.RoleSsot, StringComparer.OrdinalIgnoreCase);
foreach (var t in tags)
inverted[t] = inverted.TryGetValue(t, out var c) ? c + 1 : 1;
if (want is not null && tags.Contains(want, StringComparer.OrdinalIgnoreCase))
{
hits.Add(new KnowledgeTagHit(
rel,
tags.Select(t => "#" + t).ToArray(),
topics.Select(t => "#" + t).ToArray(),
roles.Select(t => "#" + t).ToArray(),
ssot));
}
}
if (want is not null)
{
var ordered = hits
.OrderByDescending(h => h.Ssot)
.ThenBy(h => h.Path, StringComparer.Ordinal)
.Take(lim)
.Select(h => new
{
path = h.Path,
tags = h.Tags,
topics = h.Topics,
roles = h.Roles,
ssot = h.Ssot
})
.ToArray();
return JsonSerializer.Serialize(new
{
path = searchDir,
query = "#" + want,
files_scanned = scanned,
total = ordered.Length,
hits = ordered
}, JsonOptions);
}
var inventory = inverted
.OrderByDescending(kv => kv.Value)
.ThenBy(kv => kv.Key, StringComparer.OrdinalIgnoreCase)
.Take(lim)
.Select(kv => new { tag = "#" + kv.Key, file_count = kv.Value })
.ToArray();
return JsonSerializer.Serialize(new
{
path = searchDir,
query = (string?)null,
files_scanned = scanned,
tagged_files = taggedPaths.Count,
total_tags = inverted.Count,
tags = inventory
}, JsonOptions);
}
private sealed record KnowledgeTagHit(
string Path,
string[] Tags,
string[] Topics,
string[] Roles,
bool Ssot);
private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };
public string WriteKnowledgeFile(string? knowledgePath, string filePath, string content, bool saveRevision = true, string? knowledgeRootId = null)
{
var root = ResolveKnowledgeRootForWrite(knowledgePath, knowledgeRootId);
var fullPath = GetKnowledgeFilePathFromRoot(root, filePath);
if (saveRevision && File.Exists(fullPath))
{
var current = File.ReadAllText(fullPath, Encoding.UTF8);
WriteKnowledgeRevision(root, filePath, current, "write");
}
var dir = Path.GetDirectoryName(fullPath);
if (!string.IsNullOrWhiteSpace(dir))
Directory.CreateDirectory(dir);
File.WriteAllText(fullPath, content, Encoding.UTF8);
return "OK";
}
private void WriteKnowledgeRevision(string root, string filePath, string snapshotContent, string reason)
{
var revisionsDir = Path.Combine(root, KnowledgeDirName, RevisionsDirName);
Directory.CreateDirectory(revisionsDir);
var timestamp = DateTimeOffset.UtcNow.ToString("yyyyMMdd-HHmmss-fff");
var safeName = filePath.Replace('/', '-').Replace('\\', '-');
var revisionName = $"{timestamp}-{NormalizeReason(reason)}-{safeName}-{ComputeShortHash(snapshotContent)}.md";
var revisionPath = Path.Combine(revisionsDir, revisionName);
File.WriteAllText(revisionPath, snapshotContent, Encoding.UTF8);
}
public string AppendKnowledgeFile(string? knowledgePath, string filePath, string content, bool saveRevision = true, string? knowledgeRootId = null)
{
var root = ResolveKnowledgeRootForWrite(knowledgePath, knowledgeRootId);
var fullPath = GetKnowledgeFilePathFromRoot(root, filePath);
var existing = File.Exists(fullPath) ? File.ReadAllText(fullPath, Encoding.UTF8) : "";
if (saveRevision && existing.Length > 0)
WriteKnowledgeRevision(root, filePath, existing, "append");
var dir = Path.GetDirectoryName(fullPath);
if (!string.IsNullOrWhiteSpace(dir))
Directory.CreateDirectory(dir);
var separator = existing.Length > 0 && !existing.EndsWith('\n') ? "\n" : "";
File.WriteAllText(fullPath, existing + separator + content, Encoding.UTF8);
return "OK";
}
public string UpsertKnowledgeSection(string? knowledgePath, string filePath, string sectionId, string content, bool saveRevision = true, string? knowledgeRootId = null)
{
var root = ResolveKnowledgeRootForWrite(knowledgePath, knowledgeRootId);
var fullPath = GetKnowledgeFilePathFromRoot(root, filePath);
var dir = Path.GetDirectoryName(fullPath);
if (!string.IsNullOrWhiteSpace(dir))
Directory.CreateDirectory(dir);
var existing = File.Exists(fullPath) ? File.ReadAllText(fullPath, Encoding.UTF8) : "";
if (saveRevision && existing.Length > 0)
WriteKnowledgeRevision(root, filePath, existing, "upsert");
var next = SectionMarkup.UpsertBlock(existing, sectionId, content);
File.WriteAllText(fullPath, next, Encoding.UTF8);
return "OK";
}
public string DeleteKnowledgeFile(string? knowledgePath, string filePath, string? knowledgeRootId = null)
{
var root = ResolveKnowledgeRootForWrite(knowledgePath, knowledgeRootId);
var fullPath = GetKnowledgeFilePathFromRoot(root, filePath);
if (!File.Exists(fullPath))
return "NO_CHANGES";
File.Delete(fullPath);
return "OK";
}
public string DeleteKnowledgeSection(string? knowledgePath, string filePath, string sectionId, string? knowledgeRootId = null)
{
var root = ResolveKnowledgeRootForWrite(knowledgePath, knowledgeRootId);
var fullPath = GetKnowledgeFilePathFromRoot(root, filePath);
if (!File.Exists(fullPath))
return "NO_CHANGES";
var existing = File.ReadAllText(fullPath, Encoding.UTF8);
var startMarker = $"<!-- section:{sectionId} -->";
var endMarker = $"<!-- /section:{sectionId} -->";
var start = existing.IndexOf(startMarker, StringComparison.Ordinal);
var end = start >= 0 ? existing.IndexOf(endMarker, start, StringComparison.Ordinal) : -1;
if (start < 0 || end < 0)
return "NO_CHANGES";
var before = existing[..start].TrimEnd('\r', '\n');
var after = existing[(end + endMarker.Length)..].TrimStart('\r', '\n');
var next = JoinBlocks(before, after);
File.WriteAllText(fullPath, next, Encoding.UTF8);
return "OK";
}
public string Read(string workspacePath)
{
var filePath = GetNotesPath(workspacePath);
return File.Exists(filePath) ? File.ReadAllText(filePath, Encoding.UTF8) : "";
}
public string Write(string workspacePath, string content) =>
SaveWithRevision(GetNotesPath(workspacePath), content, "write");
public string Append(string workspacePath, string contentToAppend)
{
var notesPath = GetNotesPath(workspacePath);
var existing = File.Exists(notesPath) ? File.ReadAllText(notesPath, Encoding.UTF8) : "";
var separator = existing.Length > 0 && !existing.EndsWith('\n') ? "\n" : "";
return SaveWithRevision(notesPath, existing + separator + contentToAppend, "append");
}
public string UpsertSection(string workspacePath, string sectionId, string content)
{
var notesPath = GetNotesPath(workspacePath);
var existing = File.Exists(notesPath) ? File.ReadAllText(notesPath, Encoding.UTF8) : "";
var next = SectionMarkup.UpsertBlock(existing, sectionId, content);
return SaveWithRevision(notesPath, next, $"upsert-{sectionId}");
}
public string DeleteSection(string workspacePath, string sectionId)
{
var notesPath = GetNotesPath(workspacePath);
if (!File.Exists(notesPath))
return "NO_CHANGES";
var existing = File.ReadAllText(notesPath, Encoding.UTF8);
var startMarker = $"<!-- section:{sectionId} -->";
var endMarker = $"<!-- /section:{sectionId} -->";
var start = existing.IndexOf(startMarker, StringComparison.Ordinal);
var end = start >= 0 ? existing.IndexOf(endMarker, start, StringComparison.Ordinal) : -1;
if (start < 0 || end < 0)
return "NO_CHANGES";
var before = existing[..start].TrimEnd('\r', '\n');
var after = existing[(end + endMarker.Length)..].TrimStart('\r', '\n');
var next = JoinBlocks(before, after);
return SaveWithRevision(notesPath, next, $"delete-{sectionId}");
}
public string ValidateSections(string workspacePath)
{
var notesPath = GetNotesPath(workspacePath);
var existing = File.Exists(notesPath) ? File.ReadAllText(notesPath, Encoding.UTF8) : "";
return SectionMarkup.ToJson(SectionMarkup.Analyze(existing));
}
public string NormalizeSections(string workspacePath, bool apply)
{
var notesPath = GetNotesPath(workspacePath);
var existing = File.Exists(notesPath) ? File.ReadAllText(notesPath, Encoding.UTF8) : "";
var normalized = SectionMarkup.Normalize(existing);
var changed = !string.Equals(existing, normalized, StringComparison.Ordinal);
if (!apply)
{
return JsonSerializer.Serialize(new
{
changed,
before = SectionMarkup.Analyze(existing),
after = SectionMarkup.Analyze(normalized),
content = normalized.TrimEnd('\n')
}, new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower });
}
if (!changed)
return "NO_CHANGES";
return SaveWithRevision(notesPath, normalized, "normalize-sections");
}
public string ValidateKnowledgeSections(string? knowledgePath, string filePath, string? knowledgeRootId = null)
{
var root = ResolveKnowledgeRoot(knowledgePath, knowledgeRootId);
var fullPath = GetKnowledgeFilePathFromRoot(root, filePath);
var existing = File.Exists(fullPath) ? File.ReadAllText(fullPath, Encoding.UTF8) : "";
return SectionMarkup.ToJson(SectionMarkup.Analyze(existing));
}
public string NormalizeKnowledgeSections(string? knowledgePath, string filePath, bool apply, bool saveRevision = true, string? knowledgeRootId = null)
{
var root = ResolveKnowledgeRootForWrite(knowledgePath, knowledgeRootId);
var fullPath = GetKnowledgeFilePathFromRoot(root, filePath);
var existing = File.Exists(fullPath) ? File.ReadAllText(fullPath, Encoding.UTF8) : "";
var normalized = SectionMarkup.Normalize(existing);
var changed = !string.Equals(existing, normalized, StringComparison.Ordinal);
if (!apply)
{
return JsonSerializer.Serialize(new
{
changed,
before = SectionMarkup.Analyze(existing),
after = SectionMarkup.Analyze(normalized),
content = normalized.TrimEnd('\n')
}, new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower });
}
if (!changed)
return "NO_CHANGES";
if (saveRevision && existing.Length > 0)
WriteKnowledgeRevision(root, filePath, existing, "normalize-sections");
var dir = Path.GetDirectoryName(fullPath);
if (!string.IsNullOrWhiteSpace(dir))
Directory.CreateDirectory(dir);
File.WriteAllText(fullPath, normalized, Encoding.UTF8);
return "OK";
}
public string ListRevisions(string workspacePath, int limit)
{
var notesPath = GetNotesPath(workspacePath);
var revisionsDir = GetRevisionsDir(notesPath);
if (!Directory.Exists(revisionsDir))
return "[]";
var revisions = Directory.GetFiles(revisionsDir, "*.md")
.OrderByDescending(Path.GetFileName)
.Take(limit)
.Select(path =>
{
var info = new FileInfo(path);
return new
{
file = Path.GetFileName(path),
size_bytes = info.Length,
modified_utc = info.LastWriteTimeUtc.ToString("O")
};
})
.ToArray();
return JsonSerializer.Serialize(revisions, new JsonSerializerOptions { WriteIndented = true });
}
public string Rollback(string workspacePath, string? revisionFile)
{
var notesPath = GetNotesPath(workspacePath);
var revisionsDir = GetRevisionsDir(notesPath);
if (!Directory.Exists(revisionsDir))
throw new ArgumentException("No revisions found.");
var resolvedRevisionFile = revisionFile
?? Directory.GetFiles(revisionsDir, "*.md")
.Select(Path.GetFileName)
.OrderByDescending(name => name)
.FirstOrDefault();
if (string.IsNullOrWhiteSpace(resolvedRevisionFile))
throw new ArgumentException("No revisions found.");
var revisionPath = Path.Combine(revisionsDir, resolvedRevisionFile);
if (!File.Exists(revisionPath))
throw new ArgumentException("revision_file not found.");
var target = File.ReadAllText(revisionPath, Encoding.UTF8);
var result = SaveWithRevision(notesPath, target, $"rollback-{Path.GetFileNameWithoutExtension(resolvedRevisionFile)}");
return result == "NO_CHANGES" ? $"NO_CHANGES ({resolvedRevisionFile})" : $"OK ({resolvedRevisionFile})";
}
public string Search(string workspacePath, string query, int limit)
{
var notes = Read(workspacePath);
var lines = notes.Replace("\r\n", "\n").Split('\n');
var totalMatches = 0;
var returned = new List<object>();
for (var i = 0; i < lines.Length; i++)
{
if (!lines[i].Contains(query, StringComparison.OrdinalIgnoreCase))
continue;
totalMatches++;
if (returned.Count >= limit)
continue;
returned.Add(new
{
line = i + 1,
text = lines[i]
});
}
var payload = new
{
query,
total_matches = totalMatches,
returned_matches = returned.Count,
matches = returned
};
return JsonSerializer.Serialize(payload, new JsonSerializerOptions { WriteIndented = true });
}
private string SaveWithRevision(string notesPath, string newContent, string reason)
{
lock (_sync)
{
var hasCurrent = File.Exists(notesPath);
var currentContent = hasCurrent ? File.ReadAllText(notesPath, Encoding.UTF8) : "";
if (currentContent == newContent)
return "NO_CHANGES";
if (hasCurrent)
WriteRevisionSnapshot(notesPath, currentContent, reason);
AtomicWriteAllText(notesPath, newContent);
return "OK";
}
}
private static string GetRevisionsDir(string notesPath)
{
var dir = Path.GetDirectoryName(notesPath);
if (string.IsNullOrWhiteSpace(dir))
throw new ArgumentException("Invalid notes path.");
return Path.Combine(dir, RevisionsDirName);
}
private static void AtomicWriteAllText(string path, string content)
{
var dir = Path.GetDirectoryName(path);
if (string.IsNullOrWhiteSpace(dir))
throw new ArgumentException("Invalid target path.");
Directory.CreateDirectory(dir);
var tempPath = Path.Combine(dir, $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp");
File.WriteAllText(tempPath, content, Encoding.UTF8);
File.Move(tempPath, path, true);
}
private static void WriteRevisionSnapshot(string notesPath, string snapshotContent, string reason)
{
var revisionsDir = GetRevisionsDir(notesPath);
Directory.CreateDirectory(revisionsDir);
var timestamp = DateTimeOffset.UtcNow.ToString("yyyyMMdd-HHmmss-fff");
var revisionName = $"{timestamp}-{NormalizeReason(reason)}-{ComputeShortHash(snapshotContent)}.md";
var revisionPath = Path.Combine(revisionsDir, revisionName);
File.WriteAllText(revisionPath, snapshotContent, Encoding.UTF8);
}
private static string NormalizeReason(string reason)
{
var buffer = new StringBuilder(reason.Length);
foreach (var ch in reason.ToLowerInvariant())
{
if (char.IsAsciiLetterOrDigit(ch) || ch is '.' or '_' or '-')
buffer.Append(ch);
else if (buffer.Length == 0 || buffer[^1] != '-')
buffer.Append('-');
}
return buffer.ToString().Trim('-') is { Length: > 0 } normalized
? normalized
: "update";
}
private static string ComputeShortHash(string content)
{
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(content));
return Convert.ToHexString(hash.AsSpan(0, 4)).ToLowerInvariant();
}
private static string JoinBlocks(params string[] blocks)
{
var nonEmpty = blocks
.Select(block => block.Trim('\r', '\n'))
.Where(block => block.Length > 0)
.ToArray();
if (nonEmpty.Length == 0)
return "";
return string.Join("\n\n", nonEmpty) + "\n";
}
private static Dictionary<string, string> ParseSections(string notes)
{
var sections = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (Match match in SectionRegex.Matches(notes))
{
var id = match.Groups["id"].Value;
var content = match.Groups["content"].Value.Trim('\r', '\n');
sections[id] = content;
}
return sections;
}
}