create-egregore 0.19.8 → 0.19.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/lib/local.js +11 -1
  2. package/lib/setup.js +33 -0
  3. package/package.json +1 -1
  4. package/runtime/codex/.codex/hooks/branch-guard.js +242 -34
  5. package/runtime/codex/.codex/skills/activity/SKILL.md +18 -6
  6. package/runtime/codex/.codex/skills/deep-reflect/SKILL.md +90 -55
  7. package/runtime/codex/.codex/skills/deploy-bridge/SKILL.md +25 -0
  8. package/runtime/codex/.codex/skills/handoff/SKILL.md +6 -2
  9. package/runtime/codex/.codex/skills/save/SKILL.md +21 -3
  10. package/runtime/codex/.codex/skills/scroll/SKILL.md +54 -3
  11. package/runtime/codex/.codex/skills/task/SKILL.md +25 -0
  12. package/runtime/codex/.codex/skills/tui-design/SKILL.md +1 -1
  13. package/runtime/codex/.codex/skills/wrap/SKILL.md +4 -1
  14. package/runtime/codex/.codex/spec-manifest.json +15 -3
  15. package/runtime/codex/AGENTS.md +45 -9
  16. package/runtime/codex/bin/activity-data.sh +1 -1
  17. package/runtime/codex/bin/agent.sh +66 -23
  18. package/runtime/codex/bin/attendant.sh +525 -0
  19. package/runtime/codex/bin/capture-reconcile.sh +67 -0
  20. package/runtime/codex/bin/capture-run.sh +341 -0
  21. package/runtime/codex/bin/codex-render-spec.mjs +15 -4
  22. package/runtime/codex/bin/codex-session-start.sh +45 -3
  23. package/runtime/codex/bin/codex-skill-render.mjs +23 -4
  24. package/runtime/codex/bin/graph-op.sh +719 -49
  25. package/runtime/codex/bin/graph-wal.sh +3 -2
  26. package/runtime/codex/bin/handoff-run.sh +72 -0
  27. package/runtime/codex/bin/handoff-save-egregore.sh +51 -11
  28. package/runtime/codex/bin/index-handoff.sh +26 -17
  29. package/runtime/codex/bin/ingest-graph.sh +80 -0
  30. package/runtime/codex/bin/ingest-surface.html +429 -0
  31. package/runtime/codex/bin/ingest.py +614 -0
  32. package/runtime/codex/bin/ingest.sh +231 -0
  33. package/runtime/codex/bin/ingest_graph.py +776 -0
  34. package/runtime/codex/bin/ingest_surface.py +464 -0
  35. package/runtime/codex/bin/lib/git-sync.sh +2 -6
  36. package/runtime/codex/bin/lib/greeting.sh +157 -22
  37. package/runtime/codex/bin/lib/identity.sh +50 -29
  38. package/runtime/codex/bin/lib/noncode.sh +31 -0
  39. package/runtime/codex/bin/person.py +610 -0
  40. package/runtime/codex/bin/person.sh +448 -0
  41. package/runtime/codex/bin/session-autosave.sh +184 -0
  42. package/runtime/codex/bin/session-log.sh +199 -0
  43. package/runtime/codex/bin/settings.sh +1 -1
  44. package/runtime/codex/manifest.json +19 -1
  45. package/runtime/pi/.codex/hooks/branch-guard.js +242 -34
  46. package/runtime/pi/.codex/skills/activity/SKILL.md +18 -6
  47. package/runtime/pi/.codex/skills/deep-reflect/SKILL.md +90 -55
  48. package/runtime/pi/.codex/skills/deploy-bridge/SKILL.md +25 -0
  49. package/runtime/pi/.codex/skills/handoff/SKILL.md +6 -2
  50. package/runtime/pi/.codex/skills/save/SKILL.md +21 -3
  51. package/runtime/pi/.codex/skills/scroll/SKILL.md +54 -3
  52. package/runtime/pi/.codex/skills/task/SKILL.md +25 -0
  53. package/runtime/pi/.codex/skills/tui-design/SKILL.md +1 -1
  54. package/runtime/pi/.codex/skills/wrap/SKILL.md +4 -1
  55. package/runtime/pi/.codex/spec-manifest.json +15 -3
  56. package/runtime/pi/.pi/APPEND_SYSTEM.md +41 -5
  57. package/runtime/pi/.pi/extensions/egregore.ts +98 -8
  58. package/runtime/pi/.pi/spec-manifest.json +2 -2
  59. package/runtime/pi/AGENTS.md +45 -9
  60. package/runtime/pi/bin/activity-data.sh +1 -1
  61. package/runtime/pi/bin/agent.sh +66 -23
  62. package/runtime/pi/bin/attendant.sh +525 -0
  63. package/runtime/pi/bin/capture-reconcile.sh +67 -0
  64. package/runtime/pi/bin/capture-run.sh +341 -0
  65. package/runtime/pi/bin/codex-render-spec.mjs +15 -4
  66. package/runtime/pi/bin/codex-session-start.sh +45 -3
  67. package/runtime/pi/bin/codex-skill-render.mjs +23 -4
  68. package/runtime/pi/bin/graph-op.sh +719 -49
  69. package/runtime/pi/bin/graph-wal.sh +3 -2
  70. package/runtime/pi/bin/handoff-run.sh +72 -0
  71. package/runtime/pi/bin/handoff-save-egregore.sh +51 -11
  72. package/runtime/pi/bin/index-handoff.sh +26 -17
  73. package/runtime/pi/bin/ingest-graph.sh +80 -0
  74. package/runtime/pi/bin/ingest-surface.html +429 -0
  75. package/runtime/pi/bin/ingest.py +614 -0
  76. package/runtime/pi/bin/ingest.sh +231 -0
  77. package/runtime/pi/bin/ingest_graph.py +776 -0
  78. package/runtime/pi/bin/ingest_surface.py +464 -0
  79. package/runtime/pi/bin/lib/git-sync.sh +2 -6
  80. package/runtime/pi/bin/lib/greeting.sh +157 -22
  81. package/runtime/pi/bin/lib/identity.sh +50 -29
  82. package/runtime/pi/bin/lib/noncode.sh +31 -0
  83. package/runtime/pi/bin/person.py +610 -0
  84. package/runtime/pi/bin/person.sh +448 -0
  85. package/runtime/pi/bin/pi-branch-policy.mjs +164 -4
  86. package/runtime/pi/bin/pi-product-workflows.mjs +31 -2
  87. package/runtime/pi/bin/publish-artifact.sh +14 -0
  88. package/runtime/pi/bin/session-autosave.sh +184 -0
  89. package/runtime/pi/bin/session-log.sh +199 -0
  90. package/runtime/pi/bin/settings.sh +274 -0
  91. package/runtime/pi/manifest.json +20 -1
