@mokuyoaxis/agent-guard 0.2.3 → 0.2.4

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 (69) hide show
  1. package/README.md +65 -62
  2. package/README.zh-CN.md +58 -58
  3. package/adapters/INTEGRATION.md +4 -4
  4. package/adapters/claude/README.md +3 -3
  5. package/adapters/claude/harness/README.md +1 -1
  6. package/adapters/codex/harness/README.md +2 -2
  7. package/adapters/dsh/README.md +10 -6
  8. package/adapters/dsh/harness/README.md +8 -8
  9. package/adapters/dsh/harness/guard_lab.py +3 -3
  10. package/adapters/dsh/lib/index.js +1 -1
  11. package/adapters/kimi-code/README.md +7 -7
  12. package/adapters/kimi-code/harness/README.md +3 -3
  13. package/adapters/kimi-code/harness/guard_lab.py +1 -1
  14. package/core/__init__.py +1 -1
  15. package/core/classifier.py +41 -16
  16. package/core/policy.py +11 -4
  17. package/core/recovery.py +256 -23
  18. package/core/trash_index.py +193 -0
  19. package/docs/README.md +104 -0
  20. package/docs/{architecture.md → design/architecture.md} +31 -6
  21. package/docs/{compatibility.md → design/compatibility.md} +54 -4
  22. package/docs/{threat-model.md → design/threat-model.md} +4 -4
  23. package/docs/{harness-capabilities.md → guides/harness-capabilities.md} +9 -9
  24. package/docs/guides/trash-index.md +106 -0
  25. package/docs/{development-note-unguarded-deletion.md → history/development-note-unguarded-deletion.md} +2 -2
  26. package/docs/{friction.md → history/friction.md} +39 -0
  27. package/docs/{secret-guard-analysis.md → history/secret-guard-analysis.md} +12 -12
  28. package/docs/{secret-guard-architecture.md → history/secret-guard-architecture.md} +2 -2
  29. package/docs/{secret-guard-design.md → history/secret-guard-design.md} +14 -14
  30. package/docs/lab/cases/injection-case-fake-ai-api.md +346 -0
  31. package/docs/{guard-lab.md → lab/guard-lab.md} +12 -12
  32. package/docs/{release-notes-0.2.0-rc1.md → releases/release-notes-0.2.0-rc1.md} +3 -3
  33. package/docs/{release-notes-0.2.0.md → releases/release-notes-0.2.0.md} +5 -5
  34. package/docs/{release-notes-0.2.1.md → releases/release-notes-0.2.1.md} +6 -6
  35. package/docs/{release-notes-0.2.2.md → releases/release-notes-0.2.2.md} +2 -2
  36. package/docs/{release-notes-0.2.3-rc1.md → releases/release-notes-0.2.3-rc1.md} +1 -1
  37. package/docs/{release-notes-0.2.3-rc2.md → releases/release-notes-0.2.3-rc2.md} +9 -9
  38. package/docs/{release-notes-0.2.3.md → releases/release-notes-0.2.3.md} +3 -3
  39. package/docs/releases/release-notes-0.2.4.md +89 -0
  40. package/docs/{test-report-claude-code-harness.md → reports/test-report-claude-code-harness.md} +5 -5
  41. package/docs/reports/test-report-dsh-0.2.4-ptc.md +79 -0
  42. package/docs/{test-report-dsh-guard-lab.md → reports/test-report-dsh-guard-lab.md} +1 -1
  43. package/docs/{test-report-dsh-native-session.md → reports/test-report-dsh-native-session.md} +1 -1
  44. package/docs/{test-report-dsh-paired-lab.md → reports/test-report-dsh-paired-lab.md} +1 -1
  45. package/docs/{test-report-dsh-real-followup.md → reports/test-report-dsh-real-followup.md} +1 -1
  46. package/docs/{test-report-dsh-retry-evidence.md → reports/test-report-dsh-retry-evidence.md} +1 -1
  47. package/docs/{test-report-dsh-v0.1.1.md → reports/test-report-dsh-v0.1.1.md} +4 -4
  48. package/docs/{test-report-kimi-code-block.md → reports/test-report-kimi-code-block.md} +3 -3
  49. package/docs/{test-report-kimi-guard-lab.md → reports/test-report-kimi-guard-lab.md} +3 -3
  50. package/docs/{test-report-release-readiness-0.2.3.md → reports/test-report-release-readiness-0.2.3.md} +1 -1
  51. package/docs/{test-report-workbuddy-windows-core.md → reports/test-report-workbuddy-windows-core.md} +1 -1
  52. package/docs/{test-report-zcode-glm-flash.md → reports/test-report-zcode-glm-flash.md} +2 -2
  53. package/package.json +1 -1
  54. package/skills/delete-guard/SKILL.md +38 -0
  55. package/skills/delete-guard/references/policy.md +18 -5
  56. package/skills/delete-guard/scripts/check.py +19 -0
  57. package/skills/delete-guard/scripts/restore.py +18 -6
  58. package/skills/delete-guard/scripts/status.py +52 -0
  59. package/skills/exfil-guard/references/channels.md +1 -1
  60. /package/docs/{host-drift.md → guides/host-drift.md} +0 -0
  61. /package/docs/{publishing-from-ephemeral-environments.md → guides/publishing-from-ephemeral-environments.md} +0 -0
  62. /package/docs/{guard-lab-clean-task.md → lab/tasks/guard-lab-clean-task.md} +0 -0
  63. /package/docs/{guard-lab-read-trial-task.md → lab/tasks/guard-lab-read-trial-task.md} +0 -0
  64. /package/docs/{guard-lab-trial-task.md → lab/tasks/guard-lab-trial-task.md} +0 -0
  65. /package/docs/{test-report-codex-gpt-5.6-sol.md → reports/test-report-codex-gpt-5.6-sol.md} +0 -0
  66. /package/docs/{test-report-codex-gpt-6-astra-high.md → reports/test-report-codex-gpt-6-astra-high.md} +0 -0
  67. /package/docs/{test-report-dsh-0.1.5-rc.1.md → reports/test-report-dsh-0.1.5-rc.1.md} +0 -0
  68. /package/docs/{test-report-dsh-0.2-upgrade.md → reports/test-report-dsh-0.2-upgrade.md} +0 -0
  69. /package/docs/{test-report-dsh-read-redaction.md → reports/test-report-dsh-read-redaction.md} +0 -0
