From 000244a8060f4f798199514278fe31e7af5828db Mon Sep 17 00:00:00 2001 From: FullChico <62688167+fullchico@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:01:31 -0300 Subject: [PATCH] =?UTF-8?q?release:=204.3.0=20(tr=202.8.0,=20memory=200.3.?= =?UTF-8?q?0)=20=E2=80=94=20memory=20tied=20to=20the=20process,=20dream=20?= =?UTF-8?q?reads=20whole=20sessions=20and=20subagents,=20competing=20spec?= =?UTF-8?q?=20flows,=20installer=20checks=20the=20marketplace=20source?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/harness.js | 30 ++++---- package-lock.json | 4 +- package.json | 2 +- plugins/memory/.claude-plugin/plugin.json | 2 +- plugins/memory/.codex-plugin/plugin.json | 2 +- plugins/memory/scripts/codex_learn.py | 5 +- plugins/memory/scripts/learn.py | 93 +++++++++++++++++------ plugins/memory/scripts/memory.py | 3 +- plugins/tr/.claude-plugin/plugin.json | 2 +- plugins/tr/.codex-plugin/plugin.json | 2 +- plugins/tr/skills/configure/SKILL.md | 11 +++ plugins/tr/skills/memory-dream/SKILL.md | 23 ++++-- plugins/tr/skills/process-plan/SKILL.md | 13 +++- tests/test_install.py | 19 ++++- tests/test_plugin_memory.py | 34 ++++++++- 15 files changed, 189 insertions(+), 56 deletions(-) diff --git a/bin/harness.js b/bin/harness.js index 7ffd5a7..2154435 100755 --- a/bin/harness.js +++ b/bin/harness.js @@ -274,20 +274,22 @@ function addPlugins(names, project, extras = []) { if ((["install", "update"].includes(args[1]) || (args[1] === "marketplace" && args[2] === "update")) && run.status !== 0) status = run.status === null ? 1 : run.status; } - // O carimbo fica fora do projeto, onde o sandbox impede o agente de gravar. Sem sandbox, o agente - // consegue gravar lá: o portão continua avisando, mas deixa de ser barreira. - let sandboxed = false; - for (const file of ["settings.json", "settings.local.json"]) { - try { - const data = JSON.parse(fs.readFileSync(path.join(project, ".claude", file), "utf8")); - if (data.sandbox && data.sandbox.enabled === true) sandboxed = true; - } catch (e) { /* arquivo ausente ou inválido: segue */ } - } - if (!sandboxed) { - console.log("\nAviso: este projeto não liga o sandbox do Claude Code (`sandbox.enabled` em .claude/settings.json).\n" + - "Sem ele, o agente consegue gravar no estado dos carimbos e, em tese, forjar um carimbo: o portão avisa,\n" + - "mas deixa de ser barreira. Para ligar: https://code.claude.com/docs/en/sandboxing"); - } + // Um marketplace `fullchico` já registrado com outra fonte (uma pasta de teste, um fork) faz o `add` + // passar em silêncio e o install trazer o plugin de lá. Confere a fonte e para com o conserto. + const expected = LOCAL_SOURCE || "FullChico/fullchico-harness"; + try { + const known = JSON.parse(fs.readFileSync(path.join(require("os").homedir(), ".claude/plugins/known_marketplaces.json"), "utf8")); + const src = (known.fullchico || {}).source || {}; + const actual = src.repo || src.path || src.url || ""; + if (actual && path.resolve(actual) !== path.resolve(expected) && actual.toLowerCase() !== expected.toLowerCase()) { + console.log(`\nO marketplace \`fullchico\` desta máquina aponta para ${actual}, não para ${expected}:` + + "\nos plugins vieram de lá. Para trocar, rode no terminal, um por vez:" + + "\n claude plugin marketplace remove fullchico" + + `\n claude plugin marketplace add ${expected}` + + "\ne depois rode esta instalação de novo."); + status = status || 1; + } + } catch (e) { /* sem registro legível: o `claude` já disse o que houve */ } return status; } diff --git a/package-lock.json b/package-lock.json index 607c303..025af2e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@fullchico/harness", - "version": "4.2.0", + "version": "4.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@fullchico/harness", - "version": "4.2.0", + "version": "4.3.0", "license": "MIT", "dependencies": { "@clack/prompts": "1.8.1" diff --git a/package.json b/package.json index 9d52a7e..b7f97e9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@fullchico/harness", - "version": "4.2.0", + "version": "4.3.0", "description": "Per-project harness plugin for Claude Code and Codex: orchestration, guardrails, memory and validations.", "license": "MIT", "author": "FullChico", diff --git a/plugins/memory/.claude-plugin/plugin.json b/plugins/memory/.claude-plugin/plugin.json index 48a61dc..e21f5de 100644 --- a/plugins/memory/.claude-plugin/plugin.json +++ b/plugins/memory/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "memory", - "version": "0.2.0", + "version": "0.3.0", "description": "Git-anchored project memory: a code map and notes from past sessions, injected at the start of each session and marked stale when the code changes.", "author": { "name": "FullChico" diff --git a/plugins/memory/.codex-plugin/plugin.json b/plugins/memory/.codex-plugin/plugin.json index 40b371f..2727c0c 100644 --- a/plugins/memory/.codex-plugin/plugin.json +++ b/plugins/memory/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "memory", - "version": "0.2.0", + "version": "0.3.0", "description": "Per-project harness code map, sessions and anchored notes.", "hooks": "./codex-hooks/hooks.json" } diff --git a/plugins/memory/scripts/codex_learn.py b/plugins/memory/scripts/codex_learn.py index 3839cd1..97d3842 100644 --- a/plugins/memory/scripts/codex_learn.py +++ b/plugins/memory/scripts/codex_learn.py @@ -81,7 +81,7 @@ def usage(path): def digest(path): - lines = [learn.HEADER, ""] + lines = [] for item in entries(path): payload = item.get("payload") or {} if item.get("type") != "response_item" or payload.get("type") != "message": @@ -93,8 +93,7 @@ def digest(path): text = block.get("text") if isinstance(block, dict) else None if isinstance(text, str) and text.strip(): lines.append(("DONO: " if role == "user" else "AGENTE: ") + learn._cut(text)) - text = "\n".join(lines) - return text[:learn.DIGEST_LIMIT].rsplit("\n", 1)[0] if len(text) > learn.DIGEST_LIMIT else text + return learn.parts(lines) def main(argv): diff --git a/plugins/memory/scripts/learn.py b/plugins/memory/scripts/learn.py index fca0446..8a6459f 100644 --- a/plugins/memory/scripts/learn.py +++ b/plugins/memory/scripts/learn.py @@ -8,7 +8,7 @@ O formato das transcrições não é contrato documentado; foi observado. Arquivo que não se parece com ele é recusado, em vez de virar número errado. -Uso: learn.py |usage [...]|mark ...|remember> +Uso: learn.py (imprime as partes)|usage [...]|mark ...|remember> """ import datetime import json @@ -223,29 +223,75 @@ def _cut(text: str) -> str: return text if len(text) <= MESSAGE_LIMIT else text[:MESSAGE_LIMIT] + " (cortado)" -def digest(session_path) -> str: - lines = [HEADER, ""] - for entry in _entries(session_path): - if entry.get("isSidechain") or entry.get("isMeta"): +# Texto que a plataforma põe na voz do dono e não é dele: a skill carregada, avisos do sistema. +_NOT_OWNER = ("Base directory for this skill", "", "", "") +REVIEW = "You are the independent reviewer of gate" # a sessão que um `validate-gate` abriu + + +def _lines(path, who_user="DONO", who_agent="AGENTE"): + lines = [] + for entry in _entries(path): + if entry.get("isMeta"): continue message = entry.get("message") content = message.get("content") if isinstance(message, dict) else None if entry.get("type") == "user": blocks = [content] if isinstance(content, str) else [ b.get("text") for b in content or [] if isinstance(b, dict) and b.get("type") == "text"] - lines += [f"DONO: {_cut(text)}" for text in blocks if isinstance(text, str) and text.strip()] + lines += [f"{who_user}: {_cut(text)}" for text in blocks if isinstance(text, str) and text.strip() + and not text.lstrip().startswith(_NOT_OWNER)] elif entry.get("type") == "assistant" and isinstance(content, list): - for block in content: - if not isinstance(block, dict): - continue - if block.get("type") == "text" and isinstance(block.get("text"), str) and block["text"].strip(): - lines.append(f"AGENTE: {_cut(block['text'])}") - elif block.get("type") == "tool_use": - lines.append(f"FERRAMENTA: {block.get('name')}") - text = "\n".join(lines) - if len(text) > DIGEST_LIMIT: - text = text[:DIGEST_LIMIT].rsplit("\n", 1)[0] + "\n(resumo cortado: a sessão continua além deste ponto)" - return text + lines += [f"{who_agent}: {_cut(b['text'])}" for b in content if isinstance(b, dict) + and b.get("type") == "text" and isinstance(b.get("text"), str) and b["text"].strip()] + return lines + + +def digest(session_path) -> list: + """O resumo da sessão em partes de até DIGEST_LIMIT: a sessão inteira, sem corte, e o que cada + subagente dela escreveu (quem executou e quem revisou também descobre). Devolve os textos das partes.""" + lines = _lines(session_path) + sub = os.path.join(session_path[:-len(".jsonl")], "subagents") + for name in sorted(os.listdir(sub)) if os.path.isdir(sub) else []: + if not name.endswith(".jsonl"): + continue + kind = "subagente" + try: + with open(os.path.join(sub, name[:-len(".jsonl")] + ".meta.json"), encoding="utf-8") as f: + kind = (json.load(f) or {}).get("agentType") or kind + except (OSError, ValueError, AttributeError): + pass + try: + lines += _lines(os.path.join(sub, name), f"PEDIDO A {kind}", kind.upper()) + except ValueError: + continue + return parts(lines) + + +def parts(lines) -> list: + """As linhas em partes de até DIGEST_LIMIT, sem corte.""" + found, current = [], [HEADER, ""] + for line in lines: + if sum(len(l) + 1 for l in current) + len(line) > DIGEST_LIMIT and len(current) > 2: + found.append("\n".join(current)) + current = [HEADER, ""] + current.append(line) + found.append("\n".join(current)) + if len(found) > 1: + found = [f"{text}\n(parte {n} de {len(found)})" for n, text in enumerate(found, 1)] + return found + + +def kind(session) -> str: + """trabalho, revisão (aberta por `validate-gate`; o veredito já está certificado) ou em andamento.""" + import time + if time.time() - session["mtime"] < 120: + return "em andamento" + try: + with open(session["path"], encoding="utf-8", errors="replace") as f: + head = f.read(65536) + except OSError: + return "trabalho" + return "revisão" if REVIEW in head else "trabalho" def select(found, ids) -> list: @@ -295,13 +341,16 @@ def main(argv) -> int: for session in sessions(root): if "--all" in args or not session["processed"]: when = datetime.datetime.fromtimestamp(session["mtime"]).strftime("%Y-%m-%d %H:%M") - print(f"{session['id']}\t{when}\t{'processada' if session['processed'] else 'nova'}") + print(f"{session['id']}\t{when}\t{'processada' if session['processed'] else 'nova'}\t{kind(session)}") elif command == "digest" and len(args) == 2: - text = digest(select(sessions(root), [args[0]])[0]["path"]) + parts = digest(select(sessions(root), [args[0]])[0]["path"]) os.makedirs(os.path.dirname(os.path.abspath(args[1])), exist_ok=True) - with open(args[1], "w", encoding="utf-8") as f: - f.write(text + "\n") - print(args[1]) + base, ext = os.path.splitext(args[1]) + names = [args[1]] if len(parts) == 1 else [f"{base}.{n}{ext}" for n in range(1, len(parts) + 1)] + for name, text in zip(names, parts): + with open(name, "w", encoding="utf-8") as f: + f.write(text + "\n") + print("\n".join(names)) # uma parte por linha: um extrator por parte elif command == "usage": _print_usage(root, args) elif command == "propose" and len(args) == 2: diff --git a/plugins/memory/scripts/memory.py b/plugins/memory/scripts/memory.py index b6580b3..804698c 100644 --- a/plugins/memory/scripts/memory.py +++ b/plugins/memory/scripts/memory.py @@ -197,7 +197,8 @@ def units(root) -> list: for path in paths: unit = _unit_of_file(path, depth, excluded) if path else None # Nome com caractere de controle não entra: ele iria parar no texto de toda sessão. - if unit and not any(ord(ch) < 32 for ch in unit): + # O mapa é de código: pasta só de documentos (.md) não é unidade. + if unit and not any(ord(ch) < 32 for ch in unit) and not path.lower().endswith((".md", ".mdx")): found.add(unit) return sorted(found) diff --git a/plugins/tr/.claude-plugin/plugin.json b/plugins/tr/.claude-plugin/plugin.json index bf2dd0e..8c87752 100644 --- a/plugins/tr/.claude-plugin/plugin.json +++ b/plugins/tr/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "tr", - "version": "2.7.0", + "version": "2.8.0", "description": "Single entry point of the harness: diagnosis, grilling interview (Matt Pocock), gates, validators and memory.", "author": { "name": "FullChico" diff --git a/plugins/tr/.codex-plugin/plugin.json b/plugins/tr/.codex-plugin/plugin.json index b0963a5..68959d7 100644 --- a/plugins/tr/.codex-plugin/plugin.json +++ b/plugins/tr/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "tr", - "version": "2.7.0", + "version": "2.8.0", "description": "Single entry point of the harness: diagnosis, grilling interview (Matt Pocock), gates, validators and memory.", "skills": "./codex-skills/", "hooks": "./codex-hooks/hooks.json" diff --git a/plugins/tr/skills/configure/SKILL.md b/plugins/tr/skills/configure/SKILL.md index ff06d54..fcdd172 100644 --- a/plugins/tr/skills/configure/SKILL.md +++ b/plugins/tr/skills/configure/SKILL.md @@ -34,6 +34,13 @@ tests, lint/typecheck configuration, spec documentation and deploy tools. For each suggestion, note the concrete evidence and check that the command really exists. Preserve the gates already defined by the owner. +**A flow that does what the tr does is a competing flow, not a gate.** When the project already has its own +process for specs, plans, tickets or review (a spec framework, its slash commands, a commit gate, a planning +folder with its own state), registering it as the `process` gate keeps two flows that disagree. Show the +owner what it does and where it is wired (commands, hooks, scripts, CI), and recommend replacing it with the +tr flow: its open specs become a demand through `/tr:process-plan`, and its wiring is removed as the first +demand. Its useful rules stay as project rules (`AGENTS.md`, a lint, a check). The owner decides. + As soon as the stack and the architecture are decided in the interview, run `/tr:skills-discover` by default: inventory what the project and this machine already have, propose pinning to the project the machine-only skills that matter to the stack, and search best-practice skills for each main technology @@ -160,6 +167,9 @@ loads (for example `.env`), not from the command line. When done, run `gate` and show the result to the owner. If any gate fails on the first check, explain what is missing without rewriting the registry. +When the project has the `memory` plugin (the `memory` command exists), finish by running `/tr:memory-map` +on your own: the project leaves the configuration with its code map, and every session starts from it. + ## Checklist - [ ] I summarized the doctor for each available environment and analyzed the project before asking. @@ -169,3 +179,4 @@ check, explain what is missing without rewriting the registry. - [ ] Sketch outside the repository; `--register`/`--set`/`models configure` run by me and approved by the owner in the dialog, never `Write`/`Edit`. - [ ] I remembered to review the registry before stamping. - [ ] I ran `gate` at the end and showed the state. +- [ ] With the `memory` plugin, I ran `/tr:memory-map` so the project starts with its map. diff --git a/plugins/tr/skills/memory-dream/SKILL.md b/plugins/tr/skills/memory-dream/SKILL.md index fe05bd6..a9d77db 100644 --- a/plugins/tr/skills/memory-dream/SKILL.md +++ b/plugins/tr/skills/memory-dream/SKILL.md @@ -27,7 +27,13 @@ memory check memory graph rebuild ``` -The first lists the sessions not yet processed, including those from already removed worktrees. +The first lists the sessions not yet processed, including those from already removed worktrees, with +their kind in the last column: + +- `trabalho`: a work session. Read it. +- `revisão`: a session a `validate-gate` opened for a reviewer. Its verdict is already in the + certificate; do not extract it, mark it in step 6 as it is. +- `em andamento`: still being written (usually this very session). Leave it for the next dream. Where a command asks for ``, the full id or a prefix that matches only one session works. The second lists the aged notes. Transcripts live in `~/.claude/`, read-only: the plugin never writes there. The local graph links functions and files (Graphify, when installed) to summaries, glossary, @@ -44,13 +50,15 @@ mkdir -p .harness-run/dream && { [ -f .harness-run/.gitignore ] || echo '*' > .h memory-sessions digest .harness-run/dream/.md ``` -The digest carries only what the owner and the agent wrote, without tool output. +The digest carries only what the owner, the agent and each of the session's subagents (executors, +orchestrator, reviewers) wrote, without tool output. A long session comes out in parts +(`.1.md`, `.2.md`...): the command prints one path per line, and every part is read. ## 3. Extract candidates The notes are proposed by the `memory:extractor` subagent (runs on `haiku`), never by you. You did or followed the -delivery, and would choose to remember what was hard work. It reads only the digest. One per digest, several -in the same message, up to 3 at a time, with the one-line request: +delivery, and would choose to remember what was hard work. It reads only the digest. One per digest part, +several in the same message, up to 3 at a time, with the one-line request: ```request memory:extractor summary: .harness-run/dream/.md @@ -66,8 +74,8 @@ You decide what goes in, among what was proposed. For each candidate: - **Verify against the code, opening the files.** Read the indicated paths. A word search is not verification. If the code does not show what the item claims, discard it. -- **Locate via the graph.** Run `memory graph search ""` for each - candidate; check the returned relations and paths against the current code. A relation +- **Locate via the graph (required).** Run `memory graph search ""` for each + candidate before saving it; check the returned relations and paths against the current code. A relation inferred by Graphify is a lead, not proof. If the glossary points to a path that vanished or changed, revise the anchor before saving the note. - **Discard environment workarounds.** What only exists because a tool failed in the sandbox @@ -107,4 +115,7 @@ with the same name and the same paths, which anchors it to the current commit. I memory-sessions mark ``` +Mark a work session only after every part of its digest went through the extractor: a session marked +half-read never comes back. Mark the `revisão` sessions together. Leave `em andamento` ones unmarked. + Report to the owner how many sessions were read, and the new, updated and deleted notes. diff --git a/plugins/tr/skills/process-plan/SKILL.md b/plugins/tr/skills/process-plan/SKILL.md index 915ec5d..66ec609 100644 --- a/plugins/tr/skills/process-plan/SKILL.md +++ b/plugins/tr/skills/process-plan/SKILL.md @@ -43,6 +43,12 @@ The limit on human intervention is set in the plan: only a change of scope or de external action, or a technical/policy blocker with no allowed alternative after investigation. Gate rejections produce a fix and revalidation inside the loop. +## 0. Memory up to date + +When the project has the `memory` plugin (the `memory` command exists), run `memory check` before the +interview. If units are aged or without a summary, run `/tr:memory-map` first: it redoes only what changed, +on `haiku`. The interview then starts on a current map. Without the plugin, skip this step. + ## 1. Interview Invoke `mattpocock-skills:grilling` and `mattpocock-skills:domain-modeling` with the Skill tool (the same @@ -202,5 +208,10 @@ command or artifact gate) and, for each required agent gate, the registered revi If it failed or was rejected: an implementer fixes and the reviewer revalidates what changed, without asking the owner for intermediate approval. Finally, run `tr-harness deliver` or `gate delivery`. The orchestrator reports the result to the main session; it only declares the delivery complete when that command passes. At the start of the final response write -`DELIVERY: done`; the Stop hook checks the certificates again. Intermediate replies and questions +`DELIVERY: done`; the Stop hook checks the certificates again. + +**Learn from the delivery.** When the main session receives `DELIVERY: done` and the project has the +`memory` plugin, it runs `/tr:memory-dream` right away, on its own, without asking the owner: what this +demand's sessions taught becomes notes while it is fresh. It does not block the delivery and is not a +gate; it is the loop that closes it. Report the new notes with the delivery result. Intermediate replies and questions do not use this mark. Git is initialized by the installer; push and PR are separate actions. diff --git a/tests/test_install.py b/tests/test_install.py index cf9457d..f617fd1 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -35,6 +35,18 @@ def install(self, *args): return subprocess.run([shutil.which("node"), str(ROOT / "bin/harness.js"), "install", str(self.repo), *args], capture_output=True, text=True, env=env) + def test_a_marketplace_registered_from_another_source_stops_the_install(self): + home = _tmpdir() + (home / ".claude/plugins").mkdir(parents=True) + (home / ".claude/plugins/known_marketplaces.json").write_text(json.dumps( + {"fullchico": {"source": {"source": "directory", "path": "/tmp/uma-pasta-de-teste"}}})) + env = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", HOME=str(home)) + r = subprocess.run([shutil.which("node"), str(ROOT / "bin/harness.js"), "install", str(self.repo)], + capture_output=True, text=True, env=env) + self.assertNotEqual(r.returncode, 0, "não segue em silêncio com a fonte errada") + self.assertIn("aponta para /tmp/uma-pasta-de-teste", r.stdout) + self.assertIn("claude plugin marketplace remove fullchico", r.stdout) + def calls(self): return (self.bin / "calls").read_text().splitlines() @@ -239,7 +251,12 @@ def test_pins_the_marketplace_to_this_version(self): self.assertEqual(ref, f"v{version}") def test_a_local_source_is_installed_before_publishing(self): - env = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", FULLCHICO_HARNESS_SOURCE=str(ROOT)) + home = _tmpdir() # a máquina já registrou o marketplace a partir desta pasta + (home / ".claude/plugins").mkdir(parents=True) + (home / ".claude/plugins/known_marketplaces.json").write_text(json.dumps( + {"fullchico": {"source": {"source": "directory", "path": str(ROOT)}}})) + env = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", FULLCHICO_HARNESS_SOURCE=str(ROOT), + HOME=str(home)) r = subprocess.run([shutil.which("node"), str(ROOT / "bin/harness.js"), "install", str(self.repo)], capture_output=True, text=True, env=env) self.assertEqual(r.returncode, 0, r.stderr) diff --git a/tests/test_plugin_memory.py b/tests/test_plugin_memory.py index b46550f..e46ea16 100644 --- a/tests/test_plugin_memory.py +++ b/tests/test_plugin_memory.py @@ -1,6 +1,7 @@ """Plugin `memory`: mapa e notas ancorados em git, candidatos de nota do extractor, sessões do projeto.""" import json import os +import pathlib import subprocess import sys import unittest @@ -197,11 +198,42 @@ def test_digest_keeps_only_what_people_wrote(self): self.assertEqual(r.returncode, 0, r.stderr) self.assertIn("DONO: faça X", (self.repo / "d.md").read_text()) + def test_a_long_session_is_read_whole_with_its_subagents(self): + folder = self.folder() + said = [json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": f"achado {n} " + "x" * 1500}]}}) + for n in range(60)] + said.append(json.dumps({"type": "user", "message": {"content": "Base directory for this skill: texto da skill"}})) + (folder / "longa.jsonl").write_text("\n".join(said) + "\n") + (folder / "longa/subagents").mkdir(parents=True) + (folder / "longa/subagents/agent-x.jsonl").write_text(json.dumps( + {"type": "assistant", "message": {"content": [{"type": "text", "text": "o executor descobriu Y"}]}}) + "\n") + (folder / "longa/subagents/agent-x.meta.json").write_text(json.dumps({"agentType": "general-purpose"})) + r = self.bin("memory-sessions", "digest", "longa", str(self.repo / "d.md")) + parts = r.stdout.splitlines() + self.assertGreater(len(parts), 1, "sessão longa sai em partes, sem corte") + text = "".join(pathlib.Path(p).read_text() for p in parts) + self.assertIn("achado 59", text, "nada se perde no fim") + self.assertIn("GENERAL-PURPOSE: o executor descobriu Y", text, "quem executou também é lido") + self.assertNotIn("texto da skill", text, "o texto da skill não é do dono") + + def test_sessions_say_their_kind(self): + import time + folder = self.folder() + (folder / "rev.jsonl").write_text(json.dumps({"type": "user", "message": {"content": + "You are the independent reviewer of gate `bugs`"}}) + "\n") + (folder / "job.jsonl").write_text(json.dumps({"type": "user", "message": {"content": "faça X"}}) + "\n") + old = time.time() - 3600 + for name in ("rev.jsonl", "job.jsonl"): + os.utime(folder / name, (old, old)) + out = self.bin("memory-sessions", "sessions").stdout + self.assertIn("revisão", next(l for l in out.splitlines() if l.startswith("rev"))) + self.assertIn("trabalho", next(l for l in out.splitlines() if l.startswith("job"))) + class TestPackaging(unittest.TestCase): def test_layout(self): manifest = json.loads((PLUGIN / ".claude-plugin/plugin.json").read_text()) - self.assertEqual((manifest["name"], manifest["version"]), ("memory", "0.2.0")) + self.assertEqual((manifest["name"], manifest["version"]), ("memory", "0.3.0")) hooks = json.loads((PLUGIN / "hooks/hooks.json").read_text())["hooks"] self.assertIn("SessionStart", hooks) self.assertEqual(hooks["SubagentStop"][0]["matcher"], "^memory:extractor$")