@@ -0,0 +1,614 @@
1
+ #!/usr/bin/env python3
2
+ """Deterministic, org-scoped intake substrate for Egregore.
3
+
4
+ The agent skill owns interpretation and curation. This program owns the parts
5
+ that must not depend on model judgment: stable identities, provenance,
6
+ deterministic chunks, boundary metadata, manifests, and retrieval filtering.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import hashlib
13
+ import html
14
+ import json
15
+ import mimetypes
16
+ import os
17
+ import re
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ import zipfile
22
+ from datetime import datetime, timezone
23
+ from pathlib import Path
24
+ from xml.etree import ElementTree
25
+
26
+
27
+ ROOT = Path(__file__).resolve().parent.parent
28
+ CONFIG = ROOT / "egregore.json"
29
+ TEXT_EXTS = {".txt", ".md", ".markdown", ".rst", ".csv", ".tsv", ".json", ".jsonl", ".yaml", ".yml", ".xml"}
30
+ HTML_EXTS = {".html", ".htm"}
31
+ SELECTION_SCHEMA = "egregore-ingest-selection/v1"
32
+ EXTRACTION_SCHEMA = "egregore-ingest-extraction/v1"
33
+ CORPUS_SCHEMA = "egregore-ingest-corpus/v1"
34
+
35
+
36
+ def load_config() -> dict:
37
+ with CONFIG.open(encoding="utf-8") as handle:
38
+ return json.load(handle)
39
+
40
+
41
+ def metadata_root() -> Path:
42
+ override = os.environ.get("EGREGORE_INGEST_META_ROOT")
43
+ return Path(override).resolve() if override else (ROOT / "memory" / "ingest").resolve()
44
+
45
+
46
+ def data_root() -> Path:
47
+ override = os.environ.get("EGREGORE_INGEST_ROOT")
48
+ return Path(override).resolve() if override else (ROOT / ".egregore" / "ingest").resolve()
49
+
50
+
51
+ def staging_root() -> Path:
52
+ override = os.environ.get("EGREGORE_INGEST_STAGING_ROOT")
53
+ return Path(override).resolve() if override else (ROOT / ".egregore" / "ingest-staging").resolve()
54
+
55
+
56
+ def producer_session_id() -> str:
57
+ trusted = os.environ.get("EGREGORE_SESSION_ID", "").strip()
58
+ if trusted:
59
+ return trusted
60
+ session_file = ROOT / ".egregore-session-id"
61
+ if session_file.is_file():
62
+ return session_file.read_text(encoding="utf-8").strip()
63
+ return ""
64
+
65
+
66
+ def slug(value: str) -> str:
67
+ result = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
68
+ if not result:
69
+ raise ValueError("value must contain at least one letter or number")
70
+ return result
71
+
72
+
73
+ def digest(value: bytes | str, length: int = 24) -> str:
74
+ raw = value.encode("utf-8") if isinstance(value, str) else value
75
+ return hashlib.sha256(raw).hexdigest()[:length]
76
+
77
+
78
+ def hash_file(path: Path) -> tuple[str, int]:
79
+ hasher = hashlib.sha256()
80
+ size = 0
81
+ with path.open("rb") as handle:
82
+ while block := handle.read(1024 * 1024):
83
+ hasher.update(block)
84
+ size += len(block)
85
+ return hasher.hexdigest(), size
86
+
87
+
88
+ def parse_boundaries(items: list[str]) -> dict[str, str]:
89
+ result: dict[str, str] = {}
90
+ for item in items:
91
+ if "=" not in item:
92
+ raise ValueError(f"boundary must be key=value: {item}")
93
+ key, value = item.split("=", 1)
94
+ key = slug(key)
95
+ value = value.strip()
96
+ if not value:
97
+ raise ValueError(f"boundary value is empty: {item}")
98
+ result[key] = value
99
+ return dict(sorted(result.items()))
100
+
101
+
102
+ def read_text(path: Path) -> tuple[str | None, str | None, str | None]:
103
+ ext = path.suffix.lower()
104
+ try:
105
+ if ext in TEXT_EXTS:
106
+ return path.read_text(encoding="utf-8", errors="replace"), None, "builtin-text"
107
+ if ext in HTML_EXTS:
108
+ raw = path.read_text(encoding="utf-8", errors="replace")
109
+ raw = re.sub(r"(?is)<(script|style).*?>.*?</\1>", " ", raw)
110
+ return html.unescape(re.sub(r"(?s)<[^>]+>", " ", raw)), None, "builtin-html"
111
+ if ext == ".docx":
112
+ with zipfile.ZipFile(path) as archive:
113
+ raw = archive.read("word/document.xml")
114
+ root = ElementTree.fromstring(raw)
115
+ return "\n".join(t.text or "" for t in root.iter() if t.tag.endswith("}t")), None, "builtin-docx"
116
+ if ext == ".pdf":
117
+ tool = shutil.which("pdftotext")
118
+ if not tool:
119
+ return None, "pdf requires a text-layer or runtime-native extraction", None
120
+ proc = subprocess.run([tool, str(path), "-"], check=False, capture_output=True, text=True)
121
+ if proc.returncode:
122
+ return None, f"pdftotext failed ({proc.returncode})", None
123
+ return proc.stdout, None, "pdftotext"
124
+ except (OSError, ValueError, zipfile.BadZipFile, ElementTree.ParseError) as exc:
125
+ return None, str(exc), None
126
+ return None, f"unsupported extension {ext or '(none)'}", None
127
+
128
+
129
+ def chunks(text: str, limit: int = 7000) -> list[str]:
130
+ paragraphs = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()]
131
+ if not paragraphs and text.strip():
132
+ paragraphs = [text.strip()]
133
+ result: list[str] = []
134
+ current = ""
135
+ for paragraph in paragraphs:
136
+ pieces = [paragraph[i : i + limit] for i in range(0, len(paragraph), limit)] or [""]
137
+ for piece in pieces:
138
+ candidate = f"{current}\n\n{piece}".strip() if current else piece
139
+ if current and len(candidate) > limit:
140
+ result.append(current)
141
+ current = piece
142
+ else:
143
+ current = candidate
144
+ if current:
145
+ result.append(current)
146
+ return result
147
+
148
+
149
+ def source_dir(source_id: str) -> Path:
150
+ return metadata_root() / "sources" / slug(source_id)
151
+
152
+
153
+ def load_manifest(directory: Path) -> dict:
154
+ path = directory / "manifest.json"
155
+ if not path.exists():
156
+ return {"documents": []}
157
+ return json.loads(path.read_text(encoding="utf-8"))
158
+
159
+
160
+ def atomic_json(path: Path, value: object) -> None:
161
+ path.parent.mkdir(parents=True, exist_ok=True)
162
+ temporary = path.with_suffix(path.suffix + ".tmp")
163
+ temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
164
+ temporary.replace(path)
165
+
166
+
167
+ def atomic_text(path: Path, value: str) -> None:
168
+ path.parent.mkdir(parents=True, exist_ok=True)
169
+ temporary = path.with_suffix(path.suffix + ".tmp")
170
+ temporary.write_text(value, encoding="utf-8")
171
+ temporary.replace(path)
172
+
173
+
174
+ def candidate_files(path: Path) -> tuple[Path, list[Path]]:
175
+ resolved = path.resolve()
176
+ if resolved.is_file():
177
+ return resolved.parent, [resolved]
178
+ if not resolved.is_dir():
179
+ raise ValueError(f"source path does not exist: {path}")
180
+ files = [
181
+ p
182
+ for p in resolved.rglob("*")
183
+ if p.is_file()
184
+ and not p.is_symlink()
185
+ and not any(part.startswith(".") for part in p.relative_to(resolved).parts)
186
+ ]
187
+ return resolved, sorted(files, key=lambda p: p.as_posix())
188
+
189
+
190
+ def add_path(args: argparse.Namespace) -> dict:
191
+ config = load_config()
192
+ org = slug(config.get("slug") or "egregore")
193
+ source_id = slug(args.source)
194
+ boundaries = parse_boundaries(args.boundary)
195
+ input_path = Path(args.path).resolve()
196
+ base, files = candidate_files(input_path)
197
+ directory = source_dir(source_id)
198
+ docs_dir = data_root() / "sources" / source_id / "documents"
199
+ docs_dir.mkdir(parents=True, exist_ok=True)
200
+ existing_manifest = load_manifest(directory)
201
+ previous = {d["id"]: d for d in existing_manifest.get("documents", [])}
202
+ now = datetime.now(timezone.utc).isoformat()
203
+ ingested = unchanged = metadata_updated = skipped = pruned = 0
204
+ errors: list[dict] = []
205
+ seen_paths: set[str] = set()
206
+
207
+ for path in files:
208
+ relative = path.relative_to(base).as_posix() if path != base else path.name
209
+ seen_paths.add(relative)
210
+ doc_id = digest(f"{org}\0{source_id}\0{relative}")
211
+ content_hash, size_bytes = hash_file(path)
212
+ existing = previous.get(doc_id)
213
+ registered = getattr(args, "extractions", {}).get(relative)
214
+ if (
215
+ existing
216
+ and existing.get("content_hash") == content_hash
217
+ and existing.get("boundaries", {}) == boundaries
218
+ and not registered
219
+ and existing.get("status") == "unverified"
220
+ ):
221
+ unchanged += 1
222
+ continue
223
+ if registered:
224
+ text, error = registered["text"], None
225
+ extraction = {"kind": "runtime", "extractor": registered["extractor"]}
226
+ else:
227
+ text, error, extractor = read_text(path)
228
+ extraction = {"kind": "local", "extractor": extractor} if extractor else None
229
+ if error or text is None or not text.strip():
230
+ skipped += 1
231
+ errors.append({"path": relative, "error": error or "empty extracted text"})
232
+ if existing:
233
+ normalized = data_root() / existing["file_path"]
234
+ normalized.unlink(missing_ok=True)
235
+ previous[doc_id] = {
236
+ **existing,
237
+ "content_hash": content_hash,
238
+ "revision": content_hash[:16],
239
+ "mime": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
240
+ "bytes": size_bytes,
241
+ "chunks": [],
242
+ "extraction": None,
243
+ "boundaries": boundaries,
244
+ "status": "extraction_failed",
245
+ "ingested_at": now,
246
+ }
247
+ continue
248
+ normalized_hash = hashlib.sha256(text.encode()).hexdigest()
249
+ if (
250
+ existing
251
+ and existing.get("content_hash") == content_hash
252
+ and existing.get("normalized_content_hash") == normalized_hash
253
+ and existing.get("boundaries", {}) == boundaries
254
+ and existing.get("status") == "unverified"
255
+ ):
256
+ unchanged += 1
257
+ continue
258
+ document_chunks = chunks(text)
259
+ chunk_rows = []
260
+ body = []
261
+ for index, content in enumerate(document_chunks, 1):
262
+ chunk_id = f"{doc_id}-c{index:04d}-{digest(content, 8)}"
263
+ chunk_rows.append({"id": chunk_id, "index": index, "sha256": hashlib.sha256(content.encode()).hexdigest()})
264
+ body.append(f"## Chunk {index:04d}\n\n<!-- ingest-chunk: {chunk_id} -->\n\n{content}")
265
+ out_path = docs_dir / f"{doc_id}.md"
266
+ frontmatter = {
267
+ "id": doc_id,
268
+ "type": "ingest-document",
269
+ "org": org,
270
+ "source_id": source_id,
271
+ "source_path": relative,
272
+ "title": path.stem,
273
+ "content_hash": content_hash,
274
+ "normalized_content_hash": normalized_hash,
275
+ "revision": content_hash[:16],
276
+ "status": "unverified",
277
+ "boundaries": boundaries,
278
+ "extraction": extraction,
279
+ "ingested_at": now,
280
+ }
281
+ yaml_lines = ["---"] + [f"{key}: {json.dumps(value, ensure_ascii=False)}" for key, value in frontmatter.items()] + ["---", ""]
282
+ atomic_text(out_path, "\n".join(yaml_lines) + f"# {path.stem}\n\n" + "\n\n".join(body) + "\n")
283
+ previous[doc_id] = {
284
+ "id": doc_id,
285
+ "title": path.stem,
286
+ "source_path": relative,
287
+ "file_path": out_path.relative_to(data_root()).as_posix(),
288
+ "content_hash": content_hash,
289
+ "normalized_content_hash": normalized_hash,
290
+ "revision": content_hash[:16],
291
+ "mime": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
292
+ "bytes": size_bytes,
293
+ "chunks": chunk_rows,
294
+ "extraction": extraction,
295
+ "boundaries": boundaries,
296
+ "status": "unverified",
297
+ "ingested_at": now,
298
+ }
299
+ if existing and existing.get("content_hash") == content_hash:
300
+ metadata_updated += 1
301
+ else:
302
+ ingested += 1
303
+
304
+ tombstones = existing_manifest.get("tombstones", [])
305
+ if args.prune:
306
+ if not input_path.is_dir():
307
+ raise ValueError("--prune requires a directory snapshot")
308
+ for doc_id, document in list(previous.items()):
309
+ if document["source_path"] in seen_paths:
310
+ continue
311
+ normalized = data_root() / document["file_path"]
312
+ if normalized.is_file():
313
+ normalized.unlink()
314
+ tombstones.append({
315
+ "id": doc_id,
316
+ "source_path": document["source_path"],
317
+ "content_hash": document["content_hash"],
318
+ "deleted_at": now,
319
+ })
320
+ del previous[doc_id]
321
+ pruned += 1
322
+ # A path can disappear in one authoritative snapshot and return later.
323
+ # Current documents always win over historical deletion records.
324
+ tombstones = [row for row in tombstones if row["id"] not in previous]
325
+
326
+ source_record = {
327
+ "id": source_id,
328
+ "org": org,
329
+ "name": args.name or source_id,
330
+ "kind": args.kind,
331
+ "boundaries": boundaries,
332
+ "root_hint": base.name,
333
+ "updated_at": now,
334
+ }
335
+ atomic_json(directory / "source.json", source_record)
336
+ atomic_json(
337
+ directory / "manifest.json",
338
+ {
339
+ "schema": CORPUS_SCHEMA,
340
+ "producer_session": producer_session_id(),
341
+ "source": source_record,
342
+ "documents": sorted(previous.values(), key=lambda d: d["id"]),
343
+ "tombstones": tombstones,
344
+ "errors": errors,
345
+ },
346
+ )
347
+ return {"org": org, "source": source_id, "ingested": ingested, "unchanged": unchanged, "metadata_updated": metadata_updated, "skipped": skipped, "pruned": pruned, "documents": len(previous), "metadata_root": str(directory), "data_root": str(docs_dir)}
348
+
349
+
350
+ def cmd_add(args: argparse.Namespace) -> int:
351
+ print(json.dumps(add_path(args), indent=2))
352
+ return 0
353
+
354
+
355
+ def selection_relative_path(value: object) -> str:
356
+ if not isinstance(value, str) or not value or "\x00" in value or "\\" in value:
357
+ raise ValueError("selection contains an invalid relative path")
358
+ candidate = Path(value)
359
+ if candidate.is_absolute() or any(part in {"", ".", ".."} or part.startswith(".") for part in candidate.parts):
360
+ raise ValueError(f"selection path must be visible and relative: {value}")
361
+ return candidate.as_posix()
362
+
363
+
364
+ def validate_selection(path: Path) -> tuple[dict, Path]:
365
+ manifest_path = path.resolve()
366
+ staging_base = staging_root()
367
+ if manifest_path.name != "selection.json" or manifest_path.parent.parent != staging_base:
368
+ raise ValueError("selection manifest must be inside the local ingest staging root")
369
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
370
+ if manifest.get("schema") != SELECTION_SCHEMA:
371
+ raise ValueError("unsupported selection manifest schema")
372
+ if "org" in manifest:
373
+ raise ValueError("selection manifest cannot supply an org")
374
+ if manifest.get("session_id") != manifest_path.parent.name:
375
+ raise ValueError("selection session id does not match its staging directory")
376
+ if Path(str(manifest.get("staging_root", ""))).resolve() != manifest_path.parent:
377
+ raise ValueError("selection staging root does not match the manifest location")
378
+
379
+ source = manifest.get("source")
380
+ if not isinstance(source, dict) or "org" in source:
381
+ raise ValueError("selection source contract is invalid")
382
+ source_id = slug(str(source.get("id", "")))
383
+ if source_id != source.get("id"):
384
+ raise ValueError("selection source id must already be a normalized slug")
385
+ name = str(source.get("name", "")).strip()
386
+ if not name or len(name) > 200:
387
+ raise ValueError("selection source name is invalid")
388
+ if source.get("kind") != "files":
389
+ raise ValueError("local selections must use source kind files")
390
+ boundaries = source.get("boundaries", {})
391
+ if not isinstance(boundaries, dict):
392
+ raise ValueError("selection boundaries must be an object")
393
+ normalized_boundaries = parse_boundaries([f"{key}={value}" for key, value in boundaries.items()])
394
+ if normalized_boundaries != boundaries:
395
+ raise ValueError("selection boundary keys must already be normalized slugs")
396
+
397
+ files_root = manifest_path.parent / "files"
398
+ items = manifest.get("items")
399
+ if not isinstance(items, list) or not items:
400
+ raise ValueError("selection must contain at least one item")
401
+ declared: set[str] = set()
402
+ for item in items:
403
+ if not isinstance(item, dict):
404
+ raise ValueError("selection item must be an object")
405
+ relative = selection_relative_path(item.get("relative_path"))
406
+ if relative in declared:
407
+ raise ValueError(f"duplicate selection path: {relative}")
408
+ declared.add(relative)
409
+ expected = (files_root / relative).resolve()
410
+ if Path(str(item.get("local_path", ""))).resolve() != expected or files_root.resolve() not in expected.parents:
411
+ raise ValueError(f"selection item escaped its staging root: {relative}")
412
+ if not expected.is_file() or expected.is_symlink():
413
+ raise ValueError(f"selection item is missing or unsafe: {relative}")
414
+ content_hash, size_bytes = hash_file(expected)
415
+ if item.get("sha256") != content_hash or item.get("bytes") != size_bytes:
416
+ raise ValueError(f"selection item changed after confirmation: {relative}")
417
+
418
+ actual = {
419
+ candidate.relative_to(files_root).as_posix()
420
+ for candidate in files_root.rglob("*")
421
+ if candidate.is_file() and not candidate.is_symlink()
422
+ }
423
+ if actual != declared:
424
+ raise ValueError("staging directory does not match the confirmed selection")
425
+ return manifest, files_root
426
+
427
+
428
+ def registered_extractions(manifest: dict) -> dict[str, dict]:
429
+ session_root = Path(manifest["staging_root"])
430
+ directory = session_root / "extractions"
431
+ if not directory.exists():
432
+ return {}
433
+ declared = {item["relative_path"]: item for item in manifest["items"]}
434
+ result: dict[str, dict] = {}
435
+ for sidecar_path in sorted(directory.glob("*.json")):
436
+ sidecar = json.loads(sidecar_path.read_text(encoding="utf-8"))
437
+ if sidecar.get("schema") != EXTRACTION_SCHEMA:
438
+ raise ValueError(f"unsupported extraction sidecar: {sidecar_path.name}")
439
+ relative = selection_relative_path(sidecar.get("relative_path"))
440
+ item = declared.get(relative)
441
+ if not item:
442
+ raise ValueError(f"extraction does not belong to this selection: {relative}")
443
+ if sidecar_path.name != f"{digest(relative)}.json":
444
+ raise ValueError(f"extraction sidecar has an invalid name: {relative}")
445
+ if sidecar.get("source_sha256") != item["sha256"]:
446
+ raise ValueError(f"extraction source hash does not match: {relative}")
447
+ extractor = str(sidecar.get("extractor", "")).strip()
448
+ text = sidecar.get("text")
449
+ if not extractor or len(extractor) > 100 or not isinstance(text, str) or not text.strip():
450
+ raise ValueError(f"extraction sidecar is incomplete: {relative}")
451
+ result[relative] = {"extractor": extractor, "text": text}
452
+ return result
453
+
454
+
455
+ def cmd_register_extraction(args: argparse.Namespace) -> int:
456
+ manifest, _ = validate_selection(Path(args.manifest))
457
+ relative = selection_relative_path(args.relative_path)
458
+ item = next((row for row in manifest["items"] if row["relative_path"] == relative), None)
459
+ if not item:
460
+ raise ValueError(f"file is not part of this selection: {relative}")
461
+ extractor = args.extractor.strip()
462
+ if not extractor or len(extractor) > 100:
463
+ raise ValueError("extractor name is invalid")
464
+ text = sys.stdin.read()
465
+ if not text.strip():
466
+ raise ValueError("registered extraction is empty")
467
+ directory = Path(manifest["staging_root"]) / "extractions"
468
+ path = directory / f"{digest(relative)}.json"
469
+ atomic_json(path, {
470
+ "schema": EXTRACTION_SCHEMA,
471
+ "relative_path": relative,
472
+ "source_sha256": item["sha256"],
473
+ "extractor": extractor,
474
+ "text": text,
475
+ })
476
+ print(json.dumps({"registered": relative, "extractor": extractor, "sidecar": str(path)}))
477
+ return 0
478
+
479
+
480
+ def cmd_add_selection(args: argparse.Namespace) -> int:
481
+ manifest, files_root = validate_selection(Path(args.manifest))
482
+ source = manifest["source"]
483
+ add_args = argparse.Namespace(
484
+ path=str(files_root),
485
+ source=source["id"],
486
+ name=source["name"],
487
+ kind="files",
488
+ boundary=[f"{key}={value}" for key, value in source.get("boundaries", {}).items()],
489
+ prune=bool(source.get("authoritative_snapshot", False)),
490
+ extractions=registered_extractions(manifest),
491
+ )
492
+ summary = add_path(add_args)
493
+ cleaned = summary["skipped"] == 0
494
+ if cleaned:
495
+ shutil.rmtree(Path(manifest["staging_root"]), ignore_errors=True)
496
+ summary["selection_files"] = len(manifest["items"])
497
+ summary["staging_cleaned"] = cleaned
498
+ if not cleaned:
499
+ summary["selection_path"] = str(Path(args.manifest).resolve())
500
+ print(json.dumps(summary, indent=2))
501
+ return 0
502
+
503
+
504
+ def all_sources() -> list[tuple[dict, dict]]:
505
+ base = metadata_root() / "sources"
506
+ if not base.exists():
507
+ return []
508
+ result = []
509
+ for manifest_path in sorted(base.glob("*/manifest.json")):
510
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
511
+ result.append((manifest.get("source", {}), manifest))
512
+ return result
513
+
514
+
515
+ def boundaries_match(actual: dict, required: dict) -> bool:
516
+ return all(str(actual.get(key, "")) == str(value) for key, value in required.items())
517
+
518
+
519
+ def cmd_filter_results(args: argparse.Namespace) -> int:
520
+ required = parse_boundaries(args.boundary)
521
+ allowed: set[str] = set()
522
+ for source, manifest in all_sources():
523
+ if args.source and source.get("id") != slug(args.source):
524
+ continue
525
+ if not boundaries_match(source.get("boundaries", {}), required):
526
+ continue
527
+ allowed.update(d["file_path"] for d in manifest.get("documents", []) if d.get("status") != "extraction_failed")
528
+ results = json.load(sys.stdin)
529
+ filtered = []
530
+ for item in results if isinstance(results, list) else []:
531
+ file_name = re.sub(r"^qmd://[^/]+/", "", item.get("file", ""))
532
+ if file_name in allowed:
533
+ filtered.append(item)
534
+ if len(filtered) >= args.limit:
535
+ break
536
+ print(json.dumps(filtered, ensure_ascii=False))
537
+ return 0
538
+
539
+
540
+ def cmd_status(_: argparse.Namespace) -> int:
541
+ sources = all_sources()
542
+ documents = sum(len(m.get("documents", [])) for _, m in sources)
543
+ chunks_count = sum(len(d.get("chunks", [])) for _, m in sources for d in m.get("documents", []))
544
+ errors = sum(len(m.get("errors", [])) for _, m in sources)
545
+ cached = sum(1 for _, m in sources for d in m.get("documents", []) if (data_root() / d["file_path"]).is_file())
546
+ state_dir = data_root() / ".state"
547
+ pending = []
548
+ if state_dir.exists():
549
+ pending = [json.loads(path.read_text(encoding="utf-8")) for path in sorted(state_dir.glob("*.json"))]
550
+ print(json.dumps({"org": slug(load_config().get("slug") or "egregore"), "metadata_root": str(metadata_root()), "data_root": str(data_root()), "staging_root": str(staging_root()), "sources": len(sources), "documents": documents, "cached_documents": cached, "chunks": chunks_count, "errors": errors, "pending_recovery": pending}, indent=2))
551
+ return 0
552
+
553
+
554
+ def cmd_journal(args: argparse.Namespace) -> int:
555
+ path = data_root() / ".state" / f"{slug(args.source)}.json"
556
+ if args.clear:
557
+ path.unlink(missing_ok=True)
558
+ return 0
559
+ detail = json.loads(args.detail) if args.detail else {}
560
+ atomic_json(path, {
561
+ "source": slug(args.source),
562
+ "phase": args.phase,
563
+ "detail": detail,
564
+ "updated_at": datetime.now(timezone.utc).isoformat(),
565
+ })
566
+ return 0
567
+
568
+
569
+ def parser() -> argparse.ArgumentParser:
570
+ result = argparse.ArgumentParser(description=__doc__)
571
+ sub = result.add_subparsers(dest="command", required=True)
572
+ add = sub.add_parser("add")
573
+ add.add_argument("path")
574
+ add.add_argument("--source", required=True, help="stable connector/dataset id")
575
+ add.add_argument("--name")
576
+ add.add_argument("--kind", default="files")
577
+ add.add_argument("--boundary", action="append", default=[])
578
+ add.add_argument("--prune", action="store_true", help="tombstone files absent from this authoritative directory snapshot")
579
+ add.set_defaults(func=cmd_add)
580
+ add_selection = sub.add_parser("add-selection")
581
+ add_selection.add_argument("manifest")
582
+ add_selection.set_defaults(func=cmd_add_selection)
583
+ extraction = sub.add_parser("register-extraction")
584
+ extraction.add_argument("manifest")
585
+ extraction.add_argument("relative_path")
586
+ extraction.add_argument("--extractor", required=True)
587
+ extraction.set_defaults(func=cmd_register_extraction)
588
+ filt = sub.add_parser("filter-results")
589
+ filt.add_argument("--source")
590
+ filt.add_argument("--boundary", action="append", default=[])
591
+ filt.add_argument("--limit", type=int, default=8)
592
+ filt.set_defaults(func=cmd_filter_results)
593
+ status = sub.add_parser("status")
594
+ status.set_defaults(func=cmd_status)
595
+ journal = sub.add_parser("journal")
596
+ journal.add_argument("--source", required=True)
597
+ journal.add_argument("--phase", default="pending")
598
+ journal.add_argument("--detail")
599
+ journal.add_argument("--clear", action="store_true")
600
+ journal.set_defaults(func=cmd_journal)
601
+ return result
602
+
603
+
604
+ def main() -> int:
605
+ try:
606
+ args = parser().parse_args()
607
+ return args.func(args)
608
+ except (ValueError, OSError, json.JSONDecodeError) as exc:
609
+ print(f"ingest: {exc}", file=sys.stderr)
610
+ return 2
611
+
612
+
613
+ if __name__ == "__main__":
614
+ raise SystemExit(main())