@antoneeo/kb-agentic-skill 1.38.0 → 1.40.0

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.
@@ -19,6 +19,7 @@ from pathlib import Path
19
19
  import sdlc_core
20
20
  from sdlc_core import * # compatibility with the existing KB implementation
21
21
  from sdlc_core import _map_refs
22
+ from sdlc_core import _memory_safe # F-101: moved to the core, the agent home reader confines with it
22
23
 
23
24
  # --------------------------------------------------------------- claim ledger
24
25
  # F-025. The machine detects and holds; it never decides. Every function below
@@ -413,6 +414,15 @@ def kb_check_claims(root):
413
414
  "origin cannot be reopened is model knowledge"
414
415
  % (where, src))
415
416
  continue
417
+ if not kb_corpus_file(posixpath.normpath(path_s.replace("\\", "/"))):
418
+ # F-102: the source travels with the claim, and only corpus
419
+ # files land in a receiving project.
420
+ warnings.append("%s: source %r is not a corpus file -- every "
421
+ "source enters the corpus first (distillation.md "
422
+ "§1): bring it into corpus/given/ and cite it "
423
+ "there; for a guide, cite the given/ artifact it "
424
+ "was distilled from, or do not hold the statement "
425
+ "as a claim" % (where, src))
416
426
  kb_check_locator(target, loc, where, errors, loc_cache)
417
427
  # --- provenance ---
418
428
  prov = row["prov"]
@@ -1534,6 +1544,19 @@ def kb_credential_errors(root, docs):
1534
1544
  "redact into a new snapshot (its name changes) and update %s's "
1535
1545
  "distilled_from, source_hash and markers, or declare "
1536
1546
  "`credential_scan: reviewed -- <reason>` in the guide" % rel))
1547
+ # F-101 FS8: set-aside guides are not listed as guides, so their snapshots
1548
+ # get a walk of their own -- a colleague's secret is caught before promotion.
1549
+ aside = docs / KB_SET_ASIDE / ".sources"
1550
+ if aside.is_dir() and _memory_safe(docs, aside):
1551
+ for p in sorted(aside.iterdir()):
1552
+ if not p.is_file() or p.is_symlink():
1553
+ continue
1554
+ found = kb_credential_findings(p)
1555
+ if found:
1556
+ errors.append(_kb_cred_message(
1557
+ "%s/.sources/%s" % (KB_SET_ASIDE, p.name), found,
1558
+ "a set-aside snapshot from another project: discard its guide "
1559
+ "(`imported discard`) or ask the sender for a redacted module"))
1537
1560
  return errors
1538
1561
 
1539
1562
 
@@ -1686,6 +1709,8 @@ def kb_time_cycle(docs):
1686
1709
  rel = p.relative_to(docs).as_posix()
1687
1710
  if rel.startswith("corpus/given/"):
1688
1711
  continue
1712
+ if any(part.startswith(".") for part in rel.split("/")[:-1]):
1713
+ continue # F-101 P6: a dot-folder (reference/.imported/) is no living document
1689
1714
  try:
1690
1715
  text = sdlc_core.read_text(p)
1691
1716
  except Exception:
@@ -1918,10 +1943,13 @@ def kb_export_closure(docs, slugs):
1918
1943
  return selected, artifacts, added, errors
1919
1944
 
1920
1945
 