package/core/recovery.py CHANGED
@@ -6,7 +6,8 @@ Two compensation strategies, chosen by the caller (policy decides which):
6
6
  workspace-relative structure under one transaction id
7
7
  snapshot_git - capture tracked modifications as a stash commit WITHOUT
8
8
  changing the working tree (git stash create + store), so a
9
- subsequent reset --hard / restore stays reversible
9
+ subsequent tracked-file changes stay reversible; hard
10
+ reset also requires the untracked-collision preflight
10
11
 
11
12
  Everything lands in an append-only manifest (JSONL). Restore is itself
12
13
  non-destructive: it refuses to overwrite anything that now exists at the
@@ -29,7 +30,7 @@ from typing import Any, Dict, List, Optional, Tuple
29
30
 
30
31
  from . import MANIFEST_NAME, TRASH_DIRNAME
31
32
  from .audit import new_txid, utc_now_iso
32
- from .classifier import PathSpec, _physical, _physical_keep_final
33
+ from .classifier import PathSpec, _physical, _physical_keep_final, inside_path
33
34
 
34
35
  # Soft retention policy (docs/references: GC). Thresholds only MARK entries
35
36
  # GC_ELIGIBLE; actual purging is an explicit maintenance action - a system
@@ -44,7 +45,8 @@ _STORAGE_ERRNOS = {
44
45
 
45
46
  # A transaction directory is one direct child of the quarantine, never a
46
47
  # caller-supplied path. Accept simple historical identifiers too, but no
47
- # separators or dots that could turn an ID into a path traversal.
48
+ # separators or dots that could turn an ID into a path traversal. Restore
49
+ # uses the same identifier constraint as GC.
48
50
  _GC_TXID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*\Z")
49
51
 
50
52
 
@@ -302,6 +304,91 @@ class RecoveryEngine:
302
304
 
303
305
  # ------------------------------------------------------ git snapshot
304
306
 
307
+ def preflight_git_reset_hard(
308
+ self, cwd: Optional[str] = None, target: str = "HEAD",
309
+ ) -> Tuple[List[str], str]:
310
+ """Read-only check for content a tracked-only stash cannot protect.
311
+
312
+ Compare the target tree with Git's untracked paths (including ignored
313
+ paths and nested repositories). A collision includes either side
314
+ being an ancestor of the other: Git can replace a directory with a
315
+ file, or remove a file/symlink to create a directory. Refuse such a
316
+ reset; do not move originals or claim their bytes are in the stash.
317
+ Errors are static so callers can report them without leaking paths.
318
+ """
319
+ cwd = cwd or self.workspace
320
+ git_cwd = cwd
321
+ if re.match(r"(?:refs/)?stash(?:$|[~^@])", target):
322
+ return [], "Stash-relative targets change when a snapshot is stored"
323
+
324
+ def git(*args: str, optional: bool = False) -> bytes:
325
+ proc = subprocess.run(["git", "-C", git_cwd, *args],
326
+ capture_output=True, timeout=30)
327
+ if proc.stderr or (proc.returncode != 0 and not
328
+ (optional and proc.returncode == 1)):
329
+ raise ValueError("Git preflight command failed")
330
+ return proc.stdout
331
+
332
+ def paths(data: bytes) -> List[str]:
333
+ if data and not data.endswith(b"\0"):
334
+ raise ValueError("incomplete Git path enumeration")
335
+ return [os.fsdecode(p) for p in data.split(b"\0") if p]
336
+
337
+ def parents(path: str) -> List[str]:
338
+ parts = path.split("/")
339
+ return ["/".join(parts[:i]) for i in range(1, len(parts))]
340
+
341
+ try:
342
+ # Whole-tree reset cannot be confined to a narrower workspace.
343
+ root = os.fsdecode(git("rev-parse", "--show-toplevel")).rstrip("\n")
344
+ if _physical(root) != _physical(self.workspace):
345
+ return [], "Git repository does not match the workspace"
346
+ # ls-files is scoped by its working directory. Reset is always
347
+ # whole-tree, even when invoked from a repository subdirectory.
348
+ git_cwd = root
349
+ sha = git("rev-parse", "--verify", "--end-of-options",
350
+ target + "^{commit}").strip().decode("ascii")
351
+ tree = paths(git("ls-tree", "-r", "-z", "--full-tree", sha))
352
+ index = paths(git("ls-files", "--stage", "-z"))
353
+ # Submodule working trees are not captured by stash create.
354
+ if any(row.startswith("160000 ") for row in tree + index):
355
+ return [], "Submodule reset effects cannot be protected"
356
+ ignorecase = git("config", "--type=bool", "--get", "core.ignorecase",
357
+ optional=True).strip() == b"true"
358
+
359
+ def key(path: str) -> str:
360
+ return path.casefold() if ignorecase else path
361
+
362
+ leaves = {key(row.split("\t", 1)[1]) for row in tree}
363
+ directories = {p for leaf in leaves for p in parents(leaf)}
364
+ # Intentionally omit --exclude-standard: ignored data is at risk
365
+ # too. -z preserves newlines, quoting, and non-ASCII path bytes.
366
+ others = paths(git("ls-files", "--others", "-z"))
367
+
368
+ def collides(path: str) -> bool:
369
+ path = key(path.rstrip("/"))
370
+ return (path in leaves or path in directories or
371
+ any(p in leaves for p in parents(path)))
372
+
373
+ collisions = [p for p in others if collides(p)]
374
+ # Include future audit/snapshot files even before layout exists.
375
+ # Preserve both storage and its configured spelling: replacing
376
+ # a tracked symlink to external trash would sever recovery access.
377
+ for trash_path in {self.trash_root, _physical(self.trash_root)}:
378
+ for workspace_path in {self.workspace, _physical(self.workspace)}:
379
+ trash = os.path.relpath(trash_path, workspace_path)
380
+ if trash == ".":
381
+ return [], "Quarantine overlaps the workspace root"
382
+ if trash == os.pardir or trash.startswith(os.pardir + os.sep):
383
+ continue
384
+ trash = trash.replace(os.sep, "/")
385
+ if collides(trash) or any(p.startswith(key(trash) + "/")
386
+ for p in leaves):
387
+ collisions.append(trash)
388
+ return sorted(set(collisions)), ""
389
+ except (OSError, subprocess.TimeoutExpired, ValueError, IndexError):
390
+ return [], "Git hard reset preflight could not determine effects"
391
+
305
392
  def snapshot_git(self, cwd: Optional[str] = None,
306
393
  txid: Optional[str] = None,
307
394
  meta: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
@@ -491,24 +578,129 @@ class RecoveryEngine:
491
578
  slot["state"] = "EMPTY"
492
579
  return out
493
580
 
581
+ def _validate_restore_target(self, origin: str) -> None:
582
+ """Check the parent chain, retaining the final symlink's location.
583
+
584
+ Recorded paths are absolute and normalized. Resolve both sides for
585
+ comparison so workspace aliases remain valid, but refuse a parent
586
+ that now points outside. This preflight is not an atomic filesystem
587
+ boundary against concurrent changes.
588
+ """
589
+ if (not isinstance(origin, str) or not origin or "\0" in origin or
590
+ not os.path.isabs(origin) or os.path.normpath(origin) != origin):
591
+ raise ValueError("invalid restore target path")
592
+ root = os.path.normcase(_physical(self.workspace))
593
+ target = os.path.normcase(_physical_keep_final(origin))
594
+ if target == root or not inside_path(target, root):
595
+ raise ValueError("restore target is outside workspace")
596
+
597
+ def _restore_transaction_dir(self, txid: str) -> str:
598
+ """Bind an ID to its own direct child of the selected quarantine."""
599
+ if not isinstance(txid, str) or not _GC_TXID_RE.fullmatch(txid):
600
+ raise ValueError("invalid quarantine transaction id")
601
+ tx_dir = os.path.join(self.trash_root, txid)
602
+ expected = os.path.join(_physical(self.trash_root), txid)
603
+ if (os.path.islink(tx_dir) or
604
+ os.path.normcase(_physical(tx_dir)) != os.path.normcase(expected)):
605
+ raise ValueError("uncontained quarantine transaction directory")
606
+ return tx_dir
607
+
608
+ def _validate_restore_source(self, trash: str, txid: str) -> None:
609
+ """Check the source parent chain without following a leaf link."""
610
+ tx_dir = self._restore_transaction_dir(txid)
611
+ if (not isinstance(trash, str) or not trash or "\0" in trash or
612
+ not os.path.isabs(trash) or os.path.normpath(trash) != trash):
613
+ raise ValueError("invalid restore source path")
614
+ root = os.path.normcase(_physical(tx_dir))
615
+ source = os.path.normcase(_physical_keep_final(trash))
616
+ if source == root or not inside_path(source, root):
617
+ raise ValueError("restore source is outside its transaction")
618
+
619
+ def _validate_restore_preservation(self, origin: str) -> None:
620
+ """Never relocate the quarantine or an alias used to reach it."""
621
+ current = _physical_keep_final(origin)
622
+ pairs = ((origin, self.trash_root),
623
+ (current, _physical_keep_final(self.trash_root)),
624
+ (current, _physical(self.trash_root)))
625
+ for target, storage in pairs:
626
+ target, storage = os.path.normcase(target), os.path.normcase(storage)
627
+ if inside_path(target, storage) or inside_path(storage, target):
628
+ raise ValueError("force restore target overlaps quarantine storage")
629
+
494
630
  def restore(self, txid: str, force: bool = False,
495
631
  cwd: Optional[str] = None) -> Dict[str, Any]:
496
632
  """Undo one transaction. Refuses to overwrite unless force is set.
497
633
 
498
634
  Relocate items move back to their origin paths; snapshot items apply
499
635
  the stored stash (apply, never drop - the evidence stays until a
500
- human prunes it).
636
+ human prunes it). Relocation targets must remain inside this
637
+ workspace and sources inside their own quarantine transaction;
638
+ force does not override either check. A forced overwrite first
639
+ preserves the current occupant in a separate relocation transaction.
640
+ backup_txids identifies preservation attempts, including failed ones.
501
641
  """
502
- tx = self.transactions().get(txid)
642
+ if not isinstance(txid, str) or not _GC_TXID_RE.fullmatch(txid):
643
+ return {"ok": False, "error": "invalid quarantine transaction id"}
644
+ transactions = self.transactions()
645
+ tx = transactions.get(txid)
503
646
  if not tx:
504
647
  return {"ok": False, "error": f"unknown transaction: {txid}"}
505
648
  restored: List[str] = []
506
649
  conflicts: List[str] = []
507
650
  errors: List[str] = []
508
- for item in tx["items"]:
651
+ backup_txids: List[str] = []
652
+ known_txids = set(transactions)
653
+ items = tx["items"]
654
+ try:
655
+ self._restore_transaction_dir(txid)
656
+ except (OSError, ValueError):
657
+ errors.append(
658
+ "restore source is outside its transaction or cannot be resolved")
659
+ items = []
660
+ try:
661
+ # Check every destination before restoring an earlier valid item
662
+ # or removing an existing occupant under force.
663
+ for item in items:
664
+ if item.get("type") == "relocate":
665
+ self._validate_restore_target(item.get("origin_path"))
666
+ except (OSError, ValueError):
667
+ errors.append(
668
+ "restore target is outside workspace or cannot be resolved")
669
+ items = []
670
+ try:
671
+ for item in items:
672
+ if item.get("type") == "relocate":
673
+ self._validate_restore_source(item.get("trash_path"), txid)
674
+ except (OSError, ValueError):
675
+ errors.append(
676
+ "restore source is outside its transaction or cannot be resolved")
677
+ items = []
678
+ try:
679
+ for item in items:
680
+ if (force and item.get("type") == "relocate" and
681
+ os.path.lexists(item["origin_path"])):
682
+ self._validate_restore_preservation(item["origin_path"])
683
+ except (OSError, ValueError):
684
+ errors.append(
685
+ "force restore target overlaps quarantine storage or cannot be resolved")
686
+ items = []
687
+ for item in items:
509
688
  if item.get("type") == "relocate":
510
689
  origin = item["origin_path"]
511
690
  trash = item["trash_path"]
691
+ try:
692
+ # An earlier restore can itself recreate a parent link.
693
+ self._validate_restore_target(origin)
694
+ except (OSError, ValueError):
695
+ errors.append(
696
+ "restore target is outside workspace or cannot be resolved")
697
+ continue
698
+ try:
699
+ self._validate_restore_source(trash, txid)
700
+ except (OSError, ValueError):
701
+ errors.append(
702
+ "restore source is outside its transaction or cannot be resolved")
703
+ continue
512
704
  if not os.path.lexists(trash):
513
705
  errors.append(f"quarantine copy vanished: {trash}")
514
706
  continue
@@ -516,14 +708,48 @@ class RecoveryEngine:
516
708
  if not force:
517
709
  conflicts.append(origin)
518
710
  continue
519
- if os.path.isdir(origin) and not os.path.islink(origin):
520
- shutil.rmtree(origin)
521
- else:
522
- os.unlink(origin)
523
- parent = os.path.dirname(origin)
524
- if parent:
525
- os.makedirs(parent, exist_ok=True)
711
+ try:
712
+ self._validate_restore_preservation(origin)
713
+ backup_txid = new_txid()
714
+ backup_dir = self._restore_transaction_dir(backup_txid)
715
+ if (backup_txid in known_txids or
716
+ os.path.lexists(backup_dir)):
717
+ raise ValueError("backup transaction already exists")
718
+ except (OSError, ValueError) as exc:
719
+ errors.append(f"cannot establish current-version backup: {exc}")
720
+ continue
721
+ known_txids.add(backup_txid)
722
+ backup_txids.append(backup_txid)
723
+ try:
724
+ saved = self.relocate(
725
+ [PathSpec(raw=origin, resolved=origin)],
726
+ txid=backup_txid,
727
+ meta={"tool": "restore", "restoring_txid": txid})
728
+ if saved.get("storage_failure") or len(saved["moved"]) != 1:
729
+ errors.append(
730
+ f"current-version preservation failed; "
731
+ f"inspect backup transaction {backup_txid}")
732
+ continue
733
+ except OSError as exc:
734
+ errors.append(
735
+ f"current-version preservation failed "
736
+ f"(backup transaction {backup_txid}): {exc}")
737
+ continue
738
+ try:
739
+ self._validate_restore_target(origin)
740
+ self._validate_restore_source(trash, txid)
741
+ except (OSError, ValueError):
742
+ errors.append("restore paths changed after preservation")
743
+ continue
744
+ # Do not silently overwrite a version created while the
745
+ # occupant was being preserved, even with force set.
746
+ if os.path.lexists(origin):
747
+ conflicts.append(origin)
748
+ continue
526
749
  try:
750
+ parent = os.path.dirname(origin)
751
+ if parent:
752
+ os.makedirs(parent, exist_ok=True)
527
753
  self._move(trash, origin)
528
754
  restored.append(origin)
529
755
  except OSError as exc:
@@ -541,19 +767,26 @@ class RecoveryEngine:
541
767
  errors.append(
542
768
  f"stash apply {sha}: {(apply.stderr or '').strip()}")
543
769
 
544
- self._manifest_append([{
545
- "type": "restore", "txid": txid, "force": force,
546
- "restored": restored, "conflicts": conflicts, "errors": errors,
547
- }])
548
- # drop empty quarantine directories for tidy listings
549
- txdir = os.path.join(self.trash_root, txid)
550
770
  try:
551
- if os.path.isdir(txdir) and not os.listdir(txdir):
552
- os.rmdir(txdir)
771
+ self._manifest_append([{
772
+ "type": "restore", "txid": txid, "force": force,
773
+ "restored": restored, "conflicts": conflicts, "errors": errors,
774
+ }])
553
775
  except OSError:
776
+ errors.append("restore journal could not be stored; inspect filesystem state")
777
+ # drop empty quarantine directories for tidy listings
778
+ try:
779
+ if not errors:
780
+ txdir = self._restore_transaction_dir(txid)
781
+ if os.path.isdir(txdir) and not os.listdir(txdir):
782
+ os.rmdir(txdir)
783
+ except (OSError, ValueError):
554
784
  pass
555
- return {"ok": not errors and not conflicts,
556
- "restored": restored, "conflicts": conflicts, "errors": errors}
785
+ report = {"ok": not errors and not conflicts,
786
+ "restored": restored, "conflicts": conflicts, "errors": errors}
787
+ if backup_txids:
788
+ report["backup_txids"] = backup_txids
789
+ return report
557
790
 
558
791
  # ------------------------------------------------------------- status
559
792
 
@@ -0,0 +1,193 @@
1
+ """Read-only quarantine locations for CLI, agent and future UI callers.
2
+
3
+ This queries directory layout, not recovery contents or purge authority. No
4
+ RecoveryEngine is constructed, no Git command runs, and no layout is created.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import errno
9
+ import os
10
+ import stat
11
+ from typing import Any, Dict, Iterable, List
12
+
13
+ from . import AUDIT_NAME, MANIFEST_NAME, STATE_NAME, TRASH_DIRNAME
14
+
15
+
16
+ SCHEMA_VERSION = 1
17
+ DEFAULT_MAX_DEPTH = 3
18
+ DEFAULT_MAX_ENTRIES = 10_000
19
+ EXCLUDED_DIRS = (".git", "node_modules", ".internal", "__pycache__")
20
+
21
+
22
+ def _paths(values: Iterable[str]) -> List[str]:
23
+ if isinstance(values, (str, bytes)):
24
+ raise ValueError("paths must be a sequence of text paths")
25
+ try:
26
+ values = iter(values)
27
+ except TypeError:
28
+ raise ValueError("paths must be a sequence of text paths") from None
29
+ result = []
30
+ for value in values:
31
+ try:
32
+ value = os.fspath(value)
33
+ except TypeError:
34
+ raise ValueError("paths must contain text paths") from None
35
+ if not isinstance(value, str) or not value or "\0" in value:
36
+ raise ValueError("paths must contain nonempty text paths")
37
+ normalized = os.path.normpath(os.path.abspath(os.path.expanduser(value)))
38
+ if normalized not in result:
39
+ result.append(normalized)
40
+ return result
41
+
42
+
43
+ def _error_code(exc: OSError) -> str:
44
+ if exc.errno in (errno.EACCES, errno.EPERM):
45
+ return "PERMISSION_DENIED"
46
+ if exc.errno == errno.ENOENT:
47
+ return "NOT_FOUND"
48
+ if exc.errno == errno.ENOTDIR:
49
+ return "NOT_DIRECTORY"
50
+ return "IO_ERROR"
51
+
52
+
53
+ def list_trash_locations(
54
+ roots: Iterable[str] = (), *, trash_paths: Iterable[str] = (),
55
+ max_depth: int = DEFAULT_MAX_DEPTH,
56
+ max_entries: int = DEFAULT_MAX_ENTRIES,
57
+ ) -> Dict[str, Any]:
58
+ """Return schema v1 location candidates within explicit bounded roots.
59
+
60
+ Depth counts directories below a root: depth 0 still checks that root's
61
+ .agent-trash. A recognized bucket is never traversed. Ordinary child
62
+ directory links are skipped; explicitly supplied roots/buckets may use
63
+ aliases. Expected marker names are lstat'ed, never opened.
64
+
65
+ count includes unconfirmed/unreadable candidates; identified_count only
66
+ counts existing metadata layouts. Neither identifies ownership, content
67
+ integrity or permission to restore/purge. complete covers the declared
68
+ depth/exclusions and successful reads, not the whole host or an atomic
69
+ filesystem snapshot. Errors retain partial results.
70
+ """
71
+ if type(max_depth) is not int or max_depth < 0:
72
+ raise ValueError("max_depth must be a nonnegative integer")
73
+ if type(max_entries) is not int or max_entries < 1:
74
+ raise ValueError("max_entries must be a positive integer")
75
+ roots, trash_paths = _paths(roots), _paths(trash_paths)
76
+ if not roots and not trash_paths:
77
+ raise ValueError("provide roots or trash_paths")
78
+
79
+ buckets: Dict[str, Dict[str, Any]] = {}
80
+ errors: List[Dict[str, str]] = []
81
+ visited: Dict[str, int] = {}
82
+ examined = 0
83
+ exhausted = False
84
+
85
+ def error(path: str, code: str) -> None:
86
+ record = {"path": path, "code": code}
87
+ if record not in errors:
88
+ errors.append(record)
89
+
90
+ def charge(path: str) -> bool:
91
+ nonlocal examined, exhausted
92
+ if examined >= max_entries:
93
+ if not exhausted:
94
+ error(path, "ENTRY_LIMIT_REACHED")
95
+ exhausted = True
96
+ return False
97
+ examined += 1
98
+ return True
99
+
100
+ def bucket(path: str, source: str) -> None:
101
+ try:
102
+ if not stat.S_ISDIR(os.stat(path).st_mode):
103
+ error(path, "NOT_DIRECTORY")
104
+ return
105
+ resolved = os.path.normpath(os.path.realpath(path))
106
+ except OSError as exc:
107
+ error(path, _error_code(exc))
108
+ return
109
+ key = os.path.normcase(resolved)
110
+ if key in buckets:
111
+ row = buckets[key]
112
+ if path not in row["locations"]:
113
+ row["locations"].append(path)
114
+ if source not in row["sources"]:
115
+ row["sources"].append(source)
116
+ return
117
+
118
+ present = unreadable = False
119
+ for name in (MANIFEST_NAME, AUDIT_NAME, STATE_NAME, "sessions"):
120
+ try:
121
+ mode = os.lstat(os.path.join(path, name)).st_mode
122
+ present |= (stat.S_ISDIR(mode) if name == "sessions"
123
+ else stat.S_ISREG(mode))
124
+ except FileNotFoundError:
125
+ continue
126
+ except OSError as exc:
127
+ unreadable = True
128
+ error(path, _error_code(exc))
129
+ status = ("unreadable" if unreadable else
130
+ "metadata_present" if present else "unconfirmed")
131
+ buckets[key] = {
132
+ "trash_root": path, "resolved_trash_root": resolved,
133
+ "directory": os.path.dirname(path), "locations": [path],
134
+ "sources": [source], "status": status,
135
+ }
136
+
137
+ for path in trash_paths:
138
+ if not charge(path):
139
+ break
140
+ bucket(path, "declared")
141
+
142
+ for root in roots:
143
+ if exhausted:
144
+ break
145
+ stack = [(root, 0)]
146
+ while stack and not exhausted:
147
+ directory, depth = stack.pop()
148
+ if not charge(directory):
149
+ break
150
+ if os.path.basename(directory) == TRASH_DIRNAME:
151
+ bucket(directory, "discovered")
152
+ continue
153
+ try:
154
+ physical = os.path.normcase(os.path.realpath(directory))
155
+ except OSError as exc:
156
+ error(directory, _error_code(exc))
157
+ continue
158
+ remaining = max_depth - depth
159
+ if visited.get(physical, -1) >= remaining:
160
+ continue
161
+ visited[physical] = remaining
162
+ children = []
163
+ try:
164
+ with os.scandir(directory) as entries:
165
+ for entry in entries:
166
+ if not charge(entry.path):
167
+ break
168
+ if entry.name == TRASH_DIRNAME:
169
+ bucket(entry.path, "discovered")
170
+ elif (depth < max_depth and entry.name not in EXCLUDED_DIRS
171
+ and entry.is_dir(follow_symlinks=False)):
172
+ children.append(entry.path)
173
+ except OSError as exc:
174
+ error(directory, _error_code(exc))
175
+ # Reverse push gives stable lexical order among directory children.
176
+ stack.extend((path, depth + 1) for path in sorted(children, reverse=True))
177
+
178
+ rows = sorted(buckets.values(), key=lambda row: row["resolved_trash_root"])
179
+ for row in rows:
180
+ row["locations"].sort()
181
+ row["sources"].sort()
182
+ row["trash_root"] = row["locations"][0]
183
+ row["directory"] = os.path.dirname(row["trash_root"])
184
+ return {
185
+ "schema_version": SCHEMA_VERSION,
186
+ "roots": roots, "trash_paths": trash_paths,
187
+ "max_depth": max_depth, "max_entries": max_entries,
188
+ "excluded_dirs": list(EXCLUDED_DIRS), "examined": examined,
189
+ "complete": not errors,
190
+ "count": len(rows),
191
+ "identified_count": sum(row["status"] == "metadata_present" for row in rows),
192
+ "entries": rows, "errors": errors,
193
+ }
package/docs/README.md ADDED
@@ -0,0 +1,104 @@
1
+ # Documentation / 文档导航
2
+
3
+ Start with the [harness capability matrix](guides/harness-capabilities.md) for
4
+ current coverage, the [architecture](design/architecture.md) for the shared
5
+ Core, and the [Lab guide](lab/guard-lab.md) for experiment semantics.
6
+
7
+ 先看当前能力矩阵、架构和 Lab 指南。测试报告按所测版本与配置保留;发布记录、
8
+ 历史设计和外部案例各自归档,不能据此扩展当前产品的承诺。
9
+
10
+ | Category / 分类 | Contents / 内容 |
11
+ |---|---|
12
+ | [Guides](#guides) / 使用指南 | 宿主接入证据、漂移检查、维护者发布指南 |
13
+ | [Design](#design) / 架构与契约 | 当前架构、威胁模型与兼容契约 |
14
+ | [Lab](#lab) / 实验与候选素材 | Lab 流程、任务模板、外部攻击案例 |
15
+ | [Reports](#reports) / 测试报告 | 按宿主、版本和观察范围记录的证据 |
16
+ | [Releases](#releases) / 发布记录 | 正式版与预览版各自的范围 |
17
+ | [History](#history) / 历史设计与经验 | 早期设计、实现教训和事故探索 |
18
+
19
+ ## Guides
20
+
21
+ | Document / 文档 | Scope / 范围 |
22
+ |---|---|
23
+ | [Harness capabilities](guides/harness-capabilities.md) | 当前接入范围、证据等级与未验证路径 |
24
+ | [Host drift](guides/host-drift.md) | 宿主版本、配置与本地基线检查 |
25
+ | [Trash locations](guides/trash-index.md) | 0.2.4 的只读位置查询、Agent/前端共享 JSON 契约 |
26
+ | [Publishing from ephemeral environments](guides/publishing-from-ephemeral-environments.md) | 临时环境中的 GitHub 发布操作参考 |
27
+
28
+ Adapter setup remains in [adapters/](../adapters/INTEGRATION.md). Skill contracts
29
+ remain in [skills/](../skills/delete-guard/SKILL.md).
30
+
31
+ ## Design
32
+
33
+ | Document / 文档 | Scope / 范围 |
34
+ |---|---|
35
+ | [Architecture](design/architecture.md) | Core、Decision Protocol、适配器与数据流 |
36
+ | [Threat model](design/threat-model.md) | 资产、可信假设与已知防护边界 |
37
+ | [Compatibility](design/compatibility.md) | 适配器契约、接口兼容与版本约定 |
38
+
39
+ ## Lab
40
+
41
+ | Document / 文档 | Scope / 范围 |
42
+ |---|---|
43
+ | [Guard Lab guide](lab/guard-lab.md) | 操作流程、信道、L0/L1/L2 语义与限制 |
44
+ | [Clean task](lab/tasks/guard-lab-clean-task.md) | 干净对照任务模板 |
45
+ | [Injection trial task](lab/tasks/guard-lab-trial-task.md) | 提示注入试次任务模板 |
46
+ | [Native-read trial task](lab/tasks/guard-lab-read-trial-task.md) | 原生读取脱敏任务模板 |
47
+ | [fake-ai-api reference](lab/cases/injection-case-fake-ai-api.md) | 外部攻击端候选素材;尚未作为 Lab 样本验证 |
48
+
49
+ Task templates and external case references are separate from completed test
50
+ reports. A scripted provider checks host behavior; a real-model injection
51
+ trial needs an effective unguarded baseline before a matched comparison.
52
+
53
+ ## Reports
54
+
55
+ Each report preserves its original version, configuration, result and limits.
56
+ Use the [capability matrix](guides/harness-capabilities.md) to interpret current
57
+ coverage rather than treating every historical result as current acceptance.
58
+
59
+ | Document / 文档 | Scope / 范围 |
60
+ |---|---|
61
+ | [0.2.3 contract review](reports/test-report-release-readiness-0.2.3.md) | 发布前契约复核与 DSH 原生验收 |
62
+ | [0.2.4 official Flash / PTC](reports/test-report-dsh-0.2.4-ptc.md) | 实模主/子代理碰撞拒绝;原始主 PTC 任务失败与独立收尾分别记录 |
63
+ | [Claude Code harness](reports/test-report-claude-code-harness.md) | 脚本模型驱动的真实宿主 hook 验证 |
64
+ | [Kimi Code blocking](reports/test-report-kimi-code-block.md) | 所测版本的 Bash BLOCK 与故障路径 |
65
+ | [Kimi Code Lab](reports/test-report-kimi-guard-lab.md) | 历史配对试次与后续本地复核 |
66
+ | [Codex / GPT-6 Astra](reports/test-report-codex-gpt-6-astra-high.md) | Skill/CLI 验收,不声明原生拦截 |
67
+ | [Codex / GPT-5.6 Sol](reports/test-report-codex-gpt-5.6-sol.md) | v0.1.1 历史 Skill/CLI 评估 |
68
+ | [DSH 0.1.5-rc.1](reports/test-report-dsh-0.1.5-rc.1.md) | 打包插件与执行级 Bash 验收 |
69
+ | [DSH 0.2 upgrade](reports/test-report-dsh-0.2-upgrade.md) | 升级初期兼容快照,后续状态见契约复核 |
70
+ | [DSH Lab baseline](reports/test-report-dsh-guard-lab.md) | 真实模型基线;未形成 L2 结论 |
71
+ | [DSH native sessions](reports/test-report-dsh-native-session.md) | 原生工具结果捕获与保留日志复核 |
72
+ | [DSH paired Lab](reports/test-report-dsh-paired-lab.md) | 配对工作流与结果改写契约调查 |
73
+ | [DSH retry evidence](reports/test-report-dsh-retry-evidence.md) | 失败尝试、重试会话与证据解析 |
74
+ | [DSH read redaction](reports/test-report-dsh-read-redaction.md) | 零模型原生读取、下一请求与落盘检查 |
75
+ | [DSH real follow-up](reports/test-report-dsh-real-followup.md) | 真实读取开关对照;不等于注入 L2 |
76
+ | [DSH v0.1.1](reports/test-report-dsh-v0.1.1.md) | 历史真机测试 |
77
+ | [WorkBuddy / Windows Core](reports/test-report-workbuddy-windows-core.md) | 社区 Core/CLI 反馈与修复回归 |
78
+ | [ZCode / Windows](reports/test-report-zcode-glm-flash.md) | 历史 CLI/hook 试次及许可绕过观察 |
79
+
80
+ ## Releases
81
+
82
+ | Document / 文档 | Scope / 范围 |
83
+ |---|---|
84
+ | [0.2.4](releases/release-notes-0.2.4.md) | 恢复维护、trash 查询及兼容性例外 |
85
+ | [0.2.3](releases/release-notes-0.2.3.md) | 正式版范围与证据边界 |
86
+ | [0.2.3-rc2](releases/release-notes-0.2.3-rc2.md) | 离线 Lab 与已复核 DSH 契约 |
87
+ | [0.2.3-rc1](releases/release-notes-0.2.3-rc1.md) | Windows Core 与预发布范围 |
88
+ | [0.2.2](releases/release-notes-0.2.2.md) | 宿主漂移、实时哨兵与 DSH 打包验收 |
89
+ | [0.2.1](releases/release-notes-0.2.1.md) | adapter/doctor 变更 |
90
+ | [0.2.0](releases/release-notes-0.2.0.md) | exfil 与配置安全视图等发布范围 |
91
+ | [0.2.0-rc1](releases/release-notes-0.2.0-rc1.md) | 早期源码预览范围 |
92
+
93
+ ## History
94
+
95
+ These documents explain earlier proposals and implementation experience.
96
+ Current behavior is defined by the Core, Skills and current guides.
97
+
98
+ | Document / 文档 | Scope / 范围 |
99
+ |---|---|
100
+ | [Friction log](history/friction.md) | F1–F20 实现发现与修复经验 |
101
+ | [Unguarded deletion note](history/development-note-unguarded-deletion.md) | 去标识化事故探索与恢复方向 |
102
+ | [Secret Guard analysis](history/secret-guard-analysis.md) | 实现前的需求分析 |
103
+ | [Secret Guard design](history/secret-guard-design.md) | 早期设计候选与原范围 |
104
+ | [Secret Guard architecture](history/secret-guard-architecture.md) | 早期架构草图;不代表拦截点已交付 |