cof-cli 1.2.1__tar.gz → 1.2.2__tar.gz

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 (48) hide show
  1. {cof_cli-1.2.1 → cof_cli-1.2.2}/PKG-INFO +5 -2
  2. {cof_cli-1.2.1 → cof_cli-1.2.2}/README.md +4 -1
  3. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/__init__.py +1 -1
  4. cof_cli-1.2.2/cof_cli/agents.py +269 -0
  5. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/cli.py +91 -3
  6. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/completeness.py +7 -3
  7. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/convert.py +28 -5
  8. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/psyche.py +1 -0
  9. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli.egg-info/PKG-INFO +5 -2
  10. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli.egg-info/SOURCES.txt +2 -0
  11. {cof_cli-1.2.1 → cof_cli-1.2.2}/pyproject.toml +1 -1
  12. cof_cli-1.2.2/tests/test_agents.py +155 -0
  13. {cof_cli-1.2.1 → cof_cli-1.2.2}/tests/test_roundtrip.py +42 -0
  14. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/cast.py +0 -0
  15. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/container.py +0 -0
  16. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/memories.py +0 -0
  17. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/migrate.py +0 -0
  18. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/model.py +0 -0
  19. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/ops.py +0 -0
  20. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/platform_import.py +0 -0
  21. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/profiles.py +0 -0
  22. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/propose.py +0 -0
  23. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/attitude.schema.json +0 -0
  24. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/body.schema.json +0 -0
  25. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/card.schema.json +0 -0
  26. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/consent.schema.json +0 -0
  27. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/garments-1.0.json +0 -0
  28. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/hair.schema.json +0 -0
  29. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/manifest.schema.json +0 -0
  30. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/memory.schema.json +0 -0
  31. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/pose.schema.json +0 -0
  32. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/psyche-node.schema.json +0 -0
  33. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/psyche.schema.json +0 -0
  34. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/skeleton.schema.json +0 -0
  35. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/visemes.schema.json +0 -0
  36. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/voice-profile.schema.json +0 -0
  37. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/schemas/weights.schema.json +0 -0
  38. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/selfdesc.py +0 -0
  39. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/tokens.py +0 -0
  40. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/validate.py +0 -0
  41. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli/zodiac.py +0 -0
  42. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli.egg-info/dependency_links.txt +0 -0
  43. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli.egg-info/entry_points.txt +0 -0
  44. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli.egg-info/requires.txt +0 -0
  45. {cof_cli-1.2.1 → cof_cli-1.2.2}/cof_cli.egg-info/top_level.txt +0 -0
  46. {cof_cli-1.2.1 → cof_cli-1.2.2}/setup.cfg +0 -0
  47. {cof_cli-1.2.1 → cof_cli-1.2.2}/tests/test_hunt.py +0 -0
  48. {cof_cli-1.2.1 → cof_cli-1.2.2}/tests/test_platform_import.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cof-cli
3
- Version: 1.2.1
3
+ Version: 1.2.2
4
4
  Summary: COF — Character Open File: validate, pack, unpack and convert .cof character containers
5
5
  Author: Yann Souetre
6
6
  License-Expression: MIT
@@ -32,6 +32,7 @@ cof extract clara.cof --preset default --no-risk -o clara-sans-risque/ #
32
32
  cof merge clara.cof martien.cof -o duo/ # un casting : même nom + surnom + statut fictif + morphologie ⇒ même personnage, sinon plusieurs
33
33
  cof memory add clara.cof --gist fr="Ce matin, relu avec Léo." --gist en="This morning, reread with Léo." --date 2026-10-25 --who "Léo" --what "le carnet" --what "item=appearance/x1" --tag travail --personal # --what : un objet (1.2, RFC 0005), un nom et/ou item=<élément>, |shown s'il est dans un média
34
34
  cof memory add clara/ --kind period --gist en="The agency years." --age 24 --approx --fidelity faded # sur un dossier ; `--help` liste tout (--where, --self-shown, --media, --preset…)
35
+ cof memory add clara.cof --from-agent ./agent/ # le retour : les notes du jour d'un espace OpenClaw (memory/AAAA-MM-JJ.md) ou les entrées § d'un profil Hermes (memories/MEMORY.md) deviennent des souvenirs vécus, personnels, datés, étiquetés lived:<hôte> ; idempotent (--agent-source, --lang)
35
36
  cof psyche add clara.cof --kind stance --gist fr="Envers l'utilisateur : une collègue." --about user --strength 60 --stability shifting --link because=memories/ev3 --since-date 2026-10-25 # nœud vécu, `visibility: personal` (--canon sinon), première révision ; `--help` liste tout (--lie, --risk, --tag, --preset…)
36
37
  cof psyche add clara.cof --kind habit --gist fr="Garde la guitare près du bureau." --who "ma grand-mère" --where "environment=appearance/e1" --what "ma guitare|item=appearance/x1" --canon # personnes, lieux, objets du nœud (RFC 0005) ; une personne du casting : --who identity=<id> (les liens --link ne visent que souvenirs et nœuds)
37
38
  cof psyche add clara.cof --kind stance --gist fr="Envers l'utilisateur : de la chaleur." --about user --valence 60 --aware partly --canon # RFC 0004 § 3 nonies : --valence −100…+100 (position ou goût seulement), --aware yes|partly|no, --until-age / --until-date (quand le nœud a cessé d'être tenu)
@@ -43,7 +44,9 @@ cof import carte.png -o perso/ --age 30 --lang fr --keep-png # carte PNG CCv2/
43
44
  cof export clara.cof --format png -o clara.png # → PNG avec chunks chara + ccv3
44
45
  cof export clara.cof --format card -o clara.card.json
45
46
  cof export clara.cof --format soul -o ./agent/ # → SOUL.md + IDENTITY.md
46
- cof export clara.cof --format agent -o ./agent/ # → espace de travail d'agent : SOUL.md (avec « Qui elle est » rendu depuis la psyché), IDENTITY.md, skills/, MEMORY.md + memories/ (--keep-personal, --keep-dangerous, --preset)
47
+ cof diff clara.cof rebuilt.cof # ce qui diffère entre deux .cof : membres, octets, clés JSON (code de sortie 1 si différent) — l'outil de la promesse « rien d'autre ne bouge » du builder
48
+ cof export clara.cof --format agent -o ./agent/ # → espace de travail d'agent : SOUL.md (avec « Qui elle est » rendu depuis la psyché), IDENTITY.md, AGENTS.md (consignes de mémoire pour l'hôte), skills/, MEMORY.md, COF.md (--keep-personal, --keep-dangerous, --keep-secrets, --preset) ; les souvenirs `disclosure: secret` restent dans le .cof sauf --keep-secrets (« N secret memories left out »), qui les écrit marqués `secret` et ajoute à AGENTS.md une ligne : ce sont des secrets que le personnage ne révèle jamais
49
+ cof export clara.cof --format hermes -o ./hermes/ # → profil Hermes Agent (HERMES_HOME) : SOUL.md (identité fusionnée), memories/MEMORY.md en entrées § sous le plafond de l'hôte (2 200 caractères, les plus saillants), skills/, COF.md ; mêmes options, secrets laissés de côté par défaut (avec --keep-secrets : entrées préfixées « (secret) », la ligne dans SOUL.md)
47
50
  cof embed-text clara.png fiche.md -o clara-fiche.png # texte descriptif dans un PNG (iTXt), lisible par le builder
48
51
  cof read-text clara-fiche.png
49
52
  cof migrate dossier-v0.5/ # v0.2 … v0.5 → 1.0
@@ -15,6 +15,7 @@ cof extract clara.cof --preset default --no-risk -o clara-sans-risque/ #
15
15
  cof merge clara.cof martien.cof -o duo/ # un casting : même nom + surnom + statut fictif + morphologie ⇒ même personnage, sinon plusieurs
16
16
  cof memory add clara.cof --gist fr="Ce matin, relu avec Léo." --gist en="This morning, reread with Léo." --date 2026-10-25 --who "Léo" --what "le carnet" --what "item=appearance/x1" --tag travail --personal # --what : un objet (1.2, RFC 0005), un nom et/ou item=<élément>, |shown s'il est dans un média
17
17
  cof memory add clara/ --kind period --gist en="The agency years." --age 24 --approx --fidelity faded # sur un dossier ; `--help` liste tout (--where, --self-shown, --media, --preset…)
18
+ cof memory add clara.cof --from-agent ./agent/ # le retour : les notes du jour d'un espace OpenClaw (memory/AAAA-MM-JJ.md) ou les entrées § d'un profil Hermes (memories/MEMORY.md) deviennent des souvenirs vécus, personnels, datés, étiquetés lived:<hôte> ; idempotent (--agent-source, --lang)
18
19
  cof psyche add clara.cof --kind stance --gist fr="Envers l'utilisateur : une collègue." --about user --strength 60 --stability shifting --link because=memories/ev3 --since-date 2026-10-25 # nœud vécu, `visibility: personal` (--canon sinon), première révision ; `--help` liste tout (--lie, --risk, --tag, --preset…)
19
20
  cof psyche add clara.cof --kind habit --gist fr="Garde la guitare près du bureau." --who "ma grand-mère" --where "environment=appearance/e1" --what "ma guitare|item=appearance/x1" --canon # personnes, lieux, objets du nœud (RFC 0005) ; une personne du casting : --who identity=<id> (les liens --link ne visent que souvenirs et nœuds)
20
21
  cof psyche add clara.cof --kind stance --gist fr="Envers l'utilisateur : de la chaleur." --about user --valence 60 --aware partly --canon # RFC 0004 § 3 nonies : --valence −100…+100 (position ou goût seulement), --aware yes|partly|no, --until-age / --until-date (quand le nœud a cessé d'être tenu)
