Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 16 additions & 14 deletions bin/harness.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
2 changes: 1 addition & 1 deletion plugins/memory/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
2 changes: 1 addition & 1 deletion plugins/memory/.codex-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
}
5 changes: 2 additions & 3 deletions plugins/memory/scripts/codex_learn.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand All @@ -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):
Expand Down
93 changes: 71 additions & 22 deletions plugins/memory/scripts/learn.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <raiz> <sessions [--all]|digest <id> <arquivo>|usage [<id>...]|mark <id>...|remember>
Uso: learn.py <raiz> <sessions [--all]|digest <id> <arquivo> (imprime as partes)|usage [<id>...]|mark <id>...|remember>
"""
import datetime
import json
Expand Down Expand Up @@ -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", "<system-reminder>", "<task-notification>", "<local-command-caveat>")
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:
Expand Down Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion plugins/memory/scripts/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion plugins/tr/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
2 changes: 1 addition & 1 deletion plugins/tr/.codex-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
11 changes: 11 additions & 0 deletions plugins/tr/skills/configure/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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.
23 changes: 17 additions & 6 deletions plugins/tr/skills/memory-dream/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<id>`, 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,
Expand All @@ -44,13 +50,15 @@ mkdir -p .harness-run/dream && { [ -f .harness-run/.gitignore ] || echo '*' > .h
memory-sessions digest <id> .harness-run/dream/<id>.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
(`<id>.1.md`, `<id>.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/<id>.md
Expand All @@ -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 "<concept or path>"` for each
candidate; check the returned relations and paths against the current code. A relation
- **Locate via the graph (required).** Run `memory graph search "<concept or path>"` 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
Expand Down Expand Up @@ -107,4 +115,7 @@ with the same name and the same paths, which anchors it to the current commit. I
memory-sessions mark <id> <id>
```

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.
13 changes: 12 additions & 1 deletion plugins/tr/skills/process-plan/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Loading
Loading