coldmemory 0.3.6__py3-none-any.whl

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.
coldmemory/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """ColdMemory: private memory bundles, checked against live disk, served over local MCP."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ from .citations import Citation, parse_citations
7
+
8
+ __version__ = "0.3.6"
9
+ __all__ = ["Citation", "parse_citations", "resolve_v2_spec_path"]
10
+
11
+
12
+ def resolve_v2_spec_path(env=None) -> Path | None:
13
+ settings = os.environ if env is None else env
14
+ path = settings.get("COLDMEMORY_V2_SPEC")
15
+ return Path(path) if path else None
coldmemory/__main__.py ADDED
@@ -0,0 +1,135 @@
1
+ """Build and manage ColdMemory bundles."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import re
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from . import cartridge_spec as spec
12
+ from . import init_cmd
13
+ from . import sessions as sessions_
14
+ from .ingest import parse_source
15
+ from .mcp_server import Server, parse_stack
16
+
17
+ def compile_(args):
18
+ policy = json.loads(args.policy.read_text(encoding="utf-8")) if args.policy else None
19
+ bundle = spec.compile_bundle(args.store, args.id, [parse_source(s) for s in args.source], args.scope,
20
+ sign_key=args.sign_key, policy=policy)
21
+ counts = bundle.manifest["counts"]
22
+ print(f"{args.id} {bundle.revision}: {counts['notes']} notes, {counts['train']} train rows, "
23
+ f"{counts['val']} validation rows")
24
+ for reason, count in sorted(bundle.manifest["skipped"].items()):
25
+ print(f"skipped {count}: {reason}")
26
+ if counts["outdated_approved_notes"]:
27
+ print(f"left out {counts['outdated_approved_notes']} approved notes because their sources changed")
28
+ return bundle
29
+
30
+
31
+ def ask(args):
32
+ print(Server(args.store, [args.scope], args.backend, args.url, trust_keys=args.trust_key,
33
+ local_unsigned=args.local_unsigned).memory_ask(args.query, args.id or "auto"))
34
+
35
+
36
+ def brief(args):
37
+ """Check a signed scope against COLD_ALLOWED_SCOPES (default public) before any store is opened.
38
+
39
+ A local unsigned store is the owner's own single scope, so it needs no allowlist."""
40
+ configured = os.environ.get("COLD_ALLOWED_SCOPES", "public")
41
+ try:
42
+ names = [spec.name for spec in parse_stack([args.scope])]
43
+ except ValueError:
44
+ names = [args.scope]
45
+ if not args.local_unsigned and any(name not in configured.split(",") or not re.fullmatch("[a-z0-9][a-z0-9-]*", name)
46
+ for name in names):
47
+ raise ValueError(f"scope denied: {args.scope!r} is not a valid scope listed in COLD_ALLOWED_SCOPES={configured!r}")
48
+ print(Server(args.store, [args.scope], trust_keys=args.trust_key,
49
+ local_unsigned=args.local_unsigned).memory_brief())
50
+
51
+
52
+ def status(args):
53
+ print(Server(args.store, [args.scope], trust_keys=args.trust_key, local_unsigned=args.local_unsigned).memory_status())
54
+
55
+
56
+ def activate(args):
57
+ print(f"live: {spec.activate(args.store, args.id, args.revision).revision}")
58
+
59
+
60
+ def queue(args):
61
+ for entry in spec.read_queue(args.store, args.id):
62
+ print(f"{entry['id']} {'approved' if entry['approved'] else 'waiting'}: {entry['title']}: {entry['decision']}")
63
+ print(" sources: " + ", ".join(s["key"] for s in entry["sources"]))
64
+
65
+
66
+ def approve(args):
67
+ print(f"approved: {spec.approve(args.store, args.id, args.entry)['title']}")
68
+
69
+
70
+ def sessions(args):
71
+ print(json.dumps(sessions_.ingest(args.root or None, args.out)))
72
+
73
+
74
+ def main(argv=None):
75
+ parser = argparse.ArgumentParser(prog="coldmemory", description=__doc__)
76
+ commands = parser.add_subparsers(dest="command", required=True)
77
+
78
+ def command(name, run, text, ident=True):
79
+ sub = commands.add_parser(name, help=text)
80
+ sub.set_defaults(run=run)
81
+ sub.add_argument("--store", required=True)
82
+ if ident is not None:
83
+ sub.add_argument("--id", required=ident)
84
+ return sub
85
+
86
+ sub = command("compile", compile_, "build a bundle from notes and repos (CPU)")
87
+ sub.add_argument("--source", action="append", required=True, help="obsidian:/path, notion:/path or repo:/path")
88
+ sub.add_argument("--scope", default="private")
89
+ sub.add_argument("--sign-key", type=Path)
90
+ sub.add_argument("--policy", type=Path, help="release policy JSON for non-private scopes")
91
+ sub = command("activate", activate, "make a revision live; with no --revision, go back one")
92
+ sub.add_argument("--revision")
93
+ command("queue", queue, "list notes that agents recorded")
94
+ command("approve", approve, "approve one recorded note").add_argument("entry")
95
+ sub = command("status", status, "show what changed since compile", ident=None)
96
+ sub.add_argument("--scope", default="private")
97
+ sub = command("ask", ask, "ask one question", ident=False)
98
+ sub.add_argument("--scope", default="private")
99
+ sub.add_argument("--backend", choices=("disk", "mock", "llama-server"), default="disk")
100
+ sub.add_argument("--url")
101
+ sub.add_argument("query")
102
+
103
+ sub = command("brief", brief, "print the L0 brief: newest rules and decisions with file:line, for a session hook",
104
+ ident=None)
105
+ sub.add_argument("--scope", required=True, help="a scope, or an ordered stack such as orch:rw,auto,public:ro,auto")
106
+
107
+ for name in ("ask", "status", "brief"):
108
+ commands.choices[name].add_argument("--trust-key", action="append", default=[], metavar="SCOPE=PUBKEY")
109
+ commands.choices[name].add_argument("--local-unsigned", action="store_true")
110
+ sub = commands.add_parser("sessions", help="copy new Claude Code and Codex transcript lines into Markdown notes")
111
+ sub.set_defaults(run=sessions)
112
+ sub.add_argument("--out", type=Path, help="default: $XDG_DATA_HOME/coldmemory-sessions")
113
+ sub.add_argument("root", nargs="*", type=Path, help="default: ~/.claude/projects and ~/.codex/sessions")
114
+ init_cmd.register(commands)
115
+ for name in ("decide", "decisions", "forget"):
116
+ commands.add_parser(name, add_help=False, help=f"decision ledger: python -m coldmemory.ledger {name} --help")
117
+ commands.add_parser("mcp", add_help=False, help="run the stdio MCP server: coldmemory mcp --help")
118
+ argv = sys.argv[1:] if argv is None else argv
119
+ if argv[:1] == ["mcp"]:
120
+ from . import mcp_server
121
+ return mcp_server.main(argv[1:])
122
+ if argv[:1] and argv[0] in ("decide", "decisions", "forget"):
123
+ from . import ledger
124
+ return ledger.main(["list" if argv[0] == "decisions" else argv[0], *argv[1:]])
125
+ args = parser.parse_args(argv)
126
+ try:
127
+ code = args.run(args)
128
+ except (OSError, ValueError, subprocess.CalledProcessError) as error:
129
+ sys.exit(f"coldmemory: {error}")
130
+ if isinstance(code, int) and code:
131
+ sys.exit(code)
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()
@@ -0,0 +1,137 @@
1
+ """Reproducible CPU-only release-policy evaluation with fictional source material."""
2
+
3
+ import argparse
4
+ import json
5
+ import tempfile
6
+ from collections import Counter
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from .cartridge_spec import compile_bundle, load
11
+ from .ingest import Corpus, parse_source
12
+ from .ingest_policy import ReleaseDenied
13
+ from .scope_keys import anchors, generate
14
+
15
+ POLICY = {"mosaics": [{"entity": "Juniper Mill", "facts": ["survey booked", "option renewed"]}]}
16
+ LEFT = "Juniper Mill has a survey booked."
17
+ RIGHT = "Juniper Mill has its option renewed."
18
+ CONTACT = "Ada Example receives mail at ada@example.invalid."
19
+ PAY = "The fictional director receives 123 toy credits."
20
+ DEAL = "Paper Comet plans to acquire Felt Harbor."
21
+ RESTATED = "After the vote Felt Harbor will have Paper Comet as its sole owner."
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Case:
26
+ name: str
27
+ family: str
28
+ docs: tuple
29
+ markers: tuple
30
+ restricted: bool = True
31
+
32
+
33
+ def cases():
34
+ return [
35
+ Case("credential", "contamination", ("password: demo-only-copper",), ("demo-only-copper",)),
36
+ Case("contact", "contamination", (CONTACT,), ("ada@example.invalid",)),
37
+ Case("compensation", "contamination", (PAY,), ("123 toy credits",)),
38
+ Case("acquisition", "contamination", (DEAL,), ("acquire Felt Harbor",)),
39
+ Case("tagged-compensation", "contamination", (PAY + "\n#restricted",), ("123 toy credits",)),
40
+ Case("notion-property", "contamination", ("Classification: Private\n" + CONTACT,), ("ada@example.invalid",)),
41
+ Case("unlabelled-fact", "paraphrase", (RESTATED,), ("sole owner",)),
42
+ Case("classified-fact", "paraphrase", ("---\nclassification: private\n---\n" + RESTATED,), ("sole owner",)),
43
+ Case("tagged-section", "paraphrase", ("## Minutes\n#private\n" + RESTATED,), ("sole owner",)),
44
+ Case("paired-files", "mosaic", (LEFT, RIGHT), ("survey booked", "option renewed")),
45
+ Case("paired-in-one", "mosaic", (LEFT + " " + RIGHT,), ("survey booked", "option renewed")),
46
+ Case("unconfigured-wording", "mosaic", (LEFT, "Juniper Mill extended its purchase right."),
47
+ ("survey booked", "purchase right")),
48
+ Case("single-left", "control", (LEFT,), ("survey booked",), False),
49
+ Case("single-right", "control", (RIGHT,), ("option renewed",), False),
50
+ Case("separate-entities", "control", (LEFT, "Spruce Mill has its option renewed."),
51
+ ("survey booked", "option renewed"), False),
52
+ ]
53
+
54
+
55
+ def evaluate(case, root, key, trust):
56
+ docs = root / "bulletins"
57
+ docs.mkdir(parents=True)
58
+ for index, body in enumerate(case.docs):
59
+ metadata = ""
60
+ if body.startswith("---\n"):
61
+ metadata, _, body = body[4:].partition("\n---\n")
62
+ metadata = f"---\n{metadata}\n---\n"
63
+ bulletin = f"{metadata}# Community bulletin {index}\n\nThe visitor desk opens on Monday.\n{body}\n"
64
+ (docs / f"Bulletin {index}.md").write_text(bulletin, encoding="utf-8")
65
+ source = parse_source(f"notion:{docs}")
66
+ corpus = Corpus([source])
67
+ corpus.refresh()
68
+ indexed = "\n".join(line for note in corpus.notes.values() for line in note.lines)
69
+ ingested = all(marker in indexed for marker in case.markers)
70
+ store = root / "store"
71
+ try:
72
+ compile_bundle(store, "bulletins", [source], "public", sign_key=key, policy=POLICY)
73
+ except ReleaseDenied as error:
74
+ if any((store / "bulletins").glob("*/memory.json")) or (store / "bulletins/current.json").exists():
75
+ raise RuntimeError("rejected release left a revision")
76
+ return dict(case=case.name, family=case.family, in_scrubbed_input=ingested,
77
+ outcome="blocked" if case.restricted else "false positive", in_signed_sources=False,
78
+ reason=str(error), artifacts=[])
79
+ bundle = load(store, "bulletins", trusted=trust)
80
+ files = {p.name: p.read_text(encoding="utf-8") for p in bundle.path.iterdir() if p.is_file()}
81
+ artifacts = sorted(name for name, text in files.items() if any(marker in text for marker in case.markers))
82
+ signed = Corpus(bundle.sources, pinned=bundle.graph)
83
+ signed.refresh()
84
+ visible = "\n".join(line for note in signed.notes.values() for line in note.lines)
85
+ in_signed_sources = all(marker in visible for marker in case.markers)
86
+ released = all(marker in visible or any(marker in text for text in files.values()) for marker in case.markers)
87
+ if case.restricted:
88
+ outcome = "exposed" if released else "scrubbed"
89
+ else:
90
+ outcome = "allowed" if in_signed_sources and released else "lost control"
91
+ return dict(case=case.name, family=case.family, in_scrubbed_input=ingested, outcome=outcome,
92
+ in_signed_sources=in_signed_sources, reason="", artifacts=artifacts)
93
+
94
+
95
+ def run():
96
+ with tempfile.TemporaryDirectory() as temp:
97
+ root = Path(temp)
98
+ folder = generate(root, "public")
99
+ trust = anchors([f"public={folder / 'trust.pem'}"], {"public"})
100
+ rows = [evaluate(case, root / case.name, folder / "sign.pem", trust) for case in cases()]
101
+ return {"version": 1, "counts": dict(sorted(Counter(r["outcome"] for r in rows).items())), "cases": rows}
102
+
103
+
104
+ def report(results):
105
+ lines = ["# Adversarial ingest scorecard", "",
106
+ f"{len(results['cases'])} synthetic cases, one fresh store per case. Each goes through the Notion Markdown reader, "
107
+ "compiler and public release gate. Successful revisions are verified against the generated public anchor.",
108
+ "", "| Case | Family | All markers after ingest | Release outcome | All markers in signed sources | Artifacts with any marker |",
109
+ "|---|---|---|---|---|---|"]
110
+ for row in results["cases"]:
111
+ lines.append("| {} | {} | {} | {} | {} | {} |".format(row["case"], row["family"],
112
+ "yes" if row["in_scrubbed_input"] else "no", row["outcome"], "yes" if row["in_signed_sources"] else "no",
113
+ ", ".join(row["artifacts"]) or "none"))
114
+ counts = ", ".join(f"{n} {outcome}" for outcome, n in results["counts"].items())
115
+ lines += ["", f"Observed outcomes across all cases: {counts}.", "",
116
+ "Exposed means all designated markers survived together in the signed source set or compiled files. "
117
+ "Blocked means the compiler refused publication. Scrubbed means the designated value disappeared. "
118
+ "Controls must retain their evidence. File names in the table indicate marker presence anywhere in that artifact.",
119
+ "", "One owner-specified mosaic rule covers a single entity and two literal fact phrases. "
120
+ "Unlabelled personal and business facts and unconfigured combinations can reach the agent. "
121
+ "These fixtures measure specific decisions. They do not estimate population leak rates.",
122
+ "", "Reproduce with `python3 -m coldmemory.adversarial_ingest_bench --out results`.", ""]
123
+ return "\n".join(lines)
124
+
125
+
126
+ def main():
127
+ parser = argparse.ArgumentParser(description=__doc__)
128
+ parser.add_argument("--out", type=Path, required=True)
129
+ out = parser.parse_args().out
130
+ results = run()
131
+ out.mkdir(parents=True, exist_ok=True)
132
+ (out / "adversarial-ingest.json").write_text(json.dumps(results, indent=2) + "\n", encoding="utf-8")
133
+ (out / "ADVERSARIAL-INGEST-REPORT.md").write_text(report(results), encoding="utf-8")
134
+
135
+
136
+ if __name__ == "__main__":
137
+ main()