@@ -26,7 +27,9 @@ cof import carte.png -o perso/ --age 30 --lang fr --keep-png # carte PNG CCv2/
26
27
  cof export clara.cof --format png -o clara.png # → PNG avec chunks chara + ccv3
27
28
  cof export clara.cof --format card -o clara.card.json
28
29
  cof export clara.cof --format soul -o ./agent/ # → SOUL.md + IDENTITY.md
29
- cof export clara.cof --format agent -o ./agent/ # → espace de travail d'agent : SOUL.md (avec « Qui elle est » rendu depuis la psyché), IDENTITY.md, skills/, MEMORY.md + memories/ (--keep-personal, --keep-dangerous, --preset)
30
+ cof diff clara.cof rebuilt.cof # ce qui diffère entre deux .cof : membres, octets, clés JSON (code de sortie 1 si différent) — l'outil de la promesse « rien d'autre ne bouge » du builder
31
+ cof export clara.cof --format agent -o ./agent/ # → espace de travail d'agent : SOUL.md (avec « Qui elle est » rendu depuis la psyché), IDENTITY.md, AGENTS.md (consignes de mémoire pour l'hôte), skills/, MEMORY.md, COF.md (--keep-personal, --keep-dangerous, --keep-secrets, --preset) ; les souvenirs `disclosure: secret` restent dans le .cof sauf --keep-secrets (« N secret memories left out »), qui les écrit marqués `secret` et ajoute à AGENTS.md une ligne : ce sont des secrets que le personnage ne révèle jamais
32
+ cof export clara.cof --format hermes -o ./hermes/ # → profil Hermes Agent (HERMES_HOME) : SOUL.md (identité fusionnée), memories/MEMORY.md en entrées § sous le plafond de l'hôte (2 200 caractères, les plus saillants), skills/, COF.md ; mêmes options, secrets laissés de côté par défaut (avec --keep-secrets : entrées préfixées « (secret) », la ligne dans SOUL.md)
30
33
  cof embed-text clara.png fiche.md -o clara-fiche.png # texte descriptif dans un PNG (iTXt), lisible par le builder
31
34
  cof read-text clara-fiche.png
32
35
  cof migrate dossier-v0.5/ # v0.2 … v0.5 → 1.0
@@ -1,5 +1,5 @@
1
1
  """cof-cli — reference tooling for COF (Character Open File)."""
2
2
 
3
- __version__ = "1.2.1"
3
+ __version__ = "1.2.2"
4
4
  MIMETYPE = "application/vnd.cof.character+zip"
5
5
  SPEC_VERSION = "1.2"