1921
- def kb_bundle_write(docs, out, selected, artifacts, project):
1946
+ def kb_bundle_write(docs, out, selected, artifacts, project, guides=None):
1922
1947
  """Write the bundle. Mirrors the docs-root layout; no path is rewritten.
1923
1948
  Returns whether a not-yet-honored mark was dropped (F-080) -- a yes/no,
1924
- never a count: a count of dropped marks is a count of claims by the mark."""
1949
+ never a count: a count of dropped marks is a count of claims by the mark.
1950
+ `guides` (F-101, kb_guide_selection's carried list): each guide, with the
1951
+ snapshot or corpus artifact it rests on; any guide makes the bundle
1952
+ version 2, so an importer that cannot set guides aside refuses it."""
1925
1953
  out.mkdir(parents=True, exist_ok=True)
1926
1954
  (out / "topics").mkdir(exist_ok=True)
1927
1955
  dropped = False
@@ -1930,17 +1958,23 @@ def kb_bundle_write(docs, out, selected, artifacts, project):
1930
1958
  dropped = dropped or d
1931
1959
  text = kb_drop_declarations(text)
1932
1960
  (out / "topics" / p.name).write_text(text, encoding="utf-8")
1933
- for rel in artifacts:
1961
+ carried = ["reference/" + g["name"] for g in guides or ()]
1962
+ carried += [rel for g in guides or () for rel in g["files"] if rel not in artifacts]
1963
+ for rel in list(artifacts) + carried:
1934
1964
  dst = out / rel
1935
1965
  dst.parent.mkdir(parents=True, exist_ok=True)
1936
1966
  dst.write_bytes((docs / rel).read_bytes())
1937
- lines = ["---", "kb_bundle: 1", "source_project: %s" % project,
1967
+ lines = ["---", "kb_bundle: %d" % (KB_BUNDLE_GUIDES if guides else 1),
1968
+ "source_project: %s" % project,
1938
1969
  "topics: [%s]" % ", ".join(sorted(selected)),
1939
- "artifacts: %d" % len(artifacts), "---",
1970
+ "artifacts: %d" % len(artifacts)]
1971
+ if guides:
1972
+ lines.append("guides: [%s]" % ", ".join(g["name"] for g in guides))
1973
+ lines += ["---",
1940
1974
  "# KB bundle", "",
1941
1975
  "Import with `sdlc_check.py import <this directory>`. Additive: it "
1942
1976
  "never overwrites a node and never deletes anything.", ""]
1943
- for rel in artifacts:
1977
+ for rel in list(artifacts) + carried:
1944
1978
  lines.append("- `%s` sha256:%s" % (rel, kb_sha256_bytes(docs / rel)))
1945
1979
  (out / BUNDLE_MANIFEST).write_text("\n".join(lines) + "\n", encoding="utf-8")
1946
1980
  return dropped
@@ -1972,23 +2006,21 @@ def _kb_states(state):
1972
2006
 
1973
2007
  def _kb_bom_text(data):
1974
2008
  """(bom, text): a UTF-8 BOM (Windows authoring) is kept apart and given back
1975
- on write, as sdlc_core.read_text reads past it."""
1976
- bom = codecs.BOM_UTF8 if data.startswith(codecs.BOM_UTF8) else b""
1977
- return bom, data[len(bom):].decode("utf-8")
2009
+ on write, as sdlc_core.read_text reads past it. The handling lives in the
2010
+ core (sdlc_core.bom_text), shared with its frontmatter writer (F-101)."""
2011
+ return sdlc_core.bom_text(data)
1978
2012
 
1979
2013
 
1980
2014
  def _kb_foreign_note(data, project, rel):
1981
2015
  """F-083: the bytes of a ruling note as it lands in another project, and the
1982
2016
  number of lines inserted. Lines go right after the opening '---' with the
1983
2017
  note's own line ending; an existing origin line is rewritten in place, so it
1984
- moves nothing. None when the note opens no frontmatter."""
1985
- bom, text = _kb_bom_text(data)
1986
- nl = "\r\n" if "\r\n" in text else "\n"
1987
- lines = text.split(nl)
1988
- if not lines or lines[0].strip() != "---":
2018
+ moves nothing. None when the note opens no frontmatter. BOM, line ending and
2019
+ block bounds: sdlc_core.frontmatter_lines (F-101, P7: same bytes)."""
2020
+ try:
2021
+ bom, nl, lines, end = sdlc_core.frontmatter_lines(data)
2022
+ except sdlc_core.UnterminatedFrontmatter:
1989
2023
  return None
1990
- end = next((i for i in range(1, min(len(lines), 60)) if lines[i].strip() == "---"),
1991
- None)
1992
2024
  if end is None:
1993
2025
  return None
1994
2026
  inserted = ["imported_from: %s — %s" % (project, rel)]
@@ -1998,7 +2030,7 @@ def _kb_foreign_note(data, project, rel):
1998
2030
  if not origin:
1999
2031
  inserted.append("origin: imported")
2000
2032
  lines[1:1] = inserted
2001
- return bom + nl.join(lines).encode("utf-8"), len(inserted)
2033
+ return sdlc_core.frontmatter_bytes(bom, nl, lines), len(inserted)
2002
2034
 
2003
2035
 
2004
2036
  def _kb_shift_loc(loc, k):
@@ -2271,20 +2303,99 @@ def kb_import_foreign_rulings(bundle, docs, topic_rels, written, project):
2271
2303
  return content, drop, report, errors
2272
2304
 
2273
2305
 
2306
+ # F-102: what a bundle may carry. Only knowledge travels (portability.md):
2307
+ # topics and corpus files, flat -- the layout every corpus reader assumes. The
2308
+ # paths match EXACTLY; case-folding and trailing dots/spaces are used only to
2309
+ # refuse, so no variant reaches a reader that matches exactly.
2310
+ _KB_NOT_KNOWLEDGE = ("is not knowledge -- only knowledge travels; visions, guides, "
2311
+ "decisions and workstreams stay in the project that wrote them")
2312
+ _KB_NOT_FLAT = ("is not a flat topic or corpus file -- topics and corpus are flat, "
2313
+ "and indexes are regenerated, never imported")
2314
+ _KB_CLUTTER_NAMES = (".ds_store", "thumbs.db", "desktop.ini")
2315
+ _KB_NOT_FLAT_GUIDE = ("is not a flat guide or snapshot -- a module carries exactly "
2316
+ "reference/GUIDE_<name>.md and reference/.sources/<name>")
2317
+
2318
+
2319
+ def _kb_flat_name(rel, prefix):
2320
+ """The file name when `rel` sits directly in `prefix`, written exactly."""
2321
+ if not rel.startswith(prefix):
2322
+ return None
2323
+ name = rel[len(prefix):]
2324
+ if not name or "/" in name or name != name.rstrip(". ") \
2325
+ or name.lower() == "index.md":
2326
+ return None
2327
+ return name
2328
+
2329
+
2330
+ def kb_corpus_file(rel):
2331
+ """True when `rel` is exactly corpus/given/<name> or corpus/notes/<name>.md."""
2332
+ if _kb_flat_name(rel, "corpus/given/"):
2333
+ return True
2334
+ name = _kb_flat_name(rel, "corpus/notes/")
2335
+ return bool(name) and name.endswith(".md")
2336
+
2337
+
2338
+ def kb_knowledge_path(rel, version=1):
2339
+ """True when `rel` is a corpus file or exactly topics/<name>.md; never an index.
2340
+ From bundle version 2 (F-101) also exactly reference/GUIDE_<name>.md and
2341
+ reference/.sources/<name> -- which an import sets aside, never in force."""
2342
+ if kb_corpus_file(rel):
2343
+ return True
2344
+ name = _kb_flat_name(rel, "topics/")
2345
+ if bool(name) and name.endswith(".md"):
2346
+ return True
2347
+ return version >= KB_BUNDLE_GUIDES and bool(kb_bundle_guide(rel) or kb_bundle_snapshot(rel))
2348
+
2349
+
2350
+ def kb_bundle_guide(rel):
2351
+ """The guide file name when `rel` is exactly reference/GUIDE_<name>.md."""
2352
+ name = _kb_flat_name(rel, "reference/")
2353
+ return name if name and sdlc_core.SET_ASIDE_NAME_RE.fullmatch(name) else None
2354
+
2355
+
2356
+ def kb_bundle_snapshot(rel):
2357
+ """The snapshot file name when `rel` is exactly reference/.sources/<name>."""
2358
+ return _kb_flat_name(rel, "reference/.sources/")
2359
+
2360
+
2361
+ def kb_bundle_clutter(rel):
2362
+ """Operating-system files a folder picks up in transit: skipped, never refused."""
2363
+ parts = rel.split("/")
2364
+ name = parts[-1]
2365
+ return ("__MACOSX" in parts[:-1] or name.lower() in _KB_CLUTTER_NAMES
2366
+ or name.startswith("._"))
2367
+
2368
+
2369
+ def kb_bundle_refusal(rel, version=1):
2370
+ """None for a knowledge path, else the reason the bundle is refused."""
2371
+ if kb_knowledge_path(rel, version):
2372
+ return None
2373
+ top = rel.split("/", 1)[0].rstrip(". ").lower()
2374
+ if top == "reference" and version >= KB_BUNDLE_GUIDES:
2375
+ return _KB_NOT_FLAT_GUIDE
2376
+ return _KB_NOT_FLAT if top in ("topics", "corpus") else _KB_NOT_KNOWLEDGE
2377
+
2378
+
2274
2379
  def kb_import_plan(bundle, docs, report=None):
2275
2380
  """(writes, skipped_topics, dedup, errors) -- computed BEFORE anything is
2276
2381
  written, because an import that half-applies leaves a tree whose checks fail
2277
2382
  and whose owner cannot tell what landed. Each write is (rel, bytes, dst):
2278
2383
  the bytes are the bundle's, except where F-083 makes a foreign ruling land
2279
2384
  foreign (kb_import_foreign_rulings). `report`, when a dict, receives what
2280
- that conversion did."""
2385
+ that conversion did, and the operating-system files skipped (F-102)."""
2281
2386
  errors, writes, skipped, dedup = [], [], [], []
2282
2387
  man = bundle / BUNDLE_MANIFEST
2283
2388
  if not man.is_file():
2284
2389
  return [], [], [], ["not a kb bundle: no %s in %s" % (BUNDLE_MANIFEST, bundle)]
2285
2390
  meta = sdlc_core.load_frontmatter(sdlc_core.read_text(man).splitlines()) or {}
2286
- if str(meta.get("kb_bundle", "")).strip() != "1":
2391
+ version = str(meta.get("kb_bundle", "")).strip()
2392
+ if re.fullmatch(r"[0-9]+", version) and int(version) > KB_BUNDLE_GUIDES:
2393
+ return [], [], [], ["%s declares 'kb_bundle: %s': written by a newer version "
2394
+ "of the skill -- update the skill, then import again"
2395
+ % (BUNDLE_MANIFEST, version)]
2396
+ if version not in ("1", str(KB_BUNDLE_GUIDES)):
2287
2397
  return [], [], [], ["%s carries no 'kb_bundle: 1'" % BUNDLE_MANIFEST]
2398
+ ver = int(version)
2288
2399
 
2289
2400
  known_ids = set()
2290
2401
  target = kb_collect_topics(docs)
@@ -2293,7 +2404,8 @@ def kb_import_plan(bundle, docs, report=None):
2293
2404
  if r["id"]:
2294
2405
  known_ids.add(r["id"])
2295
2406
 
2296
- entries, topic_rels, written = [], [], set()
2407
+ entries, topic_rels, written, clutter = [], [], set(), []
2408
+ guide_files, snapshot_files = {}, {}
2297
2409
  for p in sorted(bundle.rglob("*")):
2298
2410
  if not p.is_file() or p.name == BUNDLE_MANIFEST:
2299
2411
  continue
@@ -2303,6 +2415,19 @@ def kb_import_plan(bundle, docs, report=None):
2303
2415
  errors.append("bundle entry %r escapes the docs root — refusing the "
2304
2416
  "whole import, not just this file" % rel)
2305
2417
  continue
2418
+ if kb_bundle_clutter(rel):
2419
+ clutter.append(rel)
2420
+ continue
2421
+ refusal = kb_bundle_refusal(rel, ver)
2422
+ if refusal:
2423
+ errors.append("bundle entry %r %s" % (rel, refusal))
2424
+ continue
2425
+ if kb_bundle_guide(rel):
2426
+ guide_files[kb_bundle_guide(rel)] = p
2427
+ continue
2428
+ if kb_bundle_snapshot(rel):
2429
+ snapshot_files[kb_bundle_snapshot(rel)] = p
2430
+ continue
2306
2431
  if rel.startswith("topics/"):
2307
2432
  topic_rels.append(rel)
2308
2433
  if dst.is_file():
@@ -2310,6 +2435,8 @@ def kb_import_plan(bundle, docs, report=None):
2310
2435
  continue
2311
2436
  written.add(rel)
2312
2437
  entries.append((rel, p, dst))
2438
+ if report is not None:
2439
+ report["clutter"] = clutter
2313
2440
  for rel, p, _dst in entries:
2314
2441
  if rel.startswith("topics/"):
2315
2442
  for r in kb_parse_claims(sdlc_core.read_text(p))[0]:
@@ -2341,6 +2468,21 @@ def kb_import_plan(bundle, docs, report=None):
2341
2468
  continue
2342
2469
  writes.append((rel, data, dst))
2343
2470
 
2471
+ if errors:
2472
+ return [], skipped, [], errors
2473
+ aside, guide_report = kb_set_aside_plan(
2474
+ docs, guide_files, snapshot_files, str(meta.get("source_project", "")).strip())
2475
+ escaping = [rel for rel, _data, dst in aside
2476
+ if sdlc_core.confine_under(docs, rel) is None
2477
+ or not sdlc_core.confined_no_links(docs, dst)]
2478
+ if escaping:
2479
+ return [], skipped, [], ["set-aside destination %r reaches outside the docs root "
2480
+ "(a link or junction on the way) -- refusing the whole "
2481
+ "import, not just this file" % rel for rel in escaping]
2482
+ writes += aside
2483
+ if report is not None:
2484
+ report.update(guide_report)
2485
+
2344
2486
  for rel, data, _dst in writes:
2345
2487
  if not rel.startswith("topics/"):
2346
2488
  continue
@@ -2351,6 +2493,226 @@ def kb_import_plan(bundle, docs, report=None):
2351
2493
  return writes, skipped, dedup, errors
2352
2494
 
2353
2495
 
2496
+ # ------------------------------------------------------- modules (F-101 B)
2497
+ # A module is a bundle that also carries the project's guides -- every one not
2498
+ # marked `personal: true`, code guides included -- each with the snapshot or the
2499
+ # corpus artifact it rests on. Knowledge crosses, authority does not
2500
+ # (portability.md par.4): a carried guide lands SET ASIDE in reference/.imported/
2501
+ # with its origin recorded, and governs nothing until the person says yes to it
2502
+ # and the agent runs `imported promote`.
2503
+ KB_BUNDLE_GUIDES = 2 # the bundle version that carries guides
2504
+ KB_SET_ASIDE = "/".join(sdlc_core.SET_ASIDE_PARTS)
2505
+ KB_DISCARDED = "DISCARDED.md"
2506
+ _KB_DISCARDED_RE = re.compile(r"^- `(GUIDE_[A-Za-z0-9_-]+\.md)` from (.+?)\s*$")
2507
+ KB_CODE_NOT_HERE = "the code this guide describes is not in this project"
2508
+
2509
+
2510
+ def _kb_guide_source(docs, meta):
2511
+ """(kind, [docs-relative files]) of what a guide rests on: ("snapshot",
2512
+ [reference/.sources/x]), ("corpus", [artifact, its sidecar if any]), or
2513
+ (None, []) when its `distilled_from:` is neither."""
2514
+ df = kb_unquote(meta.get("distilled_from"))
2515
+ target = sdlc_core.confine_under(docs.parent, df) if df else None
2516
+ try:
2517
+ if target is None or not target.is_file() or not _memory_safe(docs, target):
2518
+ return None, []
2519
+ rel = target.resolve().relative_to(docs.resolve()).as_posix()
2520
+ except (OSError, ValueError):
2521
+ return None, []
2522
+ if kb_bundle_snapshot(rel):
2523
+ return "snapshot", [rel]
2524
+ if kb_corpus_file(rel) and not rel.endswith(".meta.md"):
2525
+ side = rel + ".meta.md"
2526
+ return "corpus", [rel] + ([side] if (docs / side).is_file() else [])
2527
+ return None, []
2528
+
2529
+
2530
+ def kb_guide_selection(docs):
2531
+ """(carried, skipped) for an export (F-101 FS7): every guide of the project's
2532
+ router, flat reference/GUIDE_*.md, that is not `personal: true`. carried:
2533
+ [{"name", "kind" (code|document), "source" (snapshot|corpus|None),
2534
+ "files"}]; skipped: [(name, reason)]."""
2535
+ carried, skipped = [], []
2536
+ ref = docs / "reference"
2537
+ if not ref.is_dir() or not _memory_safe(docs, ref):
2538
+ return carried, skipped
2539
+ for p in sorted(ref.glob("GUIDE_*.md")):
2540
+ if not p.is_file() or not _memory_safe(docs, p):
2541
+ continue
2542
+ meta = sdlc_core.load_frontmatter(sdlc_core.read_text(p).splitlines()) or {}
2543
+ if kb_unquote(meta.get("personal")).lower() == "true":
2544
+ skipped.append((p.name, "marked personal"))
2545
+ continue
2546
+ source, files = _kb_guide_source(docs, meta)
2547
+ kind = "code" if kb_unquote(meta.get("source_kind")).lower() == "code" else "document"
2548
+ carried.append({"name": p.name, "kind": kind, "source": source, "files": files})
2549
+ return carried, skipped
2550
+
2551
+
2552
+ def kb_discarded(docs):
2553
+ """[(name, project)] recorded in reference/.imported/DISCARDED.md -- exact
2554
+ names and projects, compared for equality, never joined as paths (T12)."""
2555
+ p = docs / KB_SET_ASIDE / KB_DISCARDED
2556
+ if not p.is_file() or p.is_symlink():
2557
+ return []
2558
+ out = []
2559
+ for line in sdlc_core.read_text(p).splitlines():
2560
+ m = _KB_DISCARDED_RE.match(line)
2561
+ if m:
2562
+ out.append((m.group(1), m.group(2)))
2563
+ return out
2564
+
2565
+
2566
+ def _kb_snapshot_of(meta):
2567
+ """The snapshot file name a guide's `distilled_from:` names under
2568
+ reference/.sources/, or None."""
2569
+ df = kb_unquote(meta.get("distilled_from")).replace("\\", "/")
2570
+ head, _, name = df.rpartition("/")
2571
+ return name if name and head.endswith("reference/.sources") else None
2572
+
2573
+
2574
+ def kb_set_aside_plan(docs, guide_files, snapshot_files, project):
2575
+ """(writes, report) for the guides of a version-2 bundle (F-101 FS8). Each
2576
+ lands in reference/.imported/ with `imported_from:` (and, for a code guide,
2577
+ that its code is not here); its snapshot in reference/.imported/.sources/.
2578
+ A guide already in force, already set aside, or discarded before from the
2579
+ same project is skipped and named, never overwritten; so is its snapshot."""
2580
+ aside = docs / KB_SET_ASIDE
2581
+ discarded = set(kb_discarded(docs))
2582
+ origin = project or "unknown"
2583
+ writes, report = [], {"guides": [], "guides_skipped": []}
2584
+ skip_snaps = set()
2585
+ for name in sorted(guide_files):
2586
+ data = guide_files[name].read_bytes()
2587
+ meta = sdlc_core.load_frontmatter(sdlc_core.bom_text(data)[1].splitlines()) or {}
2588
+ why = None
2589
+ if (docs / "reference" / name).exists():
2590
+ why = "a guide of that name is in force here"
2591
+ elif (aside / name).exists():
2592
+ why = "a guide of that name is already set aside"
2593
+ elif (name, origin) in discarded:
2594
+ why = "discarded before (imported undiscard %s to take it again)" % name
2595
+ if why:
2596
+ report["guides_skipped"].append((name, why))
2597
+ skip_snaps.add(_kb_snapshot_of(meta))
2598
+ continue
2599
+ keys = {"imported_from": origin}
2600
+ if kb_unquote(meta.get("source_kind")).lower() == "code":
2601
+ keys["imported_note"] = KB_CODE_NOT_HERE
2602
+ try:
2603
+ data = sdlc_core.frontmatter_with_keys(data, keys)
2604
+ except ValueError as exc:
2605
+ report["guides_skipped"].append((name, "unreadable frontmatter: %s" % exc))
2606
+ skip_snaps.add(_kb_snapshot_of(meta))
2607
+ continue
2608
+ writes.append(("%s/%s" % (KB_SET_ASIDE, name), data, aside / name))
2609
+ report["guides"].append(name)
2610
+ for name in sorted(snapshot_files):
2611
+ if name in skip_snaps:
2612
+ continue
2613
+ data = snapshot_files[name].read_bytes()
2614
+ dst = aside / ".sources" / name
2615
+ if dst.exists():
2616
+ if not dst.is_file() or kb_sha256_bytes(dst) != hashlib.sha256(data).hexdigest():
2617
+ report["guides_skipped"].append(
2618
+ (".sources/" + name, "a set-aside snapshot of that name differs"))
2619
+ continue
2620
+ writes.append(("%s/.sources/%s" % (KB_SET_ASIDE, name), data, dst))
2621
+ return writes, report
2622
+
2623
+
2624
+ def kb_cmd_imported(root, docs, action, name):
2625
+ """`imported promote|discard|undiscard <GUIDE_x.md>` (F-101 FS8), run by the
2626
+ agent on the person's answer for that guide. `name` is matched against the
2627
+ set-aside listing (or DISCARDED.md), never joined as a path. Exit 2 with the
2628
+ reason, nothing changed, on a name not there or, for promote, in force."""
2629
+ aside = docs / KB_SET_ASIDE
2630
+
2631
+ def refuse(msg):
2632
+ print("[ERROR] imported %s: %s -- nothing changed." % (action, msg))
2633
+ return 2
2634
+ record = aside / KB_DISCARDED
2635
+ if action == "undiscard":
2636
+ if name not in {n for n, _p in kb_discarded(docs)}:
2637
+ return refuse("%r is not in %s/%s" % (name, KB_SET_ASIDE, KB_DISCARDED))
2638
+ if not sdlc_core.confined_no_links(docs, record):
2639
+ return refuse("%s/%s reaches outside the docs root (a link or junction on "
2640
+ "the way)" % (KB_SET_ASIDE, KB_DISCARDED))
2641
+ bom, text = sdlc_core.bom_text(record.read_bytes())
2642
+ nl = "\r\n" if "\r\n" in text else "\n"
2643
+ kept = [ln for ln in text.split(nl)
2644
+ if not (_KB_DISCARDED_RE.match(ln)
2645
+ and _KB_DISCARDED_RE.match(ln).group(1) == name)]
2646
+ record.write_bytes(bom + nl.join(kept).encode("utf-8"))
2647
+ print("[ok] %s removed from %s/%s: the next import sets it aside again"
2648
+ % (name, KB_SET_ASIDE, KB_DISCARDED))
2649
+ return 0
2650
+ listing = sdlc_core.set_aside_guides(root, docs.name)
2651
+ if name not in listing:
2652
+ return refuse("%r is not a set-aside guide (set aside: %s)"
2653
+ % (name, ", ".join(listing) or "none"))
2654
+ src = aside / name
2655
+ if not sdlc_core.confined_no_links(docs, src):
2656
+ return refuse("%s/%s reaches outside the docs root (a link or junction on the way)"
2657
+ % (KB_SET_ASIDE, name))
2658
+ meta = sdlc_core.load_frontmatter(sdlc_core.read_text(src).splitlines()) or {}
2659
+ snap = _kb_snapshot_of(meta)
2660
+ snap_src = aside / ".sources" / snap if snap else None
2661
+ if snap_src is not None and not (snap_src.is_file() and not snap_src.is_symlink()):
2662
+ snap_src = None
2663
+ if snap_src is not None and not sdlc_core.confined_no_links(docs, snap_src):
2664
+ return refuse("%s/.sources/%s reaches outside the docs root (a link or junction on "
2665
+ "the way)" % (KB_SET_ASIDE, snap))
2666
+ if action == "promote":
2667
+ dst = docs / "reference" / name
2668
+ targets = [dst] + ([docs / "reference" / ".sources" / snap] if snap_src else [])
2669
+ for target in targets:
2670
+ if not sdlc_core.confined_no_links(docs, target):
2671
+ return refuse("%s reaches outside the docs root (a link or junction on "
2672
+ "the way)" % target.relative_to(docs).as_posix())
2673
+ if dst.exists():
2674
+ return refuse("%s is already in force in reference/: it is never overwritten"
2675
+ % name)
2676
+ sdst = docs / "reference" / ".sources" / snap if snap_src else None
2677
+ if sdst is not None and sdst.exists() and (
2678
+ not sdst.is_file() or kb_sha256_bytes(sdst) != kb_sha256_bytes(snap_src)):
2679
+ return refuse("reference/.sources/%s exists with different bytes" % snap)
2680
+ dst.write_bytes(src.read_bytes())
2681
+ src.unlink()
2682
+ if sdst is not None:
2683
+ if not sdst.exists():
2684
+ sdst.parent.mkdir(parents=True, exist_ok=True)
2685
+ sdst.write_bytes(snap_src.read_bytes())
2686
+ snap_src.unlink()
2687
+ with sdlc_core._docs_dir_as(docs.name):
2688
+ (docs / "reference" / "INDEX.md").write_text(
2689
+ sdlc_core.build_guide_index(root), encoding="utf-8")
2690
+ print("[ok] reference/%s is in force%s; the guide router is regenerated. "
2691
+ "Once committed it governs everyone on the project." %
2692
+ (name, " (snapshot in reference/.sources/%s)" % snap if sdst is not None else ""))
2693
+ return 0
2694
+ origin = kb_unquote(meta.get("imported_from")) or "unknown"
2695
+ if not sdlc_core.confined_no_links(docs, record):
2696
+ return refuse("%s/%s reaches outside the docs root (a link or junction on the way)"
2697
+ % (KB_SET_ASIDE, KB_DISCARDED))
2698
+ src.unlink()
2699
+ if snap_src is not None:
2700
+ snap_src.unlink()
2701
+ line = "- `%s` from %s" % (name, origin)
2702
+ if record.is_file():
2703
+ bom, text = sdlc_core.bom_text(record.read_bytes())
2704
+ nl = "\r\n" if "\r\n" in text else "\n"
2705
+ record.write_bytes(bom + (text.rstrip("\r\n") + nl + line + nl).encode("utf-8"))
2706
+ else:
2707
+ record.write_text("# Discarded imported guides\n\nWritten by `imported discard`: "
2708
+ "a later import of the same guide from the same project skips "
2709
+ "it. `imported undiscard <name>` removes a line.\n\n%s\n" % line,
2710
+ encoding="utf-8")
2711
+ print("[ok] %s and its snapshot deleted (the bundle still holds them); recorded in "
2712
+ "%s/%s as discarded from %s" % (name, KB_SET_ASIDE, KB_DISCARDED, origin))
2713
+ return 0
2714
+
2715
+
2354
2716
  # ------------------------------------------------------------------ commands
2355
2717
 
2356
2718
  MEMORY_DIRS = ("vision", "reference", "architecture", "functional", "strategic",
@@ -2358,20 +2720,6 @@ MEMORY_DIRS = ("vision", "reference", "architecture", "functional", "strategic",
2358
2720
  "spikes", "topics", "corpus/notes")
2359
2721
 
2360
2722
 
2361
- def _memory_safe(docs, path):
2362
- """Reject links (including Windows junctions) and paths outside the docs root."""
2363
- try:
2364
- path.resolve().relative_to(docs.resolve())
2365
- for p in (path, *path.parents):
2366
- if p == docs.parent:
2367
- break
2368
- if p.is_symlink() or (hasattr(p, "is_junction") and p.is_junction()):
2369
- return False
2370
- return True
2371
- except (OSError, ValueError, RuntimeError):
2372
- return False
2373
-
2374
-
2375
2723
  def memory_records(docs):
2376
2724
  """Live metadata, not claims or work states. Never traverse raw corpus or logs."""
2377
2725
  paths = []
@@ -2484,7 +2832,7 @@ def kb_validate_surface(docs, full=False):
2484
2832
 
2485
2833
  INTERCEPTED = {"index", "validate", "check", "graph", "corpus", "claim-id",
2486
2834
  "anchor", "export", "import", "stale", "recall", "adopt",
2487
- "inventory"}
2835
+ "inventory", "imported"}
2488
2836
 
2489
2837
 
2490
2838
  def _kb_root(args):
@@ -3128,7 +3476,9 @@ def kb_cmd_export(args):
3128
3476
  root, docs = _kb_root(args)
3129
3477
  slugs = ([s.strip() for s in args.topics.split(",") if s.strip()]
3130
3478
  if args.topics else sorted(kb_collect_topics(docs)))
3131
- if not slugs:
3479
+ # F-101: a module may carry guides alone (R6, R11); with no topics and no
3480
+ # guide to carry, export still refuses as before.
3481
+ if not slugs and (getattr(args, "no_guides", False) or not kb_guide_selection(docs)[0]):
3132
3482
  print("[ERROR] no topics to export")
3133
3483
  return 2
3134
3484
  selected, artifacts, added, errors = kb_export_closure(docs, slugs)
@@ -3137,9 +3487,29 @@ def kb_cmd_export(args):
3137
3487
  if errors:
3138
3488
  return 1
3139
3489
  out = Path(args.out)
3140
- dropped = kb_bundle_write(docs, out, selected, artifacts, root.name)
3490
+ carried, not_carried = kb_guide_selection(docs)
3491
+ if getattr(args, "no_guides", False):
3492
+ not_carried = [(g["name"], "--no-guides: today's bundle version, for receivers "
3493
+ "not yet updated") for g in carried] + not_carried
3494
+ carried = []
3495
+ dropped = kb_bundle_write(docs, out, selected, artifacts, root.name, guides=carried)
3141
3496
  print("[ok] bundle written: %s" % out)
3142
3497
  print(" topics: %d, artifacts: %d" % (len(selected), len(artifacts)))
3498
+ # F-101 FS7: the exporter sees every guide that leaves, and every one that stays.
3499
+ for g in carried:
3500
+ how = {"snapshot": "with its snapshot",
3501
+ "corpus": "with the corpus artifact it was distilled from"}.get(
3502
+ g["source"], "-- travels alone: its source is neither a snapshot nor a "
3503
+ "corpus artifact")
3504
+ code = " -- the code it describes stays here" if g["kind"] == "code" else ""
3505
+ print(" guide %s: carried %s%s" % (g["name"], how, code))
3506
+ for name, why in not_carried:
3507
+ print(" guide %s: not carried -- %s" % (name, why))
3508
+ if carried or not_carried:
3509
+ print(" guides: %d (bundle version %d)%s"
3510
+ % (len(carried), KB_BUNDLE_GUIDES if carried else 1,
3511
+ "; the receiver's agent sets them aside and asks before any is in force"
3512
+ if carried else ""))
3143
3513
  if dropped:
3144
3514
  print(" not-yet-honored markers dropped: they describe this "
3145
3515
  "project's code")
@@ -3150,6 +3520,24 @@ def kb_cmd_export(args):
3150
3520
  # alternative -- dropping the partner rows -- ships a broken tree.
3151
3521
  print(" +%d topic(s) added to keep conflict sets whole: %s"
3152
3522
  % (len(added), ", ".join(sorted(added))))
3523
+ # F-102: every shipped file an importer of this version refuses, named
3524
+ # where it can be fixed, before it travels. Spelled as the import sees it.
3525
+ def _as_imported(rel):
3526
+ return posixpath.normpath(rel.replace("\\", "/"))
3527
+ cited = set(_as_imported(rel) for _slug, (_p, _t, rows) in selected.items()
3528
+ for r in rows if not _kb_is_declared(r)
3529
+ for rel in kb_claim_sources(r))
3530
+ refused = sorted(a for a in set(map(_as_imported, artifacts))
3531
+ if not kb_knowledge_path(a))
3532
+ for rel in refused:
3533
+ if rel in cited:
3534
+ print("[note] %s is cited but is not a topic or corpus file: an importer "
3535
+ "of this version refuses the whole bundle -- bring it into "
3536
+ "corpus/given/ and re-cite it (distillation.md §1)" % rel)
3537
+ elif not (rel.endswith(".meta.md") and rel[:-len(".meta.md")] in refused):
3538
+ print("[note] %s travels with a cited file but is not a topic or corpus "
3539
+ "file: an importer of this version refuses the whole bundle -- "
3540
+ "move or remove it" % rel)
3153
3541
  return 0
3154
3542
 
3155
3543
 
@@ -3167,6 +3555,9 @@ def kb_cmd_import(args):
3167
3555
  print("[ERROR] nothing was written: an import that half-applies leaves a "
3168
3556
  "tree whose checks fail and whose owner cannot tell what landed.")
3169
3557
  return 1
3558
+ if report.get("clutter"):
3559
+ print("[note] %d operating-system file(s) skipped, never written: %s"
3560
+ % (len(report["clutter"]), ", ".join(report["clutter"])))
3170
3561
  if args.dry_run:
3171
3562
  print("[ok] dry run: %d file(s) would be written" % len(writes))
3172
3563
  else:
@@ -3174,6 +3565,11 @@ def kb_cmd_import(args):
3174
3565
  dst.parent.mkdir(parents=True, exist_ok=True)
3175
3566
  dst.write_bytes(data)
3176
3567
  print("[ok] imported %d file(s) into %s" % (len(writes), docs))
3568
+ if report.get("guides"):
3569
+ print(" guides: %d set aside in %s/, not in force: ask the person about "
3570
+ "each (%s)" % (len(report["guides"]), KB_SET_ASIDE, ", ".join(report["guides"])))
3571
+ for name, why in report.get("guides_skipped", []):
3572
+ print("[note] guide %s skipped: %s -- nothing overwritten" % (name, why))
3177
3573
  if report.get("converted"):
3178
3574
  # portability.md §0 point 4: the agent must be able to tell the user
3179
3575
  print(" %d ruling(s) arrive as IMPORTED: each rests on a renamed copy of "
@@ -3418,8 +3814,14 @@ shared project memory -- also available:
3418
3814
  docs, expired windows, superseded chains
3419
3815
  claim-id <path> <locator> compute a claim id (--fill to fill a whole table)
3420
3816
  anchor <path> <phrase> resolve a phrase to a verified locator span
3421
- export --out <dir> bundle a subgraph WITH the bytes its claims cite
3422
- import <dir> merge a bundle in additively (never overwrites)
3817
+ export --out <dir> bundle a subgraph WITH the bytes its claims cite,
3818
+ and every guide not marked personal (--no-guides:
3819
+ knowledge only, for receivers not yet updated)
3820
+ import <dir> merge a bundle in additively (never overwrites);
3821
+ its guides land set aside, not in force
3822
+ imported promote|discard|undiscard <GUIDE_x.md>
3823
+ on the person's answer: put a set-aside guide in
3824
+ force, drop it, or forget that it was dropped
3423
3825
  adopt dry run: document guides resting on .sources/
3424
3826
  snapshots, and what moving them into corpus/given/
3425
3827
  involves (writes nothing; portability.md par.6)
@@ -3487,6 +3889,7 @@ def main(argv=None):
3487
3889
  p = sub.add_parser("export")
3488
3890
  p.add_argument("--out", required=True)
3489
3891
  p.add_argument("--topics")
3892
+ p.add_argument("--no-guides", dest="no_guides", action="store_true")
3490
3893
  p.add_argument("--root")
3491
3894
  p.add_argument("--docs-dir")
3492
3895
  p = sub.add_parser("import")
@@ -3501,6 +3904,11 @@ def main(argv=None):
3501
3904
  p.add_argument("path")
3502
3905
  p.add_argument("--root")
3503
3906
  p.add_argument("--docs-dir")
3907
+ p = sub.add_parser("imported")
3908
+ p.add_argument("action", choices=("promote", "discard", "undiscard"))
3909
+ p.add_argument("name")
3910
+ p.add_argument("--root")
3911
+ p.add_argument("--docs-dir")
3504
3912
  args = ap.parse_args(argv)
3505
3913
  if args.cmd == "claim-id":
3506
3914
  return kb_cmd_claim_id(args)
@@ -3530,6 +3938,8 @@ def main(argv=None):
3530
3938
  return kb_cmd_adopt(root, docs)
3531
3939
  if args.cmd == "inventory":
3532
3940
  return kb_cmd_inventory(root, docs, args.path)
3941
+ if args.cmd == "imported":
3942
+ return kb_cmd_imported(root, docs, args.action, args.name)
3533
3943
  if args.cmd == "validate":
3534
3944
  return kb_cmd_validate(root, docs, strict=args.strict, hybrid=args.hybrid)
3535
3945
  return kb_cmd_check(root, docs, strict=args.strict, hybrid=args.hybrid)