GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Merge pull request #14594 from developing-today/oc-code-07/8626-notes… · developing-today/code@fb7d97e

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pkgs/atlas-search/crates
    • atlas-core
      • src
        • lib.rs
        • notes.rs
      • tests
        • notes.rs
    • atlas-search/src/bin
      • atlas-stage.rs
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pkgs/atlas-search/crates/atlas-core/src/lib.rs‎

Copy file name to clipboardExpand all lines: pkgs/atlas-search/crates/atlas-core/src/lib.rs
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ pub mod join;
6363
pub mod local;
6464
pub mod manifest;
6565
pub mod memory;
66+
pub mod notes;
6667
pub mod occurrences;
6768
pub mod owner_inventory;
6869
pub mod search;
Collapse file

‎pkgs/atlas-search/crates/atlas-core/src/notes.rs‎

Copy file name to clipboard
+368Lines changed: 368 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,368 @@
1+
//! The Atlas memory-integration zettelkasten connector
2+
//! (developing-today/code#8626 slice 4, the design record
3+
//! `pkgs/atlas-search/docs/memory-integration-design-8567.md`
4+
//! section 1: the notes-vault corpus).
5+
//!
6+
//! The design unifies the fleet's own corpora in the existing
7+
//! stage/registry path: one staging unit per corpus, staged units
8+
//! carrying the design's provenance set (corpus, agent, source_ref,
9+
//! updated_at, sensitivity, zone=fleet), and incremental re-indexing
10+
//! on source change (the issue's second acceptance criterion,
11+
//! demonstrated per connector family). This module is the vault-notes
12+
//! slice of that work, on the pattern slice 1 establishes
13+
//! ([`crate::memory`], including the slice-1b replay-safe
14+
//! discipline):
15+
//!
16+
//! * [`scan_note_files`] reads a Zettelkasten/Emanote notes vault:
17+
//! every `*.md` file under the vault root, in sorted
18+
//! tree-relative order so a scan is deterministic. Non-markdown
19+
//! files are not corpus content and are skipped; unreadable files
20+
//! and invalid UTF-8 are loud errors naming the path — a partial
21+
//! or silently defaulted ingest is exactly what the registry's
22+
//! provenance discipline exists to prevent.
23+
//! * [`stage_note_files`] stages the scanned notes into the
24+
//! `zettelkasten` unit through the same `items` + `chunks_raw`
25+
//! write path every staged unit uses: `kind` is `note`, `source`
26+
//! is the note's source-of-truth pointer, and `meta` carries the
27+
//! design's provenance set with the file's mtime as `updated_at`.
28+
//! Re-scanning an unchanged vault stages zero; an edited note
29+
//! re-stages exactly its chunks (the note's item is updated and
30+
//! its chunks replaced; every other item is untouched).
31+
//! Promotion and search are the existing aggregator and fan-out,
32+
//! unchanged.
33+
//!
34+
//! Out of scope: per-note agent attribution from note frontmatter
35+
//! (the vault records no author reliably, so `agent` is null — the
36+
//! design carries it "where known"); backlink-context enrichment
37+
//! (links ride along as note text; a backlink graph is follow-up
38+
//! work); and the slice-3 query surface, which this slice stages
39+
//! for but does not expose.
40+
41+
use std::path::Path;
42+
43+
use rusqlite::{Connection, OptionalExtension, params};
44+
45+
use crate::error::{Error, Result};
46+
use crate::shards::Tier;
47+
use crate::stage::{check_stage_schema, chunk_artifact_text, open, sha256_hex};
48+
49+
/// The staging-unit id of the zettelkasten corpus — the corpus this
50+
/// connector populates (design section 1: the Zettelkasten/Emanote
51+
/// notes vault).
52+
pub const ZETTELKASTEN_UNIT: &str = "zettelkasten";
53+
54+
/// One vault note, as scanned: its path relative to the vault root
55+
/// (the stable source identity, `/`-separated), its text, its
56+
/// modification instant as RFC 3339 UTC where known, and its
57+
/// physical sensitivity tier (the corpus default is the corpus's
58+
/// internal tier — individual notes carry no sensitivity marking).
59+
#[derive(Debug, Clone, PartialEq)]
60+
pub struct NoteFile {
61+
/// The note's path relative to the scanned vault root,
62+
/// `/`-separated (e.g. `habits/sleep.md`).
63+
pub rel_path: String,
64+
/// The note's full text, staged as-is (wikilinks and tags ride
65+
/// along as text).
66+
pub text: String,
67+
/// The note's modification instant as RFC 3339 UTC, where the
68+
/// filesystem reports one.
69+
pub updated_at: Option<String>,
70+
/// The note's physical sensitivity tier.
71+
pub sensitivity: Tier,
72+
}
73+
74+
impl NoteFile {
75+
/// The note's source-of-truth pointer: the corpus scheme plus
76+
/// its vault-relative path, carried as the staged item's
77+
/// `source` and in its provenance as `source_ref`.
78+
pub fn source_ref(&self) -> String {
79+
format!("note:{}", self.rel_path)
80+
}
81+
}
82+
83+
/// Format a filesystem modification instant as RFC 3339 UTC
84+
/// (second precision). Times before the unix epoch report `None`
85+
/// and let the caller fall back to the staging instant.
86+
fn system_time_rfc3339(mtime: std::time::SystemTime) -> Option<String> {
87+
let secs = mtime.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs() as i64;
88+
// Days-to-civil, shared with the `atlas-stage now_utc` helper:
89+
// RFC 3339 records when, not sub-second detail.
90+
let days = secs.div_euclid(86_400);
91+
let rem = secs.rem_euclid(86_400);
92+
let (h, m, s) = (rem / 3600, (rem % 3600) / 60, rem % 60);
93+
let z = days + 719_468;
94+
let era = z.div_euclid(146_097);
95+
let doe = z.rem_euclid(146_097);
96+
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
97+
let y = yoe + era * 400;
98+
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
99+
let mp = (5 * doy + 2) / 153;
100+
let d = doy - (153 * mp + 2) / 5 + 1;
101+
let month = if mp < 10 { mp + 3 } else { mp - 9 };
102+
let year = if month <= 2 { y + 1 } else { y };
103+
Some(format!("{year:04}-{month:02}-{d:02}T{h:02}:{m:02}:{s:02}Z"))
104+
}
105+
106+
/// Scan a notes vault root for stageable notes: every `*.md` file
107+
/// under `root`, in sorted tree-relative order so a scan is
108+
/// deterministic. Non-markdown files are not corpus content and are
109+
/// skipped; unreadable files and invalid UTF-8 are loud errors
110+
/// naming the path.
111+
pub fn scan_note_files(root: &Path) -> Result<Vec<NoteFile>> {
112+
if !root.is_dir() {
113+
return Err(Error::fatal(format!(
114+
"notes connector: notes vault {} is not a directory",
115+
root.display()
116+
)));
117+
}
118+
let mut rel_paths: Vec<String> = Vec::new();
119+
let mut stack: Vec<std::path::PathBuf> = vec![root.to_path_buf()];
120+
while let Some(dir) = stack.pop() {
121+
let entries = std::fs::read_dir(&dir).map_err(|e| {
122+
Error::backend(format!("notes connector: listing {}: {e}", dir.display()))
123+
})?;
124+
for entry in entries {
125+
let entry = entry.map_err(|e| {
126+
Error::backend(format!("notes connector: listing {}: {e}", dir.display()))
127+
})?;
128+
let path = entry.path();
129+
if path.is_dir() {
130+
stack.push(path);
131+
} else if path.is_file()
132+
&& path
133+
.extension()
134+
.and_then(|x| x.to_str())
135+
.is_some_and(|x| x.eq_ignore_ascii_case("md"))
136+
{
137+
let rel = path.strip_prefix(root).map_err(|e| {
138+
Error::backend(format!(
139+
"notes connector: relativizing {}: {e}",
140+
path.display()
141+
))
142+
})?;
143+
rel_paths.push(
144+
rel.components()
145+
.map(|c| c.as_os_str().to_string_lossy())
146+
.collect::<Vec<_>>()
147+
.join("/"),
148+
);
149+
}
150+
}
151+
}
152+
rel_paths.sort();
153+
rel_paths
154+
.iter()
155+
.map(|rel| {
156+
// Rebuild the filesystem path from the `/`-joined
157+
// relative form (components were split on the platform
158+
// separator, so this round-trips on any host).
159+
let mut path = root.to_path_buf();
160+
for comp in rel.split('/') {
161+
path.push(comp);
162+
}
163+
let text = std::fs::read_to_string(&path)
164+
.map_err(|e| Error::backend(format!("notes connector: reading note {rel}: {e}")))?;
165+
let updated_at = std::fs::metadata(&path)
166+
.and_then(|m| m.modified())
167+
.ok()
168+
.and_then(system_time_rfc3339);
169+
Ok(NoteFile {
170+
rel_path: rel.clone(),
171+
text,
172+
updated_at,
173+
sensitivity: Tier::Internal,
174+
})
175+
})
176+
.collect()
177+
}
178+
179+
/// Stage one vault note into a v1 staging DB as one `items` row plus
180+
/// its `chunks_raw` rows, on the same write path as every staged
181+
/// unit: `kind` is `note`, `source` is the note's source-of-truth
182+
/// pointer, and `meta` carries the design's provenance set
183+
/// (corpus `zettelkasten`, agent `null` — the vault records no
184+
/// author reliably — source_ref, updated_at from the file's mtime,
185+
/// sensitivity, zone `fleet`). Replay-safe: an unchanged note
186+
/// re-stages to its existing item with no write; an edited note
187+
/// updates its item and replaces exactly its chunks. Returns the
188+
/// item's id. The DB must already be a v1 staging DB
189+
/// ([`check_stage_schema`]); vectors are produced later, at
190+
/// promotion, as for every staged item.
191+
pub fn stage_note_file(
192+
conn: &Connection,
193+
unit_id: &str,
194+
file: &NoteFile,
195+
now: &str,
196+
) -> Result<i64> {
197+
stage_note_file_with_status(conn, unit_id, file, now).map(|(id, _)| id)
198+
}
199+
200+
fn stage_note_file_with_status(
201+
conn: &Connection,
202+
unit_id: &str,
203+
file: &NoteFile,
204+
now: &str,
205+
) -> Result<(i64, bool)> {
206+
let tx = conn
207+
.unchecked_transaction()
208+
.map_err(|e| Error::backend(format!("notes connector: starting stage transaction: {e}")))?;
209+
let result = stage_note_file_in_transaction(&tx, unit_id, file, now)?;
210+
tx.commit().map_err(|e| {
211+
Error::backend(format!(
212+
"notes connector: committing stage transaction: {e}"
213+
))
214+
})?;
215+
Ok(result)
216+
}
217+
218+
fn stage_note_file_in_transaction(
219+
conn: &Connection,
220+
unit_id: &str,
221+
file: &NoteFile,
222+
now: &str,
223+
) -> Result<(i64, bool)> {
224+
check_stage_schema(conn)?;
225+
let chunks = chunk_artifact_text(&file.text);
226+
let source = file.source_ref();
227+
let meta = serde_json::json!({
228+
"corpus": ZETTELKASTEN_UNIT,
229+
"agent": None::<String>,
230+
"source_ref": source,
231+
"updated_at": file.updated_at,
232+
"sensitivity": file.sensitivity.name(),
233+
"zone": "fleet",
234+
"rel_path": file.rel_path,
235+
"staged_at": now,
236+
"chunks": chunks.len(),
237+
})
238+
.to_string();
239+
let existing = conn
240+
.query_row(
241+
"SELECT id, text, sensitivity, meta FROM items \
242+
WHERE unit_id = ?1 AND kind = 'note' AND source = ?2 ORDER BY id DESC LIMIT 1",
243+
params![unit_id, source],
244+
|row| {
245+
Ok((
246+
row.get::<_, i64>(0)?,
247+
row.get::<_, String>(1)?,
248+
row.get::<_, String>(2)?,
249+
row.get::<_, Option<String>>(3)?,
250+
))
251+
},
252+
)
253+
.optional()
254+
.map_err(|e| {
255+
Error::backend(format!(
256+
"notes connector: finding item for {}: {e}",
257+
file.rel_path
258+
))
259+
})?;
260+
261+
let (item_id, changed) = match existing {
262+
Some((id, text, sensitivity, old_meta)) => {
263+
let unchanged = text == file.text
264+
&& sensitivity == file.sensitivity.name()
265+
&& old_meta
266+
.as_deref()
267+
.and_then(|raw| serde_json::from_str::<serde_json::Value>(raw).ok())
268+
.is_some_and(|old| {
269+
let new: serde_json::Value =
270+
serde_json::from_str(&meta).unwrap_or_default();
271+
old.get("updated_at") == new.get("updated_at")
272+
&& old.get("sensitivity") == new.get("sensitivity")
273+
});
274+
if unchanged {
275+
return Ok((id, false));
276+
}
277+
conn.execute(
278+
"UPDATE items SET text = ?1, sensitivity = ?2, created_at = ?3, meta = ?4 WHERE id = ?5",
279+
params![
280+
file.text,
281+
file.sensitivity.name(),
282+
file.updated_at.as_deref().unwrap_or(now),
283+
meta,
284+
id,
285+
],
286+
)
287+
.map_err(|e| Error::backend(format!("notes connector: updating item for {}: {e}", file.rel_path)))?;
288+
conn.execute("DELETE FROM chunks_raw WHERE item_id = ?1", [id])
289+
.map_err(|e| {
290+
Error::backend(format!(
291+
"notes connector: replacing chunks for {}: {e}",
292+
file.rel_path
293+
))
294+
})?;
295+
(id, true)
296+
}
297+
None => {
298+
conn.execute(
299+
"INSERT INTO items (unit_id, kind, source, text, sensitivity, created_at, meta) \
300+
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
301+
params![
302+
unit_id,
303+
"note",
304+
source,
305+
file.text,
306+
file.sensitivity.name(),
307+
file.updated_at.as_deref().unwrap_or(now),
308+
meta,
309+
],
310+
)
311+
.map_err(|e| {
312+
Error::backend(format!(
313+
"notes connector: inserting item for {}: {e}",
314+
file.rel_path
315+
))
316+
})?;
317+
(conn.last_insert_rowid(), true)
318+
}
319+
};
320+
for (idx, chunk) in chunks.iter().enumerate() {
321+
conn.execute(
322+
"INSERT INTO chunks_raw (item_id, idx, text, content_hash, created_at) \
323+
VALUES (?1, ?2, ?3, ?4, ?5)",
324+
params![item_id, idx as i64, chunk, sha256_hex(chunk), now],
325+
)
326+
.map_err(|e| {
327+
Error::backend(format!(
328+
"notes connector: inserting chunk {idx} for {}: {e}",
329+
file.rel_path
330+
))
331+
})?;
332+
}
333+
Ok((item_id, changed))
334+
}
335+
336+
/// Stage scanned vault notes into a unit, in scan order. Returns the
337+
/// ids of the notes that staged new or changed content — an
338+
/// unchanged re-scan returns an empty vec, never duplicate items.
339+
pub fn stage_note_files(
340+
conn: &Connection,
341+
unit_id: &str,
342+
files: &[NoteFile],
343+
now: &str,
344+
) -> Result<Vec<i64>> {
345+
files
346+
.iter()
347+
.map(|file| stage_note_file_with_status(conn, unit_id, file, now))
348+
.filter_map(|result| match result {
349+
Ok((id, true)) => Some(Ok(id)),
350+
Ok((_, false)) => None,
351+
Err(error) => Some(Err(error)),
352+
})
353+
.collect()
354+
}
355+
356+
/// [`scan_note_files`] + [`stage_note_files`] against a staging DB
357+
/// file: the form the `atlas-stage ingest-notes` tool calls, so the
358+
/// CLI needs no DB handle of its own.
359+
pub fn scan_and_stage_note_files_in_db(
360+
db: &Path,
361+
unit_id: &str,
362+
vault: &Path,
363+
now: &str,
364+
) -> Result<Vec<i64>> {
365+
let files = scan_note_files(vault)?;
366+
let conn = open(db)?;
367+
stage_note_files(&conn, unit_id, &files, now)
368+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.