@@ -0,0 +1,269 @@
1
+ """Agent hosts (8 Nov. 2026): what `cof export --format agent` adds for OpenClaw, the Hermes Agent profile
2
+ (`--format hermes`), and the way back — `cof memory add --from-agent <dir>` turns what an agent wrote during use into
3
+ `lived`, `personal` memories (RFC 0002 § 3: canon is read-only for tools; everything that happens in use is a layer of
4
+ lived nodes).
5
+
6
+ Facts the code relies on (read in the two repositories, 8 Nov. 2026):
7
+ - OpenClaw (openclaw/openclaw): a workspace is a folder of Markdown files — AGENTS.md (operating instructions, loaded
8
+ every session), SOUL.md, IDENTITY.md, USER.md, MEMORY.md (curated long-term memory), memory/YYYY-MM-DD.md (daily
9
+ notes the agent appends to), skills/<name>/SKILL.md. The agent writes memory only where AGENTS.md tells it to.
10
+ - Hermes Agent (NousResearch/hermes-agent): a profile ($HERMES_HOME) holds SOUL.md, memories/MEMORY.md and
11
+ memories/USER.md written by its `memory` tool — entries separated by "\\n§\\n", MEMORY.md capped at 2 200 characters
12
+ (tools/memory_tool_store.py: "Warn; never truncate a user's memories") — and skills/<name>/SKILL.md.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ import sys
19
+ from datetime import datetime, timezone
20
+ from pathlib import Path
21
+
22
+ HERMES_MEMORY_CHARS = 2200 # tools/memory_tool.py MEMORY_CHAR_LIMIT in hermes-agent 2026.9 — the host refuses to add beyond it
23
+ HERMES_DELIM = "\n§\n"
24
+ NOTE_LINE = re.compile(r"^\s*[-*]\s*(?:(?P<time>\d{1,2}:\d{2})\s*[·\-–]\s*)?(?P<body>.+?)\s*$")
25
+ AXIS = re.compile(r"\s*·\s*(with|where|tags|avec|où|étiquettes)\s*:\s*", re.I)
26
+
27
+
28
+ # ----------------------------------------------------------------------------- AGENTS.md (OpenClaw)
29
+ SECRETS_LINE = ("Memories marked `secret` (in `MEMORY.md`) are secrets the character never reveals: "
30
+ "they shape what you say, you never tell them, hint at them or confirm them.")
31
+
32
+
33
+ def agents_md(name: str, lang: str = "en", gender: str | None = None) -> str:
34
+ """The operating notes OpenClaw reads at the start of every session. Without them the agent has no instruction to
35
+ write memory at all; with them, its daily notes come back into the .cof through `cof memory add --from-agent`."""
36
+ subj, poss = {"female": ("she", "her"), "male": ("he", "his")}.get(gender or "", ("they", "their")) # RFC 0003 gender → pronouns
37
+ return "\n".join([
38
+ f"# AGENTS.md — operating notes for {name}",
39
+ "",
40
+ f"This workspace was exported from a Character Open File (.cof). `SOUL.md` says who {name} is, `IDENTITY.md` how",
41
+ f"{subj} present{'s' if subj != 'they' else ''}, `MEMORY.md` what {subj} remember{'s' if subj != 'they' else ''} (curated by {poss} author), `COF.md` what {poss} author allows, `skills/` what {subj} know{'s' if subj != 'they' else ''} how to do.",
42
+ "",
43
+ "## Memory",
44
+ "",
45
+ "- `MEMORY.md` is the curated long-term memory: read it, never rewrite it by hand — your host consolidates it.",
46
+ "- During a session, append what you live to `memory/YYYY-MM-DD.md` (today's date, UTC), **one line per fact**, in this exact shape so the character file can take it back:",
47
+ "",
48
+ " `- HH:MM · <one or two sentences, first person, past tense> · with: <people> · where: <place> · tags: <a, b>`",
49
+ "",
50
+ " `with`, `where` and `tags` are optional; keep each line under 400 characters; write in the language of the conversation.",
51
+ "- Write what happened and what it changed for you — not the user's secrets, passwords, keys or private data. If the user asks you to forget something, delete the line.",
52
+ "",
53
+ "## Rights",
54
+ "",
55
+ "`COF.md` lists the permissions the author granted. Honour them: they travel with the character, not with the host.",
56
+ "",
57
+ "## Skills",
58
+ "",
59
+ "`skills/<name>/SKILL.md` — load a skill when its description matches the task.",
60
+ "",
61
+ ])
62
+
63
+
64
+ # ----------------------------------------------------------------------------- Hermes profile
65
+ def hermes_identity_block(identity_md: str) -> str:
66
+ """Hermes has no IDENTITY.md: its lines (`- Label: value`) become a short "Identity" section of SOUL.md, avatar aside."""
67
+ rows = [l for l in identity_md.splitlines() if l.startswith("- ") and not l.lower().startswith("- avatar:")]
68
+ return "\n".join(["## Identity", *rows, ""]) if rows else ""
69
+
70
+
71
+ def hermes_memory(entries: list[tuple[int, str]], limit: int = HERMES_MEMORY_CHARS) -> tuple[str, int]:
72
+ """`memories/MEMORY.md` for Hermes: entries separated by `§`, the most salient first until the host's limit,
73
+ then back in timeline order. Returns (text, entries dropped)."""
74
+ order = sorted(range(len(entries)), key=lambda i: (-entries[i][0], i))
75
+ kept, used = set(), 0
76
+ for i in order:
77
+ e = entries[i][1].strip()
78
+ cost = len(e) + (len(HERMES_DELIM) if kept else 0)
79
+ if used + cost > limit:
80
+ continue
81
+ kept.add(i); used += cost
82
+ text = HERMES_DELIM.join(entries[i][1].strip() for i in range(len(entries)) if i in kept)
83
+ return text, len(entries) - len(kept)
84
+
85
+
86
+ def export_hermes(src: Path, out: Path, preset: str | None = None, keep_personal: bool = False, keep_dangerous: bool = False, keep_secrets: bool = False) -> dict:
87
+ """A Hermes Agent profile folder (to use as $HERMES_HOME, or to copy into one): SOUL.md (with the identity lines),
88
+ memories/MEMORY.md (`§` entries within the host's limit), skills/, COF.md, README-COF.md. Built on export_agent.
89
+ Secret memories stay behind unless `keep_secrets`; with it their entries carry `(secret)` and SOUL.md says they are never told."""
90
+ import shutil
91
+ import tempfile
92
+ from .convert import export_agent
93
+ with tempfile.TemporaryDirectory(prefix="cof-hermes-") as td:
94
+ ws = Path(td) / "ws"
95
+ done = export_agent(src, ws, preset, keep_personal=keep_personal, keep_dangerous=keep_dangerous, keep_secrets=keep_secrets)
96
+ out.mkdir(parents=True, exist_ok=True)
97
+ soul = (ws / "SOUL.md").read_text("utf-8").rstrip() + "\n"
98
+ ident = (ws / "IDENTITY.md").read_text("utf-8") if (ws / "IDENTITY.md").is_file() else ""
99
+ block = hermes_identity_block(ident)
100
+ if block:
101
+ head, _, rest = soul.partition("\n")
102
+ soul = head + "\n\n" + block + "\n" + rest.lstrip("\n")
103
+ entries = _memory_entries(src, preset, keep_personal, keep_secrets)
104
+ if keep_secrets and done.get("secret_kept"): # Hermes has no AGENTS.md: SOUL.md is what it reads every session
105
+ soul = soul.rstrip("\n") + "\n\n" + SECRETS_LINE.replace("(in `MEMORY.md`)", "(in `memories/MEMORY.md`)") + "\n"
106
+ (out / "SOUL.md").write_text(soul, "utf-8")
107
+ text, dropped = hermes_memory(entries)
108
+ (out / "memories").mkdir(exist_ok=True)
109
+ (out / "memories" / "MEMORY.md").write_text(text + ("\n" if text else ""), "utf-8")
110
+ done["hermes_memory_entries"], done["hermes_memory_dropped"], done["hermes_memory_chars"] = len(entries) - dropped, dropped, len(text)
111
+ if (ws / "skills").is_dir():
112
+ shutil.copytree(ws / "skills", out / "skills", dirs_exist_ok=True)
113
+ for f in ("COF.md",):
114
+ if (ws / f).is_file():
115
+ shutil.copy(ws / f, out / f)
116
+ av = next((p for p in ws.glob("avatar.*")), None)
117
+ if av:
118
+ shutil.copy(av, out / av.name) # Hermes shows an avatar only in its desktop Bot Mode: kept for that upload
119
+ (out / "README-COF.md").write_text("\n".join([
120
+ "# This profile came from a Character Open File",
121
+ "",
122
+ f"`SOUL.md` and `memories/MEMORY.md` were written by `cof export --format hermes` (preset `{preset or 'default'}`).",
123
+ f"`memories/MEMORY.md` holds {done['hermes_memory_entries']} of {len(entries)} memories, within the host's limit of {HERMES_MEMORY_CHARS} characters"
124
+ + (f" ({dropped} left in the .cof)." if dropped else "."),
125
+ "Use it as `HERMES_HOME`, or copy `SOUL.md`, `memories/` and `skills/` into an existing profile.",
126
+ "What Hermes writes to `memories/MEMORY.md` during use comes back into the .cof with `cof memory add <file> --from-agent <this folder>`.",
127
+ "`COF.md` lists the rights the author granted; the host does not read it, you do.",
128
+ "",
129
+ ]), "utf-8")
130
+ return done
131
+
132
+
133
+ def _memory_entries(src: Path, pid: str | None, keep_personal: bool, keep_secrets: bool = False) -> list[tuple[int, str]]:
134
+ """(salience, 'label (when): gist') per canon memory of the preset, timeline order."""
135
+ from .memories import gist_text, load_nodes, preset_memories, timeline, when_label
136
+ from .model import default_preset_id, resolve_variant
137
+ manifest = json.loads((src / "manifest.json").read_text("utf-8"))
138
+ pid = pid or default_preset_id(manifest)
139
+ nodes = load_nodes(src, manifest)
140
+ vids = [v for v in preset_memories(manifest, pid) if v in nodes]
141
+ out = []
142
+ for vid in timeline(manifest, nodes, vids):
143
+ node = nodes[vid]
144
+ if node.get("visibility") == "personal" and not keep_personal:
145
+ continue
146
+ secret = node.get("disclosure") == "secret"
147
+ if secret and not keep_secrets:
148
+ continue # a secret never leaves with an agent that talks, unless asked (CLI-02)
149
+ rv = resolve_variant(manifest, "memories", vid) or {}
150
+ lang, text = gist_text(manifest, vid, node, pid)
151
+ when = when_label(rv.get("kind"), node, lang)
152
+ label = rv.get("label") or vid
153
+ t = text.strip()
154
+ if t.lower().startswith(label.strip().rstrip("…").lower()[:40]): # a lived memory's label is the start of its text: say the when, not the text twice
155
+ entry = (f"{when}: " if when else "") + t
156
+ else:
157
+ entry = f"{label}" + (f" ({when})" if when else "") + f": {t}"
158
+ if secret:
159
+ entry = "(secret) " + entry
160
+ out.append((int(node.get("salience") or 50), entry))
161
+ return out
162
+
163
+
164
+ # ----------------------------------------------------------------------------- the way back
165
+ def parse_agent_dir(folder: Path) -> list[dict]:
166
+ """What an agent wrote during use, as entries {source, file, date, time, text, with, where, tags}:
167
+ OpenClaw daily notes `memory/YYYY-MM-DD.md` (bullet lines, ideally in the AGENTS.md shape) and
168
+ Hermes `memories/MEMORY.md` (`§`-separated entries). A curated MEMORY.md of an OpenClaw workspace is not read:
169
+ it is the export itself, consolidated by the host — the daily notes are the record of what happened."""
170
+ out: list[dict] = []
171
+ mem = folder / "memory"
172
+ if mem.is_dir():
173
+ for f in sorted(mem.glob("*.md")):
174
+ m = re.fullmatch(r"(\d{4}-\d{2}-\d{2})", f.stem)
175
+ if not m:
176
+ continue
177
+ try:
178
+ datetime.strptime(m.group(1), "%Y-%m-%d")
179
+ except ValueError:
180
+ print(f"WARN {f.name}: not a date — day note skipped", file=sys.stderr)
181
+ continue
182
+ for line in f.read_text("utf-8", errors="replace").splitlines():
183
+ mm = NOTE_LINE.match(line)
184
+ if not mm or not mm.group("body").strip() or line.lstrip().startswith("#"):
185
+ continue
186
+ e = _split_axes(mm.group("body"))
187
+ if not e["text"]:
188
+ continue
189
+ e.update(source="openclaw", file=str(f.relative_to(folder)), date=m.group(1), time=mm.group("time") or "")
190
+ out.append(e)
191
+ hm = folder / "memories" / "MEMORY.md"
192
+ if hm.is_file():
193
+ raw = hm.read_text("utf-8", errors="replace")
194
+ for chunk in raw.split("§"):
195
+ text = chunk.strip()
196
+ if not text or text.startswith("#"):
197
+ continue
198
+ e = _split_axes(text)
199
+ if not e["text"]:
200
+ continue
201
+ day = datetime.fromtimestamp(hm.stat().st_mtime, timezone.utc).strftime("%Y-%m-%d")
202
+ md = re.match(r"(\d{4}-\d{2}-\d{2})(?: \d{2}:\d{2})?:\s+(.+)$", e["text"], re.S) # an entry that starts with its day (a lived memory exported by cof)
203
+ if md:
204
+ day, e["text"] = md.group(1), md.group(2).strip()
205
+ e.update(source="hermes", file="memories/MEMORY.md", date=day, time="")
206
+ out.append(e)
207
+ return out
208
+
209
+
210
+ def _split_axes(body: str) -> dict:
211
+ """'text · with: a, b · where: place · tags: x, y' → parts (French labels accepted)."""
212
+ parts = AXIS.split(body)
213
+ e = {"text": parts[0].strip(" ·"), "with": [], "where": "", "tags": []}
214
+ for key, val in zip(parts[1::2], parts[2::2]):
215
+ k = key.lower()
216
+ if k in ("with", "avec"):
217
+ e["with"] = [x.strip() for x in re.split(r"[,;]", val) if x.strip()]
218
+ elif k in ("where", "où"):
219
+ e["where"] = val.strip()
220
+ else:
221
+ e["tags"] = [x.strip() for x in re.split(r"[,;]", val) if x.strip()]
222
+ return e
223
+
224
+
225
+ def import_agent_memories(work: Path, folder: Path, *, identity: str | None = None, lang: str | None = None,
226
+ presets: list[str] | None = None, source: str | None = None) -> list[str]:
227
+ """Append what the agent lived as `lived`, `personal` memories of the unpacked character folder `work`; an entry
228
+ whose text is already a lived memory of the file is skipped (re-import is idempotent). Returns the new node ids."""
229
+ from .memories import load_nodes
230
+ from .selfdesc import memory_add
231
+ manifest = json.loads((work / "manifest.json").read_text("utf-8"))
232
+ lived: set[tuple[str, str]] = set(); canon: set[str] = set()
233
+ for n in load_nodes(work, manifest).values():
234
+ for g in (n.get("gist") or {}).values():
235
+ if n.get("origin") == "lived":
236
+ lived.add(((n.get("when") or {}).get("date") or "", _norm(g)))
237
+ else:
238
+ canon.add(_norm(g))
239
+ long_canon = [c for c in canon if len(c) >= 24]; short_canon = [c for c in canon if 8 <= len(c) < 24]
240
+ entries = [e for e in parse_agent_dir(folder) if not source or e["source"] == source]
241
+ if not entries:
242
+ raise ValueError(f"{folder}: nothing to import (memory/YYYY-MM-DD.md notes or memories/MEMORY.md entries)")
243
+ lang = lang or _guess_lang(manifest)
244
+ added = []
245
+ for e in entries:
246
+ n = _norm(e["text"])
247
+ if (e["date"], n) in lived: # the same fact on the same day: already there (re-import is idempotent)
248
+ continue
249
+ if n in canon or any(c in n for c in long_canon) or any(n.endswith(c) for c in short_canon):
250
+ continue # an entry the host got FROM the file (a Hermes MEMORY.md repeats the export): not lived
251
+ tags = [f"lived:{e['source']}", *e["tags"]]
252
+ who = [w.replace("|", "/") for w in e["with"]] # names only: an agent's note never sets shown / real / age (the --who syntax) — hunt 1.2.2, SAFETY-04
253
+ vid = memory_add(work, identity=identity, kind="moment", gists={lang: e["text"]}, label=e["text"][:60], date=e["date"],
254
+ where=e["where"] or None, who=who or None, tags=tags, personal=True, origin="lived",
255
+ presets=presets, lang=lang)
256
+ lived.add((e["date"], n)); added.append(vid)
257
+ return added
258
+
259
+
260
+ def _norm(s: str) -> str:
261
+ """Text as compared for the re-import: case, spaces and punctuation set aside."""
262
+ return re.sub(r"[^\w]+", " ", (s or "").lower()).strip()
263
+
264
+
265
+ def _guess_lang(manifest: dict) -> str:
266
+ for v in (manifest.get("elements", {}).get("personality", {}).get("variants") or {}).values():
267
+ if v.get("language"):
268
+ return v["language"]
269
+ return (manifest.get("languages") or ["en"])[0]
@@ -99,6 +99,56 @@ def cmd_unpack(a):
99
99
  return 0
100
100
 
101
101
 
102
+ def cmd_diff(a):
103
+ """What differs between two .cof files (or unpacked folders): members present on one side only, members whose bytes
104
+ differ, and for every JSON member the flattened keys added, removed or changed. Exit 0 when identical, 1 otherwise.
105
+ Made for the builder's round-trip promise of 1.2.2 (« open, edit, build: nothing else moves »)."""
106
+ import io, zipfile
107
+ def members(p):
108
+ p = Path(p)
109
+ if p.is_dir():
110
+ return {str(f.relative_to(p)).replace("\\", "/"): f.read_bytes() for f in sorted(p.rglob("*")) if f.is_file()}
111
+ with zipfile.ZipFile(p) as z:
112
+ return {n: z.read(n) for n in z.namelist() if not n.endswith("/")}
113
+ def flat(o, pre=""):
114
+ if isinstance(o, dict):
115
+ out = {}
116
+ for k, v in o.items(): out.update(flat(v, f"{pre}.{k}" if pre else str(k)))
117
+ return out or {pre: {}}
118
+ if isinstance(o, list):
119
+ out = {}
120
+ ids = [v.get("id") for v in o if isinstance(v, dict)]
121
+ by_id = len(ids) == len(o) and all(isinstance(i, str) and i for i in ids) and len(set(ids)) == len(ids) # a list of records (assets…): matched by id, not by position
122
+ for i, v in enumerate(o): out.update(flat(v, f"{pre}[{v['id']}]" if by_id else f"{pre}[{i}]"))
123
+ return out or {pre: []}
124
+ return {pre: o}
125
+ A, B = members(a.a), members(a.b); same = True
126
+ for n in sorted(set(A) - set(B)): print(f"- only in A: {n}"); same = False
127
+ for n in sorted(set(B) - set(A)): print(f"+ only in B: {n}"); same = False
128
+ for n in sorted(set(A) & set(B)):
129
+ if A[n] == B[n]: continue
130
+ same = False
131
+ if n.endswith(".json"):
132
+ try:
133
+ fa, fb = flat(json.loads(A[n].decode("utf-8"))), flat(json.loads(B[n].decode("utf-8")))
134
+ except Exception:
135
+ print(f"~ {n}: bytes differ"); continue
136
+ keys = sorted(set(fa) | set(fb)); shown = 0
137
+ for k in keys:
138
+ if k in fa and k not in fb: line = f" - {k} = {json.dumps(fa[k], ensure_ascii=False)[:120]}"
139
+ elif k in fb and k not in fa: line = f" + {k} = {json.dumps(fb[k], ensure_ascii=False)[:120]}"
140
+ elif fa[k] != fb[k]: line = f" ~ {k}: {json.dumps(fa[k], ensure_ascii=False)[:60]} → {json.dumps(fb[k], ensure_ascii=False)[:60]}"
141
+ else: continue
142
+ if shown == 0: print(f"~ {n}:")
143
+ if shown < a.limit: print(line)
144
+ shown += 1
145
+ if shown > a.limit: print(f" … {shown - a.limit} more")
146
+ else:
147
+ print(f"~ {n}: bytes differ ({len(A[n])} → {len(B[n])} bytes)")
148
+ print("identical" if same else "different")
149
+ return 0 if same else 1
150
+
151
+
102
152
  def cmd_info(a):
103
153
  m = read_manifest(a.cof)
104
154
  c = m.get("completeness") or compute_completeness(m)
@@ -321,12 +371,27 @@ def cmd_export(a):
321
371
  elif fmt == "agent":
322
372
  from .convert import export_agent
323
373
  out = out or Path(f"{_fname(manifest)}-agent")
324
- done = export_agent(d, out, pid, keep_personal=getattr(a, "keep_personal", False), keep_dangerous=getattr(a, "keep_dangerous", False))
374
+ done = export_agent(d, out, pid, keep_personal=getattr(a, "keep_personal", False), keep_dangerous=getattr(a, "keep_dangerous", False), keep_secrets=getattr(a, "keep_secrets", False))
325
375
  print(f"skills: {', '.join(done['skills']) or '—'} · memory files: {len(done['memories'])} · memories (nodes): {done.get('memory_nodes', 0)} · psyche (nodes): {done.get('psyche_nodes', 0)} · documents: {len(done['documents'])}")
326
376
  if done.get("personal_dropped") or done.get("psyche_personal_dropped"):
327
377
  print(f"personal memories not exported: {done.get('personal_dropped', 0)}, personal psyche nodes: {done.get('psyche_personal_dropped', 0)} (--keep-personal exports them)")
328
378
  if done.get("dangerous_dropped"):
329
379
  print(f"dangerous psyche nodes not exported: {done['dangerous_dropped']} (an agent acts — --keep-dangerous exports them)")
380
+ if done.get("secret_dropped"):
381
+ print(f"{done['secret_dropped']} secret memories left out (use --keep-secrets to include them)")
382
+ elif fmt == "hermes":
383
+ from .agents import export_hermes
384
+ out = out or Path(f"{_fname(manifest)}-hermes")
385
+ done = export_hermes(d, out, pid, keep_personal=getattr(a, "keep_personal", False), keep_dangerous=getattr(a, "keep_dangerous", False), keep_secrets=getattr(a, "keep_secrets", False))
386
+ print(f"Hermes profile: SOUL.md · memories/MEMORY.md {done['hermes_memory_entries']} entries, {done['hermes_memory_chars']} chars"
387
+ + (f" ({done['hermes_memory_dropped']} memories left in the .cof: the host caps MEMORY.md)" if done['hermes_memory_dropped'] else "")
388
+ + f" · skills: {', '.join(done['skills']) or '—'} · psyche (nodes): {done.get('psyche_nodes', 0)}")
389
+ if done.get("personal_dropped") or done.get("psyche_personal_dropped"):
390
+ print(f"personal memories not exported: {done.get('personal_dropped', 0)}, personal psyche nodes: {done.get('psyche_personal_dropped', 0)} (--keep-personal exports them)")
391
+ if done.get("dangerous_dropped"):
392
+ print(f"dangerous psyche nodes not exported: {done['dangerous_dropped']} (an agent acts — --keep-dangerous exports them)")
393
+ if done.get("secret_dropped"):
394
+ print(f"{done['secret_dropped']} secret memories left out (use --keep-secrets to include them)")
330
395
  elif fmt == "card":
331
396
  out = out or Path(f"{_fname(manifest)}.card.json")
332
397
  out.write_text(json.dumps(card, ensure_ascii=False, indent=2), "utf-8")
@@ -403,6 +468,24 @@ def _add_node(a, what: str, add):
403
468
 
404
469
  def cmd_memory_add(a):
405
470
  from .selfdesc import memory_add
471
+ if getattr(a, "from_agent", None):
472
+ if a.gist:
473
+ print("ERROR --from-agent takes its gists from the agent's notes: no --gist", file=sys.stderr); return 2
474
+ from .agents import import_agent_memories
475
+ folder = Path(a.from_agent)
476
+ if not folder.is_dir():
477
+ print(f"ERROR {folder}: not a folder", file=sys.stderr); return 2
478
+ added: list[str] = []
479
+ def add_all(work):
480
+ nonlocal added
481
+ added = import_agent_memories(work, folder, identity=a.identity, presets=a.preset, source=a.agent_source, lang=a.lang)
482
+ return ", ".join(added) if added else "(nothing new)"
483
+ rc = _add_node(a, "Lived memories", add_all)
484
+ if rc == 0:
485
+ print(f"lived memories added: {len(added)} (personal, origin lived, tagged lived:<host>)")
486
+ return rc
487
+ if not a.gist:
488
+ print("ERROR --gist LANG=TEXT is required (or --from-agent <folder>)", file=sys.stderr); return 2
406
489
  gists = _gists(a)
407
490
  if gists is None:
408
491
  return 2
@@ -660,7 +743,10 @@ def main(argv=None) -> int:
660
743
  ms = s.add_subparsers(dest="mcmd", required=True)
661
744
  ma = ms.add_parser("add", help="append one memory node"); ma.add_argument("src", help=".cof file or character folder")
662
745
  ma.add_argument("--identity", help="character id (default: the file's default character)"); ma.add_argument("--kind", choices=["moment", "period"], default="moment")
663
- ma.add_argument("--gist", action="append", required=True, metavar="LANG=TEXT", help="the memory in one paragraph; repeat per language")
746
+ ma.add_argument("--gist", action="append", metavar="LANG=TEXT", help="the memory in one paragraph; repeat per language")
747
+ ma.add_argument("--from-agent", metavar="FOLDER", help="instead of --gist: what an agent lived, read from an OpenClaw workspace (memory/YYYY-MM-DD.md, lines written as AGENTS.md asks) or a Hermes profile (memories/MEMORY.md, § entries); each note becomes a lived, personal memory dated by its file, tagged lived:<host>; already-imported notes are skipped")
748
+ ma.add_argument("--agent-source", choices=["openclaw", "hermes"], help="with --from-agent: read only that host's notes")
749
+ ma.add_argument("--lang", help="with --from-agent: the language the agent wrote in (default: the personality's language)")
664
750
  ma.add_argument("--label"); ma.add_argument("--age", type=float); ma.add_argument("--date", help="YYYY, YYYY-MM or YYYY-MM-DD"); ma.add_argument("--approx", action="store_true")
665
751
  ma.add_argument("--where"); ma.add_argument("--who", action="append", metavar="LABEL[|shown][|AGE][|real]", help="a person: label, then optional words 'shown' (appears in a media), their age, 'real' (a real person who is not a character of the file); repeat");
666
752
  ma.add_argument("--what", action="append", metavar="LABEL[|item=REF][|shown]", help="an object (1.2, RFC 0005): its name and/or item=<category>/<id> (an accessory of the character, e.g. item=appearance/x1), 'shown' if it appears in a media; repeat")
@@ -716,6 +802,8 @@ def main(argv=None) -> int:
716
802
  pt.add_argument("--out-cof", help="output .cof with --into-card (default: in place)"); pt.set_defaults(fn=cmd_psyche_text)
717
803
  s = sub.add_parser("unpack", help=".cof → folder"); s.add_argument("cof"); s.add_argument("-o", "--out"); s.set_defaults(fn=cmd_unpack)
718
804
  s = sub.add_parser("info", help="summary of a .cof"); s.add_argument("cof"); s.set_defaults(fn=cmd_info)
805
+ s = sub.add_parser("diff", help="what differs between two .cof files or folders (members, bytes, JSON keys); exit 1 when different"); s.add_argument("a"); s.add_argument("b")
806
+ s.add_argument("--limit", type=int, default=40, help="lines shown per JSON member"); s.set_defaults(fn=cmd_diff)
719
807
  s = sub.add_parser("tokens", help="token estimate per block"); s.add_argument("path"); s.set_defaults(fn=cmd_tokens)
720
808
  s = sub.add_parser("embed-text", help="write a text (.md/.txt) into a PNG as iTXt 'Description' — readable by the builder (personality + appearance)"); s.add_argument("png"); s.add_argument("text"); s.add_argument("-o", "--out"); s.set_defaults(fn=cmd_embed_text)
721
809
  s = sub.add_parser("read-text", help="show the descriptive text embedded in an image (PNG/JPEG: iTXt, XMP, EXIF)"); s.add_argument("image"); s.set_defaults(fn=cmd_read_text)
@@ -736,7 +824,7 @@ def main(argv=None) -> int:
736
824
  s.add_argument("--inspect", action="store_true", help="print the structure of the files with every value redacted (to share an unknown export's shape), write nothing")
737
825
  s.add_argument("--keep-png", action="store_true", help="plain card import: keep the PNG as the head.front view")
738
826
  s.add_argument("--json", action="store_true"); s.set_defaults(fn=cmd_import)
739
- s = sub.add_parser("export", help="folder/.cof → png | soul | card | agent (workspace: SOUL.md, IDENTITY.md, skills/, memories) — from the default preset or --preset"); s.add_argument("src"); s.add_argument("--format", choices=["png", "soul", "card", "agent"], required=True); s.add_argument("-o", "--out"); s.add_argument("--preset"); s.add_argument("--keep-personal", action="store_true", help="agent: also export `visibility: personal` memories and psyche nodes (dropped by default)"); s.add_argument("--keep-dangerous", action="store_true", help="agent: also render psyche nodes of risk `dangerous` (dropped by default: an agent acts — RFC 0004 § 3 septies)"); s.set_defaults(fn=cmd_export)
827
+ s = sub.add_parser("export", help="folder/.cof → png | soul | card | agent (OpenClaw-style workspace: AGENTS.md, SOUL.md, IDENTITY.md, MEMORY.md, skills/, memories) | hermes (a Hermes Agent profile: SOUL.md, memories/MEMORY.md in § entries, skills/) — from the default preset or --preset"); s.add_argument("src"); s.add_argument("--format", choices=["png", "soul", "card", "agent", "hermes"], required=True); s.add_argument("-o", "--out"); s.add_argument("--preset"); s.add_argument("--keep-personal", action="store_true", help="agent: also export `visibility: personal` memories and psyche nodes (dropped by default)"); s.add_argument("--keep-dangerous", action="store_true", help="agent: also render psyche nodes of risk `dangerous` (dropped by default: an agent acts — RFC 0004 § 3 septies)"); s.add_argument("--keep-secrets", action="store_true", help="agent / hermes: also write memories of `disclosure: secret` (left out by default: an agent talks); AGENTS.md (Hermes: SOUL.md) then says they are never revealed"); s.set_defaults(fn=cmd_export)
740
828
  s = sub.add_parser("migrate", help="folder v0.2 … v0.5 → v1.0; --psyche converts the 1.0 lists (goals, fears, values, behaviours) into psyche nodes (1.2)"); s.add_argument("dir"); s.add_argument("--psyche", action="store_true", help="write psyche nodes from psyche.json goals / fears / values and the card's cof.goals / cof.fears / cof.behavior (the lists stay); idempotent"); s.add_argument("--json", action="store_true"); s.set_defaults(fn=cmd_migrate)
741
829
  s = sub.add_parser("merge", help="merge several .cof files/folders (same name, nickname, fictional status and morphology class ⇒ same identity, otherwise multiple identities)"); s.add_argument("sources", nargs="+"); s.add_argument("-o", "--out", required=True); s.add_argument("--json", action="store_true"); s.set_defaults(fn=cmd_merge)
742
830
  s = sub.add_parser("extract", help="extract a preset, a character (--identity), or the presets carrying one or more tags (intersection), into a lighter COF folder"); s.add_argument("src"); g = s.add_mutually_exclusive_group(required=True); g.add_argument("--preset"); g.add_argument("--identity", help="one character: all its presets, elements, files and rights"); g.add_argument("--tag", action="append", help="repeatable: --tag english --tag age-12"); s.add_argument("-o", "--out", required=True); s.add_argument("--json", action="store_true"); s.add_argument("--all-audiences", "--no-intimate", dest="no_intimate", action="store_true", help="all-audiences slice: drop intimate / nude variants and the media of explicit memories (gist kept), allowSexualUsage = false"); s.add_argument("--keep-personal", action="store_true", help="keep `visibility: personal` memories and psyche nodes (a user's data; dropped by default)"); s.add_argument("--no-risk", action="store_true", help="risk purge (RFC 0004 § 3 septies): drop psyche nodes of risk `inappropriate` and `dangerous` (and the contradictions that lose a side); separate from --all-audiences"); s.set_defaults(fn=cmd_extract)
@@ -1,10 +1,10 @@
1
- """Completeness KPI (v0.5) — per preset, from categories/kinds. Derived assets never count."""
1
+ """Completeness KPI (v0.6) — per preset, from categories/kinds. Derived assets never count."""
2
2
  from __future__ import annotations
3
3
 
4
4
  import json
5
5
  from pathlib import Path
6
6
 
7
- from .model import asset_index, by_kind, default_preset_id, first, preset_identity, preset_ids, resolved
7
+ from .model import asset_index, by_kind, default_preset_id, first, preset_identity, preset_ids, resolve_preset_slots, resolved
8
8
 
9
9
  WEIGHTS = {"identity": 0.10, "personality": 0.20, "appearance": 0.20, "physique": 0.05,
10
10
  "voice": 0.15, "volume": 0.10, "motion": 0.05, "rights": 0.15}
@@ -46,7 +46,11 @@ def compute_preset(manifest: dict, pid: str | None, src: Path | None = None) ->
46
46
  elif p and p.get("kind") == "description":
47
47
  n = len(p.get("text") or "")
48
48
  s += 35 + 15 * (n >= 400) + 10 * (n >= 1500) # a rich free-text sheet is usable for chat (≥ 50)
49
- s += 15 * bool(p and p.get("psyche"))
49
+ # psyche 15: the 1.0 sheet (psyche.json) of the personality variant, or — COF 1.2, RFC 0004, where the 1.0 lists are deprecated
50
+ # in favour of nodes — at least one psyche node held by the preset (slots.psyche through extends); not cumulative
51
+ held = set(resolve_preset_slots(m, pid).get("psyche") or []) if pid else set()
52
+ nodes = (((m.get("elements") or {}).get("psyche") or {}).get("variants") or {})
53
+ s += 15 * bool((p and p.get("psyche")) or any(v in nodes for v in held))
50
54
  L["personality"] = min(100, s)
51
55
 
52
56
  f = first(r, "appearance", "face"); fi = imgs(f)
@@ -254,6 +254,8 @@ def card_to_cof_dir(card: dict, dest: Path, *, png: bytes | None = None, age: in
254
254
 
255
255
  v3 = {**card, "spec": "chara_card_v3", "spec_version": "3.0"}
256
256
  v3.setdefault("data", {}).setdefault("extensions", {})
257
+ g = v3["data"].get("group_only_greetings") # a V2 card relabelled V3: the one V3 field the spec says MUST be present (SPEC_V3 § group_only_greetings)
258
+ v3["data"]["group_only_greetings"] = [x for x in g if isinstance(x, str)] if isinstance(g, list) else []
257
259
  (pdir / "card.json").write_text(json.dumps(v3, ensure_ascii=False, indent=2) + "\n", "utf-8")
258
260
 
259
261
  elements = {"personality": {"variants": {"p1": {"kind": "card", "label": data.get("name") or "Personality", "language": language, "card": "elements/personality/p1/card.json"}}}}
@@ -398,9 +400,11 @@ def memory_objects(manifest: dict, node: dict, lang: str) -> list[str]:
398
400
  return out
399
401
 
400
402
 
401
- def memory_section(src: Path, manifest: dict, pid: str | None, keep_personal: bool = False) -> tuple[str, list[tuple[str, dict, dict]], int]:
403
+ def memory_section(src: Path, manifest: dict, pid: str | None, keep_personal: bool = False, keep_secrets: bool = False, stats: dict | None = None) -> tuple[str, list[tuple[str, dict, dict]], int]:
402
404
  """The "Memories" section of MEMORY.md (RFC 0002 § 6.4): canon gists in timeline order, each with its
403
- when-marker, disclosure and fidelity. Returns (markdown, [(vid, variant, node)] exported, personal nodes dropped)."""
405
+ when-marker, disclosure and fidelity. Returns (markdown, [(vid, variant, node)] exported, personal nodes dropped).
406
+ `disclosure: secret` nodes stay behind unless `keep_secrets` (hunt 1.2.2 CLI-02, decided B): an agent talks;
407
+ their count goes to `stats["secret_dropped"]` when a dict is given."""
404
408
  from .memories import gist_text, load_nodes, preset_memories, text_in, timeline, when_label
405
409
  from .model import resolve_variant
406
410
  from .model import variant_owner
@@ -409,12 +413,17 @@ def memory_section(src: Path, manifest: dict, pid: str | None, keep_personal: bo
409
413
  if not vids:
410
414
  return "", [], 0
411
415
  dropped = 0
416
+ secret_dropped = 0
412
417
  kept = []
413
418
  for vid in timeline(manifest, nodes, vids):
414
419
  node = nodes[vid]
415
420
  if node.get("visibility") == "personal" and not keep_personal:
416
421
  dropped += 1; continue
422
+ if node.get("disclosure") == "secret" and not keep_secrets:
423
+ secret_dropped += 1; continue # a secret never leaves with an agent that talks, unless asked (CLI-02)
417
424
  kept.append((vid, resolve_variant(manifest, "memories", vid) or {}, node))
425
+ if stats is not None:
426
+ stats["secret_dropped"] = secret_dropped
418
427
  if not kept:
419
428
  return "", [], dropped
420
429
  lines = ["## Memories", "",
@@ -463,13 +472,14 @@ def memory_section(src: Path, manifest: dict, pid: str | None, keep_personal: bo
463
472
  return "\n".join(lines).rstrip() + "\n", kept, dropped
464
473
 
465
474
 
466
- def export_agent(src: Path, out: Path, preset: str | None = None, keep_personal: bool = False, keep_dangerous: bool = False) -> dict:
475
+ def export_agent(src: Path, out: Path, preset: str | None = None, keep_personal: bool = False, keep_dangerous: bool = False, keep_secrets: bool = False) -> dict:
467
476
  """A ready-to-use agent workspace from one preset: SOUL.md, IDENTITY.md, avatar, skills/<name>/,
468
477
  memories at the root, documents in docs/, and COF.md (rights and provenance the agent host must honour).
469
478
  With a `memories` category (1.1): MEMORY.md = the host memory file (files/memory) followed by the canon gists in
470
479
  timeline order, and memories/<id>/ holding the media of non-explicit nodes (RFC 0002 § 6.4).
471
480
  With a `psyche` category (1.2): SOUL.md gains "Who she is" from the preset's nodes; personal nodes stay behind unless
472
- `keep_personal`, `dangerous` nodes unless `keep_dangerous` — an agent acts (RFC 0004 § 3 septies)."""
481
+ `keep_personal`, `dangerous` nodes unless `keep_dangerous` — an agent acts (RFC 0004 § 3 septies).
482
+ Memories of `disclosure: secret` are not written unless `keep_secrets`; with it, AGENTS.md says they are never told."""
473
483
  import shutil
474
484
  from .model import asset_index, default_preset_id, effective_permissions, preset_identity, resolved
475
485
  manifest = json.loads((src / "manifest.json").read_text("utf-8"))
@@ -508,8 +518,11 @@ def export_agent(src: Path, out: Path, preset: str | None = None, keep_personal:
508
518
  dest.mkdir(parents=True, exist_ok=True); shutil.copy(src / safe_rel(a["path"]), dest / Path(a["path"]).name)
509
519
  done["memories" if kind == "memory" else "documents"].append(Path(a["path"]).name)
510
520
  # memories category (1.1): MEMORY.md = host memory file (if any) + the canon gists; media of non-explicit nodes
511
- section, kept, dropped = memory_section(src, manifest, pid, keep_personal)
521
+ mst: dict = {}
522
+ section, kept, dropped = memory_section(src, manifest, pid, keep_personal, keep_secrets, mst)
512
523
  done["memory_nodes"], done["personal_dropped"] = len(kept), dropped
524
+ done["secret_dropped"] = mst.get("secret_dropped", 0)
525
+ done["secret_kept"] = sum(1 for _, _, n in kept if n.get("disclosure") == "secret")
513
526
  from .psyche import load_nodes as load_psyche, select_nodes
514
527
  psy_kept, pst = select_nodes(manifest, load_psyche(src, manifest), pid, keep_personal, keep_dangerous)
515
528
  done["psyche_nodes"] = len(psy_kept); done["psyche_personal_dropped"] = pst["personal_dropped"]; done["dangerous_dropped"] = pst["dangerous_dropped"]
@@ -550,4 +563,14 @@ def export_agent(src: Path, out: Path, preset: str | None = None, keep_personal:
550
563
  if manifest.get("container", {}).get("executableContent") == "scripts":
551
564
  note += ["", "Skills may contain scripts: never run them without the user's explicit approval."]
552
565
  (out / "COF.md").write_text("\n".join(note) + "\n", "utf-8")
566
+ if not (out / "AGENTS.md").is_file(): # OpenClaw reads AGENTS.md every session: without it the agent has no instruction to write memory (8 Nov. 2026)
567
+ from .agents import agents_md
568
+ (out / "AGENTS.md").write_text(agents_md(ident.get("name") or manifest.get("name") or "the character", gender=ident.get("gender")), "utf-8")
569
+ done["agents_md"] = True
570
+ if keep_secrets and done["secret_kept"]:
571
+ from .agents import SECRETS_LINE
572
+ am = out / "AGENTS.md"
573
+ txt = am.read_text("utf-8") if am.is_file() else ""
574
+ if SECRETS_LINE not in txt:
575
+ am.write_text(txt.rstrip("\n") + "\n\n" + SECRETS_LINE + "\n", "utf-8")
553
576
  return done
@@ -167,6 +167,7 @@ def soul_section(manifest: dict, nodes: dict[str, dict], pid: str | None, keep_p
167
167
  if not keep_personal:
168
168
  hidden = {f"psyche/{v}" for v, n in nodes.items() if n.get("visibility") == "personal"}
169
169
  hidden |= {f"memories/{v}" for v, n in (memory_nodes or {}).items() if n.get("visibility") == "personal"}
170
+ hidden |= {f"memories/{v}" for v, n in (memory_nodes or {}).items() if n.get("disclosure") == "secret"} # a stance never names a secret memory (hunt 1.2.2 CLI-02)
170
171
  if not vids:
171
172
  return "", stats
172
173
  me = preset_owner(manifest, pid) # the section's language: the preset's personality, else the character's, else the file's first
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cof-cli
3
- Version: 1.2.1
3
+ Version: 1.2.2
4
4
  Summary: COF — Character Open File: validate, pack, unpack and convert .cof character containers
5
5
  Author: Yann Souetre
6
6
  License-Expression: MIT
@@ -32,6 +32,7 @@ cof extract clara.cof --preset default --no-risk -o clara-sans-risque/ #
32
32
  cof merge clara.cof martien.cof -o duo/ # un casting : même nom + surnom + statut fictif + morphologie ⇒ même personnage, sinon plusieurs
33
33
  cof memory add clara.cof --gist fr="Ce matin, relu avec Léo." --gist en="This morning, reread with Léo." --date 2026-10-25 --who "Léo" --what "le carnet" --what "item=appearance/x1" --tag travail --personal # --what : un objet (1.2, RFC 0005), un nom et/ou item=<élément>, |shown s'il est dans un média
34
34
  cof memory add clara/ --kind period --gist en="The agency years." --age 24 --approx --fidelity faded # sur un dossier ; `--help` liste tout (--where, --self-shown, --media, --preset…)
35
+ cof memory add clara.cof --from-agent ./agent/ # le retour : les notes du jour d'un espace OpenClaw (memory/AAAA-MM-JJ.md) ou les entrées § d'un profil Hermes (memories/MEMORY.md) deviennent des souvenirs vécus, personnels, datés, étiquetés lived:<hôte> ; idempotent (--agent-source, --lang)
35
36
  cof psyche add clara.cof --kind stance --gist fr="Envers l'utilisateur : une collègue." --about user --strength 60 --stability shifting --link because=memories/ev3 --since-date 2026-10-25 # nœud vécu, `visibility: personal` (--canon sinon), première révision ; `--help` liste tout (--lie, --risk, --tag, --preset…)
36
37
  cof psyche add clara.cof --kind habit --gist fr="Garde la guitare près du bureau." --who "ma grand-mère" --where "environment=appearance/e1" --what "ma guitare|item=appearance/x1" --canon # personnes, lieux, objets du nœud (RFC 0005) ; une personne du casting : --who identity=<id> (les liens --link ne visent que souvenirs et nœuds)
37
38
  cof psyche add clara.cof --kind stance --gist fr="Envers l'utilisateur : de la chaleur." --about user --valence 60 --aware partly --canon # RFC 0004 § 3 nonies : --valence −100…+100 (position ou goût seulement), --aware yes|partly|no, --until-age / --until-date (quand le nœud a cessé d'être tenu)
@@ -43,7 +44,9 @@ cof import carte.png -o perso/ --age 30 --lang fr --keep-png # carte PNG CCv2/
43
44
  cof export clara.cof --format png -o clara.png # → PNG avec chunks chara + ccv3
44
45
  cof export clara.cof --format card -o clara.card.json
45
46
  cof export clara.cof --format soul -o ./agent/ # → SOUL.md + IDENTITY.md
46
- cof export clara.cof --format agent -o ./agent/ # → espace de travail d'agent : SOUL.md (avec « Qui elle est » rendu depuis la psyché), IDENTITY.md, skills/, MEMORY.md + memories/ (--keep-personal, --keep-dangerous, --preset)
47
+ cof diff clara.cof rebuilt.cof # ce qui diffère entre deux .cof : membres, octets, clés JSON (code de sortie 1 si différent) — l'outil de la promesse « rien d'autre ne bouge » du builder
48
+ cof export clara.cof --format agent -o ./agent/ # → espace de travail d'agent : SOUL.md (avec « Qui elle est » rendu depuis la psyché), IDENTITY.md, AGENTS.md (consignes de mémoire pour l'hôte), skills/, MEMORY.md, COF.md (--keep-personal, --keep-dangerous, --keep-secrets, --preset) ; les souvenirs `disclosure: secret` restent dans le .cof sauf --keep-secrets (« N secret memories left out »), qui les écrit marqués `secret` et ajoute à AGENTS.md une ligne : ce sont des secrets que le personnage ne révèle jamais
49
+ cof export clara.cof --format hermes -o ./hermes/ # → profil Hermes Agent (HERMES_HOME) : SOUL.md (identité fusionnée), memories/MEMORY.md en entrées § sous le plafond de l'hôte (2 200 caractères, les plus saillants), skills/, COF.md ; mêmes options, secrets laissés de côté par défaut (avec --keep-secrets : entrées préfixées « (secret) », la ligne dans SOUL.md)
47
50
  cof embed-text clara.png fiche.md -o clara-fiche.png # texte descriptif dans un PNG (iTXt), lisible par le builder
48
51
  cof read-text clara-fiche.png
49
52
  cof migrate dossier-v0.5/ # v0.2 … v0.5 → 1.0
@@ -1,6 +1,7 @@
1
1
  README.md
2
2
  pyproject.toml
3
3
  cof_cli/__init__.py
4
+ cof_cli/agents.py
4
5
  cof_cli/cast.py
5
6
  cof_cli/cli.py
6
7
  cof_cli/completeness.py
@@ -39,6 +40,7 @@ cof_cli/schemas/skeleton.schema.json
39
40
  cof_cli/schemas/visemes.schema.json
40
41
  cof_cli/schemas/voice-profile.schema.json
41
42
  cof_cli/schemas/weights.schema.json
43
+ tests/test_agents.py
42
44
  tests/test_hunt.py
43
45
  tests/test_platform_import.py
44
46
  tests/test_roundtrip.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cof-cli"
7
- version = "1.2.1"
7
+ version = "1.2.2"
8
8
  description = "COF — Character Open File: validate, pack, unpack and convert .cof character containers"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -0,0 +1,155 @@
1
+ """Agent hosts (8 Nov. 2026): AGENTS.md in the agent export, the Hermes profile, and the way back (--from-agent)."""
2
+ import json
3
+ import shutil
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from cof_cli.agents import HERMES_DELIM, HERMES_MEMORY_CHARS, export_hermes, hermes_memory, import_agent_memories, parse_agent_dir
9
+ from cof_cli.convert import export_agent
10
+
11
+ ROOT = Path(__file__).resolve().parents[2]
12
+ CLARA = ROOT / "spec" / "examples" / "10-clara-mercier"
13
+
14
+
15
+ def test_agent_export_writes_agents_md(tmp_path):
16
+ done = export_agent(CLARA, tmp_path / "ws")
17
+ txt = (tmp_path / "ws" / "AGENTS.md").read_text("utf-8")
18
+ assert done["agents_md"] and "memory/YYYY-MM-DD.md" in txt and "HH:MM ·" in txt and "COF.md" in txt
19
+
20
+
21
+ def test_hermes_profile_fits_the_host(tmp_path):
22
+ done = export_hermes(CLARA, tmp_path / "h")
23
+ mem = (tmp_path / "h" / "memories" / "MEMORY.md").read_text("utf-8")
24
+ assert len(mem) <= HERMES_MEMORY_CHARS and HERMES_DELIM in mem and done["hermes_memory_entries"] == 5
25
+ soul = (tmp_path / "h" / "SOUL.md").read_text("utf-8")
26
+ assert "## Identity" in soul and "- Name: Clara Mercier" in soul and "Avatar" not in soul.split("## Identity")[1].split("##")[0]
27
+ assert (tmp_path / "h" / "README-COF.md").is_file() and (tmp_path / "h" / "COF.md").is_file()
28
+
29
+
30
+ def test_hermes_memory_keeps_the_most_salient_within_the_limit():
31
+ entries = [(10, "a" * 1000), (90, "b" * 1000), (50, "c" * 1000)]
32
+ text, dropped = hermes_memory(entries, limit=2100)
33
+ assert dropped == 1 and text.startswith("b" * 1000) and text.endswith("c" * 1000) and "a" * 10 not in text
34
+
35
+
36
+ def test_parse_openclaw_notes_and_hermes_entries(tmp_path):
37
+ (tmp_path / "memory").mkdir()
38
+ (tmp_path / "memory" / "2026-11-08.md").write_text("# day\n\n- 09:12 · Saw the Alps from the train. · with: the user, Léo · where: a train · tags: alps, travel\n- plain note without time\n", "utf-8")
39
+ (tmp_path / "memories").mkdir()
40
+ (tmp_path / "memories" / "MEMORY.md").write_text("User prefers French.\n§\nWe planned a review.\n", "utf-8")
41
+ E = parse_agent_dir(tmp_path)
42
+ assert [e["source"] for e in E] == ["openclaw", "openclaw", "hermes", "hermes"]
43
+ assert E[0] == {"text": "Saw the Alps from the train.", "with": ["the user", "Léo"], "where": "a train", "tags": ["alps", "travel"],
44
+ "source": "openclaw", "file": "memory/2026-11-08.md", "date": "2026-11-08", "time": "09:12"}
45
+ assert E[1]["text"] == "plain note without time" and E[1]["time"] == ""
46
+
47
+
48
+ def test_from_agent_adds_lived_personal_memories_once(tmp_path):
49
+ work = tmp_path / "clara"
50
+ shutil.copytree(CLARA, work)
51
+ ws = tmp_path / "ws"
52
+ (ws / "memory").mkdir(parents=True)
53
+ (ws / "memory" / "2026-11-08.md").write_text("- 09:12 · Saw the Alps from the train. · tags: alps\n", "utf-8")
54
+ added = import_agent_memories(work, ws, lang="en")
55
+ assert len(added) == 1
56
+ assert import_agent_memories(work, ws, lang="en") == [] # idempotent
57
+ m = json.loads((work / "manifest.json").read_text("utf-8"))
58
+ node = json.loads((work / m["elements"]["memories"]["variants"][added[0]]["memory"]).read_text("utf-8"))
59
+ assert node["origin"] == "lived" and node["visibility"] == "personal" and node["when"] == {"date": "2026-11-08"}
60
+ assert node["tags"] == ["lived:openclaw", "alps"] and node["gist"] == {"en": "Saw the Alps from the train."}
61
+ r = subprocess.run([sys.executable, "-m", "cof_cli.cli", "validate", str(work)], capture_output=True, text=True, cwd=ROOT / "cli")
62
+ assert r.returncode == 0, r.stdout[-800:]
63
+
64
+
65
+ def test_hermes_loop_does_not_duplicate_what_the_host_got_from_the_file(tmp_path):
66
+ """Hunt 1.2.2, CLI-01: a Hermes MEMORY.md repeats the export; re-importing it must add nothing. CLI-04: the same fact on two
67
+ days is two memories. CLI-07: a lived memory's Hermes entry says its when, not its text twice."""
68
+ work = tmp_path / "clara"
69
+ shutil.copytree(CLARA, work)
70
+ ws = tmp_path / "ws"
71
+ (ws / "memory").mkdir(parents=True)
72
+ (ws / "memory" / "2026-11-08.md").write_text("- 09:12 · Fed the cat. · tags: cat\n", "utf-8")
73
+ (ws / "memory" / "2026-11-09.md").write_text("- 09:12 · Fed the cat. · tags: cat\n", "utf-8")
74
+ (ws / "memory" / "2026-13-45.md").write_text("- 09:12 · Not a day. · tags: x\n", "utf-8") # CLI-05: skipped, not fatal
75
+ added = import_agent_memories(work, ws, lang="en")
76
+ assert len(added) == 2 # one per day, the bad file ignored
77
+ export_hermes(work, tmp_path / "h", keep_personal=True)
78
+ mem = (tmp_path / "h" / "memories" / "MEMORY.md").read_text("utf-8")
79
+ assert "2026-11-08: Fed the cat." in mem and "Fed the cat. (2026-11-08): Fed the cat." not in mem
80
+ assert import_agent_memories(work, tmp_path / "h", lang="en") == [] # the export, read back: nothing new
81
+
82
+
83
+ def test_agents_md_follows_the_character_gender(tmp_path):
84
+ from cof_cli.agents import agents_md
85
+ assert "he presents" in agents_md("Ulrich", gender="male") and "his author" in agents_md("Ulrich", gender="male")
86
+ assert "they present," in agents_md("Zed") and "she presents" in agents_md("Clara", gender="female")
87
+
88
+
89
+ def test_group_only_greetings_is_normalised_to_a_list_of_strings(tmp_path):
90
+ from cof_cli.convert import card_to_cof_dir
91
+ card = {"spec": "chara_card_v3", "spec_version": "3.0", "data": {"name": "N", "description": "d", "personality": "p", "scenario": "s",
92
+ "first_mes": "hi", "mes_example": "", "group_only_greetings": ["ok", 3, None]}}
93
+ card_to_cof_dir(card, tmp_path / "c", age=30)
94
+ import glob
95
+ v3 = json.loads(open(glob.glob(str(tmp_path / "c" / "elements" / "personality" / "*" / "card.json"))[0], encoding="utf-8").read())
96
+ assert v3["data"]["group_only_greetings"] == ["ok"]
97
+
98
+
99
+ def test_from_agent_never_declares_shown_real_or_age_people(tmp_path):
100
+ """Hunt 1.2.2, SAFETY-04: a day note's `with:` names went through the --who pipe syntax (label|shown|34|real)."""
101
+ work = tmp_path / "clara"
102
+ shutil.copytree(CLARA, work)
103
+ ws = tmp_path / "ws"
104
+ (ws / "memory").mkdir(parents=True)
105
+ (ws / "memory" / "2026-11-10.md").write_text("- 10:00 · Coffee with a friend. · with: Sam|shown|9|real, Lou | oops\n", "utf-8")
106
+ added = import_agent_memories(work, ws, lang="en")
107
+ m = json.loads((work / "manifest.json").read_text("utf-8"))
108
+ node = json.loads((work / m["elements"]["memories"]["variants"][added[0]]["memory"]).read_text("utf-8"))
109
+ assert [w.get("label", {}).get("en") for w in node["who"]] == ["Sam/shown/9/real", "Lou / oops"]
110
+ assert all("shown" not in w and "real" not in w and "age" not in w for w in node["who"])
111
+
112
+
113
+ def _clara_with_a_secret(tmp_path):
114
+ work = tmp_path / "clara"
115
+ shutil.copytree(CLARA, work)
116
+ r = subprocess.run([sys.executable, "-m", "cof_cli.cli", "memory", "add", str(work), "--gist", "en=I burned the letter from my brother before anyone read it.",
117
+ "--label", "The burned letter", "--date", "2015", "--disclosure", "secret", "--origin", "authored", "--salience", "90"],
118
+ capture_output=True, text=True, cwd=ROOT / "cli")
119
+ assert r.returncode == 0, r.stdout + r.stderr
120
+ return work
121
+
122
+
123
+ def test_agent_export_leaves_secret_memories_out_unless_asked(tmp_path):
124
+ """Hunt 1.2.2, CLI-02 decided B (11 Nov. 2026): a secret memory is not written to an agent workspace by default;
125
+ --keep-secrets writes it and AGENTS.md says it is never revealed; the CLI says how many were left out."""
126
+ from cof_cli.agents import SECRETS_LINE
127
+ work = _clara_with_a_secret(tmp_path)
128
+ done = export_agent(work, tmp_path / "ws")
129
+ assert done["secret_dropped"] == 1 and done["secret_kept"] == 0
130
+ assert "burned the letter" not in (tmp_path / "ws" / "MEMORY.md").read_text("utf-8")
131
+ assert SECRETS_LINE not in (tmp_path / "ws" / "AGENTS.md").read_text("utf-8")
132
+ done = export_agent(work, tmp_path / "ws2", keep_secrets=True)
133
+ assert done["secret_dropped"] == 0 and done["secret_kept"] == 1
134
+ mem = (tmp_path / "ws2" / "MEMORY.md").read_text("utf-8")
135
+ assert "burned the letter" in mem and "The burned letter · 2015 · secret" in mem
136
+ assert (tmp_path / "ws2" / "AGENTS.md").read_text("utf-8").count(SECRETS_LINE) == 1
137
+ r = subprocess.run([sys.executable, "-m", "cof_cli.cli", "export", str(work), "--format", "agent", "-o", str(tmp_path / "ws3")], capture_output=True, text=True, cwd=ROOT / "cli")
138
+ assert r.returncode == 0 and "1 secret memories left out (use --keep-secrets to include them)" in r.stdout, r.stdout + r.stderr
139
+ r = subprocess.run([sys.executable, "-m", "cof_cli.cli", "export", str(work), "--format", "agent", "--keep-secrets", "-o", str(tmp_path / "ws4")], capture_output=True, text=True, cwd=ROOT / "cli")
140
+ assert r.returncode == 0 and "secret memories left out" not in r.stdout and "burned the letter" in (tmp_path / "ws4" / "MEMORY.md").read_text("utf-8")
141
+
142
+
143
+ def test_hermes_export_secrets_unchanged_by_default_and_kept_on_request(tmp_path):
144
+ from cof_cli.agents import SECRETS_LINE
145
+ work = _clara_with_a_secret(tmp_path)
146
+ base = export_hermes(CLARA, tmp_path / "h0")
147
+ done = export_hermes(work, tmp_path / "h")
148
+ assert done["hermes_memory_entries"] == base["hermes_memory_entries"] and done["secret_dropped"] == 1
149
+ assert (tmp_path / "h" / "memories" / "MEMORY.md").read_text("utf-8") == (tmp_path / "h0" / "memories" / "MEMORY.md").read_text("utf-8")
150
+ assert SECRETS_LINE.split(" (in")[0] not in (tmp_path / "h" / "SOUL.md").read_text("utf-8")
151
+ export_hermes(work, tmp_path / "h2", keep_secrets=True)
152
+ assert "(secret) The burned letter (2015): I burned the letter" in (tmp_path / "h2" / "memories" / "MEMORY.md").read_text("utf-8")
153
+ assert "(in `memories/MEMORY.md`) are secrets the character never reveals" in (tmp_path / "h2" / "SOUL.md").read_text("utf-8")
154
+ r = subprocess.run([sys.executable, "-m", "cof_cli.cli", "export", str(work), "--format", "hermes", "-o", str(tmp_path / "h3")], capture_output=True, text=True, cwd=ROOT / "cli")
155
+ assert r.returncode == 0 and "1 secret memories left out (use --keep-secrets to include them)" in r.stdout, r.stdout + r.stderr
@@ -2544,3 +2544,45 @@ def test_extract_recomputes_auto_tags(tmp_path):
2544
2544
  hab1 = m["elements"]["psyche"]["variants"]["hab1"]
2545
2545
  assert "a-mem-ev1-1" not in (hab1.get("media") or []) and not any(a["id"] == "a-mem-ev1-1" for a in m["assets"])
2546
2546
  assert "ERROR" not in r.stdout, r.stdout
2547
+
2548
+
2549
+ def test_import_of_a_v2_card_writes_a_complete_v3(tmp_path):
2550
+ """A V2 card imported as V3 carries `group_only_greetings`, which SPEC_V3 says MUST be present (8 Nov. 2026)."""
2551
+ card = {"spec": "chara_card_v2", "spec_version": "2.0", "data": {"name": "Zoé", "description": "a test", "personality": "", "scenario": "",
2552
+ "first_mes": "", "mes_example": "", "creator_notes": "", "system_prompt": "", "post_history_instructions": "",
2553
+ "alternate_greetings": [], "tags": [], "creator": "", "character_version": "1.0"}}
2554
+ d = card_to_cof_dir(card, tmp_path / "imp", png=None, age=30, language="fr")
2555
+ out = json.loads((d / "elements" / "personality" / "p1" / "card.json").read_text("utf-8"))
2556
+ assert out["spec"] == "chara_card_v3" and out["data"]["group_only_greetings"] == []
2557
+
2558
+
2559
+ def test_diff_tells_identical_from_different(tmp_path):
2560
+ """`cof diff` (1.2.2): the tool of the round-trip promise — exit 0 and « identical » for the same file, exit 1 with the
2561
+ flattened JSON keys that changed otherwise."""
2562
+ import shutil, subprocess, sys
2563
+ from pathlib import Path
2564
+ root = Path(__file__).resolve().parents[2]; sample = root / "viewer" / "samples" / "clara-mercier.cof"
2565
+ r = subprocess.run([sys.executable, "-m", "cof_cli.cli", "diff", str(sample), str(sample)], capture_output=True, text=True, cwd=root / "cli")
2566
+ assert r.returncode == 0 and r.stdout.strip().endswith("identical")
2567
+ import zipfile, json
2568
+ b = tmp_path / "b.cof"
2569
+ with zipfile.ZipFile(sample) as zi, zipfile.ZipFile(b, "w", zipfile.ZIP_DEFLATED) as zo:
2570
+ for n in zi.namelist():
2571
+ data = zi.read(n)
2572
+ if n == "manifest.json":
2573
+ m = json.loads(data); m["x-hunt"] = 1; m["name"] = "Someone"; data = json.dumps(m).encode()
2574
+ if n.endswith("COF.md"): continue
2575
+ zo.writestr(n, data)
2576
+ r = subprocess.run([sys.executable, "-m", "cof_cli.cli", "diff", str(sample), str(b)], capture_output=True, text=True, cwd=root / "cli")
2577
+ assert r.returncode == 1 and "only in A: COF.md" in r.stdout and "+ x-hunt = 1" in r.stdout and "~ name:" in r.stdout
2578
+ # records with ids (assets) are matched by id: a reordered asset list is no difference, a changed asset is named by its id
2579
+ c = tmp_path / "c.cof"
2580
+ with zipfile.ZipFile(sample) as zi, zipfile.ZipFile(c, "w", zipfile.ZIP_DEFLATED) as zo:
2581
+ for n in zi.namelist():
2582
+ data = zi.read(n)
2583
+ if n == "manifest.json":
2584
+ m = json.loads(data); m["assets"] = list(reversed(m["assets"])); m["assets"][0]["x-seen"] = True; data = json.dumps(m).encode()
2585
+ zo.writestr(n, data)
2586
+ r = subprocess.run([sys.executable, "-m", "cof_cli.cli", "diff", str(sample), str(c)], capture_output=True, text=True, cwd=root / "cli")
2587
+ lines = [l for l in r.stdout.splitlines() if l.strip().startswith(("+", "-", "~")) and "manifest" not in l]
2588
+ assert r.returncode == 1 and len(lines) == 1 and lines[0].strip().startswith("+ assets[") and lines[0].strip().endswith("].x-seen = true") and "[0]" not in lines[0]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes