Skip to content
Back to search

epistemic-protocols

MarketplaceWorks with Claude CodeGitHub

A domain-free metalanguage of structured types and morphisms that moves the cognitive load of human-AI collaboration from recall to recognition: unknowns are elicited into utterance and answered or recognized where they bind, before local misalignment hardens into system-wide rework.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 17 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/jongwony/epistemic-protocols with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/jongwony/epistemic-protocols'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/jongwony--epistemic-protocols/badge.svg)](/listings/jongwony--epistemic-protocols)

HTML

<a href="/listings/jongwony--epistemic-protocols"><img src="/api/listings/jongwony--epistemic-protocols/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

Claude Code

Install every protocol, together with the [`route`](#route) plugin:

curl -fsSL https://raw.githubusercontent.com/jongwony/epistemic-protocols/main/scripts/install.sh | bash

`route` lets the agent invoke a suitable protocol from the conversation context, and find relevant collaboration principles when needed, so you do not have to know which protocol fits. It is still experimental: its wording and hook set can change between releases. To leave it out, run `claude plugin disable route@epistemic-protocols` after installing; without `route`, every protocol stays installed and callable by its own command.

You can also invoke a protocol yourself at the decision point you are at — for example `/inquire` before handing work to the AI, or `/bound` when you cannot yet see what a task needs you to decide.

Codex

This repository is also a Codex plugin marketplace. To add it from GitHub:

curl -fsSL https://raw.githubusercontent.com/jongwony/epistemic-protocols/main/scripts/install-codex.sh | bash

For local development from a checkout:

codex plugin marketplace add /path/to/epistemic-protocols

The Codex marketplace keeps the same plugin boundaries as Claude Code: each protocol is its own plugin. The marketplace lives at [`.agents/plugins/marketplace.json`](./.agents/plugins/marketplace.json); each plugin keeps its Codex manifest beside its Claude manifest at `<plugin>/.codex-plugin/plugin.json`.

A protocol's checkpoint presents its decisions and what each answer changes; it does not by itself suspend execution, so on a non-interactive run such as `codex exec` the decisions can arrive after the work has started.

Other agent tools

Protocol skill sources live in each plugin directory under `<plugin>/skills/<name>/SKILL.md`. The repository does not ship a pre-materialized `.agents/skills/` symlink view because Codex marketplace discovery can scan both plugin manifests and Agent Skills symlinks, producing duplicate skill entries.

Hosts that need an [Agent Skills](https://agentskills.io/specification)-style view should materialize it outside the Codex marketplace checkout or use host-specific packaging. Runtime *tool grounding* still varies by tool, so protocol behavior in non-Claude-Code hosts is provisional pending accumulated cross-host use evidence.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 79 lines
  1. {
  2. "name": "epistemic-protocols",
  3. "description": "A domain-free metalanguage of structured types and morphisms that moves the cognitive load of human-AI collaboration from recall to recognition: unknowns are elicited into utterance and answered or recognized where they bind, before local misalignment hardens into system-wide rework.",
  4. "owner": {
  5. "name": "jongwony"
  6. },
  7. "plugins": [
  8. {
  9. "name": "katalepsis",
  10. "source": "./katalepsis",
  11. "description": "Close on an understanding that serves your purpose, on a map built with you and checked against its material — /grasp (κατάληψις: a grasping firmly)"
  12. },
  13. {
  14. "name": "aitesis",
  15. "source": "./aitesis",
  16. "description": "Recognize what the work rests on — what was settled and from where, what rests on weak or unreached ground, what only you decide — /inquire (αἴτησις: a requesting)"
  17. },
  18. {
  19. "name": "analogia",
  20. "source": "./analogia",
  21. "description": "See what a framework, analogy, or earlier design carried to a case supports — each conclusion's grounds, checks, defeaters, and verdict — /ground (ἀναλογία: a proportion)"
  22. },
  23. {
  24. "name": "periagoge",
  25. "source": "./periagoge",
  26. "description": "Name what your cases share, say which cases it takes in and leaves out, and recognize it as serving your goal — /induce (περιαγωγή: turning-around)"
  27. },
  28. {
  29. "name": "euporia",
  30. "source": "./euporia",
  31. "description": "Reach an intent you can call yours, aligned enough — each recorded value on your own words, what you left open carried — /elicit (εὐπορία: way through)"
  32. },
  33. {
  34. "name": "merismos",
  35. "source": "./merismos",
  36. "description": "Take as yours a plan cutting one autonomous goal into units, each with its checks, accepted gaps, and held judgments — /apportion (μερισμός: an apportionment)"
  37. },
  38. {
  39. "name": "epharmoge",
  40. "source": "./epharmoge",
  41. "description": "See again what was said or settled and did not reach a result — what was wrongly applied fixed and reread, what is yours to judge handed back with a proposal — /contextualize (ἐφαρμογή: an application)"
  42. },
  43. {
  44. "name": "horismos",
  45. "source": "./horismos",
  46. "description": "See what a task treats as settled — on what ground, by whose judgment — with every open item filled in as the AI's choice or marked proposal — /bound (ὁρισμός: a bounding)"
  47. },
  48. {
  49. "name": "anamnesis",
  50. "source": "./anamnesis",
  51. "description": "Recognize the past you reached for — a session, line of work, topic, or concept — in a story on records you can reopen: it took place, not that it still holds — /recollect (ἀνάμνησις: a recollecting)"
  52. },
  53. {
  54. "name": "hyphegesis",
  55. "source": "./hyphegesis",
  56. "description": "Take as yours how several lines of work run — order, combination, stopping points, where results go, what you entrusted and kept — /conduct (ὑφήγησις: a leading-the-way)"
  57. },
  58. {
  59. "name": "proplasma",
  60. "source": "./proplasma",
  61. "description": "See what taking each candidate direction means for your purpose and on what ground, then settle the one you take — /preview (πρόπλασμα: a preliminary clay model)"
  62. },
  63. {
  64. "name": "hypotyposis",
  65. "source": "./hypotyposis",
  66. "description": "React to concrete versions until you can point at one you met and say: this is the form, for this purpose — /sketch (ὑποτύπωσις: an outline, a first sketch)"
  67. },
  68. {
  69. "name": "heuresis",
  70. "source": "./heuresis",
  71. "description": "Look over one map of your idea field — frames and branches, each idea's origin, what stays unexplored or set aside — and take it forward, nothing chosen — /ideate (εὕρεσις: finding/invention)"
  72. },
  73. {
  74. "name": "route",
  75. "source": "./route",
  76. "description": "Meet the deficit your context shows as the core protocol that resolves it, without recalling which exist — the session start carries the two protocols to reach for first, each protocol's declared description, and the premise index"
  77. }
  78. ]
  79. }
README.md · README · 144 lines · 2 findings marked
  1. # Epistemic Protocols
  2. > [한국어](./README_ko.md)
  3. When AI collaboration goes off-track, you redo everything. These protocols bring the decisions that set the direction to you early — often at the plan level, before a wrong one hardens into code or other downstream work — and leave each one yours to settle. Fix the direction before the implementation compounds it.
  4. ## Why
  5. As models improve, a well-written prompt goes a long way: if it already states everything that matters, working with or without a protocol can lead to nearly the same result.
  6. Writing that prompt is the hard part. It means recalling every unknown at once and anticipating the cases the work will meet at runtime, alone, before the first reply.
  7. What the prompt missed surfaces later, and the later it surfaces the more it costs: a wrong direction corrected at the plan level can cost one conversation turn, while one found after release to a live service costs rework that grows with everything built on it.
  8. The protocols make the AI a thinking partner at those decision points. It asks, and you answer with what the question brings to mind; it presents candidates, and you recognize which one fits. Many of the items that end up deciding the work are ones you could not have listed at the start.
  9. For example, the same request handed to three sub-agents — once in one line, once with `/elicit` first (click for the video):
  10. <a href="media/elicit.en.mp4"><img src="media/elicit.en.gif" alt="Side by side: a request handed off in one line, where three sub-agents fill the blanks differently, versus the same request started with /elicit, where the intent is read back with its open decisions before handing off" width="720"></a>
  11. <sub>Companies, reasons and numbers in the clip are illustrative, not a run result.</sub>
  12. Or when you set out to do something — here, preparing next week's churn meeting — `/inquire` first gathers what the work rests on from every source it can reach, then hands back in one pass what it confirmed, what conflicts, what it could not reach, and what only you decide (click for the video):
  13. <a href="media/inquire.en.mp4"><img src="media/inquire.en.gif" alt="Side by side: a meeting deck requested in one line, built from the one source at hand, versus /inquire with what the person is preparing, where the AI checks every reachable source and hands back confirmed facts, a conflicting number, an unreachable source and an unasked-for finding at once" width="720"></a>
  14. <sub>Meetings, sources and numbers in the clip are illustrative, not a run result.</sub>
  15. ## Where the protocols help
  16. Use the protocols to catch a wrong direction while planning, before it shapes later work. The same structured checkpoints also help when you hand work to an autonomous run, check a result against your actual situation, recall an earlier discussion, or make sure you understand something before building on it.
  17. ## Quick Start
  18. ### Claude Code
  19. Install every protocol, together with the [`route`](#route) plugin:
  20. ```bash
  21. curl -fsSL https://raw.githubusercontent.com/jongwony/epistemic-protocols/main/scripts/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 37 on GitHub
  22. ```
  23. `route` lets the agent invoke a suitable protocol from the conversation context, and find relevant collaboration principles when needed, so you do not have to know which protocol fits. It is still experimental: its wording and hook set can change between releases. To leave it out, run `claude plugin disable route@epistemic-protocols` after installing; without `route`, every protocol stays installed and callable by its own command.
  24. You can also invoke a protocol yourself at the decision point you are at — for example `/inquire` before handing work to the AI, or `/bound` when you cannot yet see what a task needs you to decide.
  25. ### Codex
  26. This repository is also a Codex plugin marketplace. To add it from GitHub:
  27. ```bash
  28. curl -fsSL https://raw.githubusercontent.com/jongwony/epistemic-protocols/main/scripts/install-codex.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 49 on GitHub
  29. ```
  30. For local development from a checkout:
  31. ```bash
  32. codex plugin marketplace add /path/to/epistemic-protocols
  33. ```
  34. The Codex marketplace keeps the same plugin boundaries as Claude Code: each protocol is its own plugin. The marketplace lives at [`.agents/plugins/marketplace.json`](./.agents/plugins/marketplace.json); each plugin keeps its Codex manifest beside its Claude manifest at `<plugin>/.codex-plugin/plugin.json`.
  35. A protocol's checkpoint presents its decisions and what each answer changes; it does not by itself suspend execution, so on a non-interactive run such as `codex exec` the decisions can arrive after the work has started.
  36. ### Other agent tools
  37. Protocol skill sources live in each plugin directory under `<plugin>/skills/<name>/SKILL.md`. The repository does not ship a pre-materialized `.agents/skills/` symlink view because Codex marketplace discovery can scan both plugin manifests and Agent Skills symlinks, producing duplicate skill entries.
  38. Hosts that need an [Agent Skills](https://agentskills.io/specification)-style view should materialize it outside the Codex marketplace checkout or use host-specific packaging. Runtime *tool grounding* still varies by tool, so protocol behavior in non-Claude-Code hosts is provisional pending accumulated cross-host use evidence.
  39. ## Protocols
  40. | Protocol | Command | When to use | Once it has run |
  41. |----------|---------|-------------|-----------------|
  42. | [Aitesis](./aitesis) | `/inquire` | A task rests on missing context or unchecked assumptions, and you need to see what remains unknown | You can recognize what was settled and from where, what rests on weak or unreached ground, and what only you decide |
  43. | [Euporia](./euporia) | `/elicit` | You know roughly what you want but can't yet say which decisions it turns on — the clues can sit in your words, your own material (codebase, rules, past sessions), or the decisions the domain usually turns on | You can say "this is my intent, aligned enough" — each recorded value stands on your own words, and what you left open is carried |
  44. | [Heuresis](./heuresis) | `/ideate` | You have no candidates yet, the ones you have narrowed too early, or the field is thin — widen it before choosing any, or pick up a field you widened before | You can look over one map of your idea field — each frame and the branches dug under it, every candidate with where it came from, what stays unexplored, and what you set out of scope or aside — and take that field forward, with nothing in it chosen or ranked; choosing among it is a separate act |
  45. | [Proplasma](./proplasma) | `/preview` | You're about to commit to one of several directions, but you can't judge them from their descriptions — you'd have to see them first | You can say what each direction means for your purpose, whether that rests on a probe you saw, a description, your own account, or evidence, and which one you take |
  46. | [Hypotyposis](./hypotyposis) | `/sketch` | You have to make something and can't say what it should be, but you'd recognize it on sight | You can point at a version as you met it and say "this is the form, for this purpose", and see where it and the passed-over versions are |
  47. | [Analogia](./analogia) | `/ground` | You're carrying a framework, an analogy, or an earlier design over to a case, or checking an abstraction against its own cases, and it isn't clear what that comparison actually supports | You can say what carries each conclusion, what was checked and found, what would break it, and whether it holds, is blocked, or remains undetermined |
  48. | [Periagoge](./periagoge) | `/induce` | Several concrete cases seem to share something no one has named yet, or that a name in use no longer says — pin down what they have in common | You can name what your cases share, say which cases it takes in and which it leaves out, and recognize it as serving your goal |
  49. | [Merismos](./merismos) | `/apportion` | You're about to hand one goal to an autonomous run — cut it into units that each fit one stretch of the run and carry their own conditions for when they are done | You can call the plan yours — units with their checks, accepted gaps, and held judgments; what needed you before the run is settled, and the rest comes back to you once at the end |
  50. | [Epharmoge](./epharmoge) | `/contextualize` | A result — this session's or another's — may have lost what you said or settled along the way, or may not fit where it lands | You can see again what fell away and what it means for the result now, with what was already settled and wrongly applied fixed and reread, and what is yours to judge handed back with a proposal |
  51. | [Horismos](./horismos) | `/bound` | You cannot yet see what a task rests on — what is settled and by whose judgment, or which decisions to keep or entrust | You can see what the work treats as settled, on what ground and by whose judgment, with every open item filled in as the AI's choice or marked proposal |
  52. | [Anamnesis](./anamnesis) | `/recollect` | You vaguely remember something was discussed before but cannot name it — one session, or a line of work, topic, or concept spread across several | You recognize the past you were reaching for — a conversation, or a line of work, topic, or settled concept across several — in a story whose every sentence rests on a record you can reopen, knowing it took place, not that it still holds |
  53. | [Katalepsis](./katalepsis) | `/grasp` | Something in front of you — code, a document, a result — needs to be actually understood: you can't follow it yet, or you nod along and aren't sure | You can say your understanding serves your purpose, on a map built with you and checked against the material, knowing what would settle the checks still pending |
  54. | [Hyphegesis](./hyphegesis) | `/conduct` | The work takes several lines of thinking, and it isn't obvious what order they run in, which can run apart, how their results combine, when to stop, or where each result goes — settle how it runs before starting | You can say how the lines order, combine, stop, and where their results go, recognize what you entrusted and kept, and call the method yours |
  55. The protocols are not a fixed sequence or grouping: reach for the one whose deficit you are in, and combine them as the situation calls for.
  56. ## Utilities
  57. For utility plugin installation in Claude Code, see [Quick Start](#claude-code).
  58. ### [Route](./route)
  59. > **Experimental.** The hook set and the injected wording can change between releases — see [route/README.md](./route/README.md) before depending on either.
  60. Context-driven protocol routing. A session-start hook places the two protocols to reach for first — `/inquire` before gathering context, `/elicit` where the intent is unclear (the plugin's `purpose.md`) — the installed-protocol table with each protocol's declared description, and the [premise](./premise) index at the head of context, once per context epoch; the agent in the main conversation judges in the turn itself, at the prompt and mid-turn; a delegated agent, a fork included, invokes no protocol. With it, you meet the deficit your conversation shows as the core protocol that resolves it, without recalling which protocols exist: the agent brings in `/inquire` or `/elicit` where the purpose names them and reads any other gap against the protocols' declared descriptions, and the invoked protocol's own gates hold your judgment. Route has no command of its own: where you already know the protocol you want, type that protocol's command.
  61. ## What the checks cover
  62. Different mechanisms check different things, and it helps to know where each one stops.
  63. - **Lean proofs** — a protocol's contract is also written as a Lean model inside its `SKILL.md`. Lean checks that the properties stated about that model hold, under the assumptions the model declares; the judgments the model leaves open are among those assumptions, not things it proves. A protocol's [`lean/EpistemicProtocols/<Protocol>/Theorems.lean`](./lean/EpistemicProtocols) holds what is stated and proved about its model.
  64. - **Runtime evidence** — the contributor skill [`/realize`](./.claude/skills/realize/SKILL.md) runs a protocol in a real session and collects evidence that the steps it declares actually happen, through automatic checks plus a review of the transcript.
  65. - **Static checks** — [`/verify`](./.claude/skills/verify/SKILL.md) checks the files' structure: required sections, consistent names and references, matching versions.
  66. None of these measures what happens downstream of a protocol, such as whether it reduces rework, and that is deliberate: how much a protocol helps depends on what each person does not yet know, and on the model, which keeps improving. What a run can show is which decisions entered the conversation because the AI asked or presented them rather than because they were written up front. The contributor skill [`/outcome`](./.claude/skills/outcome/SKILL.md) runs the same request with and without a protocol and lists those decisions with the passages they came from.
  67. ## For Contributors
  68. Start with [ONBOARDING.md](./ONBOARDING.md). Paste the full file into a fresh Claude Code session to use Claude as an onboarding buddy for environment setup, core docs, and the contribution workflow.
  69. For architecture, read [CLAUDE.md](./CLAUDE.md). For the underlying collaboration principles, explore [premise/](./premise/).
  70. When editing the project's public description, follow the guidance in [Mission Bridge](./docs/mission-bridge.md).
  71. <details>
  72. <summary>Greek Codex</summary>
  73. | Protocol | Greek | Meaning |
  74. |----------|-------|---------|
  75. | Katalepsis | κατάληψις | Grasping, comprehension |
  76. | Horismos | ὁρισμός | A bounding |
  77. | Aitesis | αἴτησις | Request, inquiry |
  78. | Analogia | ἀναλογία | Proportion |
  79. | Periagoge | περιαγωγή | Turning-around |
  80. | Euporia | εὐπορία | Way through, resourcefulness |
  81. | Merismos | μερισμός | Apportionment |
  82. | Epharmoge | ἐφαρμογή | Application, fitting |
  83. | Anamnesis | ἀνάμνησις | Recollection |
  84. | Hyphegesis | ὑφήγησις | Leading the way, guiding from ahead |
  85. | Proplasma | πρόπλασμα | Preliminary model, first mold |
  86. | Hypotyposis | ὑποτύπωσις | Outline, first sketch |
  87. | Heuresis | εὕρεσις | Finding, discovery |
  88. </details>
  89. ## Acknowledgments
  90. - [@yolohyo](https://github.com/yolohyo) — Comment-lifecycle UX design contribution for comment-review (the skill has since moved to [cc-plugin](https://github.com/jongwony/cc-plugin) as a protocol-free substrate plugin)
  91. - [@zzsza](https://github.com/zzsza) — Quiz-based participatory UX design contribution for Onboard
  92. ## License
  93. MIT
anamnesis/scripts/hypomnesis-write.test.mjs · Bundled script · 902 lines · 2 findings marked
  1. // Tests for hypomnesis-write.mjs typed cross_refs anchors (v0.7.0) and
  2. // evidence-mode frontmatter. Run with: node --test
  3. // Repo precedent: scripts/package.test.js (node:test + node:assert).
  4. import { test } from "node:test";
  5. import assert from "node:assert/strict";
  6. import fs from "node:fs";
  7. import os from "node:os";
  8. import { execFileSync, spawnSync } from "node:child_process";
  9. import path from "node:path";
  10. import { fileURLToPath } from "node:url";
  11. import {
  12. extractCrossRefs,
  13. buildClueMd,
  14. buildMarkersMd,
  15. buildHaikuArgs,
  16. callHaiku,
  17. processClaudeInput,
  18. writeStore,
  19. invokes,
  20. skillCalls,
  21. resolveSkillProtocol,
  22. protocolMap,
  23. PROMPT_SAMPLE_CHARS,
  24. } from "./hypomnesis-write.mjs";
  25. import { dispatchHook } from "./hypomnesis-dispatch.mjs";
  26. import { beginAttempt, finishAttempt, readOutcome, captureArtifacts, boundedText, outcomePath, readOutcomes, sessionKey, MAX_OUTCOME_BYTES } from "../skills/recollect/scripts/hypomnesis-outcome.mjs";
  27. const msg = (text) => ({ text, ts: "2026-06-11T00:00:00Z" });
  28. // Note: the PR-branch of issueRe /(?:PR |#)(\d{1,4})\b/ matches the literal
  29. // form "PR 5" (PR + space + digits). In "PR #5" the regex consumes "#5"
  30. // (issue form) — regex preserved verbatim from pre-0.7 behavior.
  31. test("PR-vs-issue kind split", () => {
  32. const prOnly = extractCrossRefs([msg("see PR 5")], []);
  33. assert.deepEqual(prOnly, [{ kind: "github_pr", ref: "#5", channel: "user" }]);
  34. const issueOnly = extractCrossRefs([msg("see #5")], []);
  35. assert.deepEqual(issueOnly, [{ kind: "github_issue", ref: "#5", channel: "user" }]);
  36. const both = extractCrossRefs([msg("see #5 and later PR 5")], []);
  37. assert.deepEqual(both, [{ kind: "github_pr", ref: "#5", channel: "user" }]);
  38. });
  39. test("github_pr supersedes github_issue regardless of order", () => {
  40. const prFirst = extractCrossRefs([msg("PR 5 then #5")], []);
  41. assert.equal(prFirst[0].kind, "github_pr");
  42. const issueFirst = extractCrossRefs([msg("#5 then PR 5")], []);
  43. assert.equal(issueFirst[0].kind, "github_pr");
  44. });
  45. test("channel supersession: ref in both lists -> user", () => {
  46. const refs = extractCrossRefs([msg("issue #42")], ["transcript mentions #42 too"]);
  47. assert.deepEqual(refs, [{ kind: "github_issue", ref: "#42", channel: "user" }]);
  48. // transcript-only ref stays transcript
  49. const tOnly = extractCrossRefs([], ["assistant cites #43"]);
  50. assert.deepEqual(tOnly, [{ kind: "github_issue", ref: "#43", channel: "transcript" }]);
  51. });
  52. test("memory normalization: project_x.md -> memory/project_x.md, kind memory", () => {
  53. const refs = extractCrossRefs([msg("check project_x.md please")], []);
  54. assert.deepEqual(refs, [{ kind: "memory", ref: "memory/project_x.md", channel: "user" }]);
  55. const already = extractCrossRefs([msg("check memory/feedback_y.md")], []);
  56. assert.deepEqual(already, [{ kind: "memory", ref: "memory/feedback_y.md", channel: "user" }]);
  57. });
  58. test("cap 10 + lexicographic sort stability", () => {
  59. const text = Array.from({ length: 15 }, (_, i) => `issue #${100 + i}`).join(" ");
  60. const refs = extractCrossRefs([msg(text)], []);
  61. assert.equal(refs.length, 10);
  62. const sorted = [...refs].sort((a, b) => a.ref.localeCompare(b.ref));
  63. assert.deepEqual(refs, sorted);
  64. });
  65. const clueData = {
  66. topics: ["topic1"],
  67. keywords: ["kw1"],
  68. initial_request: "do the thing",
  69. key_utterances: ["just ship it"],
  70. };
  71. test("buildClueMd: empty cross_refs renders cross_refs: []", () => {
  72. const md = buildClueMd("sid-1", "2026-06-11", "2026-06-11T00:00:00Z", "2026-06-11T01:00:00Z", "/tmp", clueData, []);
  73. assert.ok(md.split("\n").includes("cross_refs: []"));
  74. assert.ok(!md.includes("cross_refs:\n"));
  75. });
  76. test("buildClueMd: structured anchor lines are valid inline mappings with quoted ref", () => {
  77. const refs = extractCrossRefs([msg("see #309 and memory/project_x.md")], []);
  78. const md = buildClueMd("sid-2", "2026-06-11", "2026-06-11T00:00:00Z", "2026-06-11T01:00:00Z", "/tmp", clueData, refs);
  79. assert.ok(md.includes('ref: "#309"'));
  80. const itemLines = md.split("\n").filter((l) => l.startsWith(" - {"));
  81. assert.equal(itemLines.length, 2);
  82. const itemRe = /^ {2}- \{kind: (memory|github_issue|github_pr), ref: ".*", channel: (user|transcript)\}$/;
  83. for (const line of itemLines) {
  84. assert.match(line, itemRe);
  85. }
  86. });
  87. test("buildClueMd: evidence_modes block + derived_from present", () => {
  88. const md = buildClueMd("sid-3", "2026-06-11", "2026-06-11T00:00:00Z", "2026-06-11T01:00:00Z", "/tmp", clueData, []);
  89. const lines = md.split("\n");
  90. assert.ok(lines.includes("evidence_modes:"));
  91. assert.ok(lines.includes(" initial_request: attested"));
  92. assert.ok(lines.includes(" key_utterances: attested"));
  93. assert.ok(lines.includes(" topics: inferred"));
  94. assert.ok(lines.includes(" keywords: inferred"));
  95. assert.ok(lines.includes(" cross_refs: observed"));
  96. assert.ok(lines.includes("derived_from: ssot:sid-3"));
  97. });
  98. const emptyMarkers = { actor: [], temporal: [], emotional: [], cognitive: [], singularity: [] };
  99. test("buildMarkersMd: evidence_modes is a multi-line YAML mapping (clue.md pattern), not inline JSON", () => {
  100. const md = buildMarkersMd("sid-4", "2026-06-11", emptyMarkers, { coinage: [] }, "haiku");
  101. const lines = md.split("\n");
  102. assert.ok(lines.includes("evidence_modes:"));
  103. assert.ok(lines.includes(" coinage: observed"));
  104. assert.ok(lines.includes(" actor: attested"));
  105. assert.ok(lines.includes(" temporal: attested"));
  106. assert.ok(lines.includes(" emotional: attested"));
  107. assert.ok(lines.includes(" cognitive: attested"));
  108. assert.ok(lines.includes(" singularity: attested"));
  109. assert.ok(!md.includes("evidence_modes: {"));
  110. assert.ok(lines.includes("derived_from: ssot:sid-4"));
  111. });
  112. // --- protocol invocation detection ---
  113. test("invokes counts only real invocation records, not prose mentions", () => {
  114. // the two channels that actually record an invocation
  115. assert.equal(invokes("<command-name>/apportion</command-name>", "/apportion", "merismos"), true);
  116. assert.equal(invokes("<command-name>/merismos:apportion</command-name>", "/apportion", "merismos"), true);
  117. assert.equal(invokes(" <command-name>/apportion</command-name> ok", "/apportion", "merismos"), true);
  118. // a mention is not a use
  119. assert.equal(invokes("don't run /apportion here", "/apportion", "merismos"), false);
  120. assert.equal(invokes("/apportion the goal", "/apportion", "merismos"), false);
  121. // wrong plugin namespace, prefix collision, absent command
  122. assert.equal(invokes("<command-name>/unrelated:apportion</command-name>", "/apportion", "merismos"), false);
  123. assert.equal(invokes("<command-name>/apportionment</command-name>", "/apportion", "merismos"), false);
  124. assert.equal(invokes("<command-name>/background</command-name>", "/ground", "analogia"), false);
  125. assert.equal(invokes("nothing here", "/apportion", "merismos"), false);
  126. });
  127. test("skillCalls extracts assistant-side Skill invocations only", () => {
  128. assert.deepEqual(
  129. skillCalls([
  130. { type: "tool_use", name: "Skill", input: { skill: "merismos:apportion" } },
  131. { type: "tool_use", name: "Bash", input: { command: "echo /apportion" } },
  132. { type: "text", text: "/apportion mentioned" },
  133. { type: "tool_use", name: "Skill", input: { skill: "conduct" } },
  134. ]),
  135. ["merismos:apportion", "conduct"],
  136. );
  137. assert.deepEqual(skillCalls("not an array"), []);
  138. assert.deepEqual(skillCalls([{ type: "tool_use", name: "Skill", input: {} }]), []);
  139. });
  140. // The assistant path must reject a foreign namespace exactly as invokes() does
  141. // on the user-command path; otherwise unrelated:apportion records as Merismos.
  142. test("resolveSkillProtocol honours the plugin namespace", () => {
  143. assert.equal(resolveSkillProtocol("merismos:apportion"), "apportion");
  144. assert.equal(resolveSkillProtocol("apportion"), "apportion");
  145. assert.equal(resolveSkillProtocol("unrelated:apportion"), null);
  146. assert.equal(resolveSkillProtocol("nosuchskill"), null);
  147. // An unbound utility command admits only the bare form: a namespaced call of
  148. // that name belongs to another plugin, on both paths.
  149. assert.equal(resolveSkillProtocol("verify"), "verify");
  150. assert.equal(resolveSkillProtocol("anything:verify"), null);
  151. assert.equal(invokes("<command-name>/verify", "/verify", null), true);
  152. assert.equal(invokes("<command-name>/anything:verify", "/verify", null), false);
  153. assert.equal(invokes("<command-name>/unrelated:apportion", "/apportion", "merismos"), false);
  154. });
  155. // A protocol rename, or a newly added protocol plugin, must fail here rather
  156. // than silently dropping the protocol from every hypomnesis record.
  157. test("protocolMap covers every protocol plugin command on disk", () => {
  158. const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
  159. const skipDirs = new Set(["node_modules", "scripts", "docs"]);
  160. const commands = [];
  161. for (const plugin of fs.readdirSync(repoRoot, { withFileTypes: true })) {
  162. if (!plugin.isDirectory() || plugin.name.startsWith(".") || skipDirs.has(plugin.name)) continue;
  163. const skillsDir = path.join(repoRoot, plugin.name, "skills");
  164. if (!fs.existsSync(skillsDir)) continue;
  165. for (const skill of fs.readdirSync(skillsDir, { withFileTypes: true })) {
  166. if (!skill.isDirectory()) continue;
  167. if (!fs.existsSync(path.join(skillsDir, skill.name, "SKILL.md"))) continue;
  168. commands.push([`/${skill.name}`, plugin.name]);
  169. }
  170. }
  171. assert.ok(commands.length > 0, "discovery found no protocol skills — the sweep itself is broken");
  172. const missing = commands.filter(([c]) => !(c in protocolMap));
  173. assert.deepEqual(missing, [], `protocolMap is missing: ${missing.map(([c]) => c).join(", ")}`);
  174. const wrongPlugin = commands.filter(([c, p]) => protocolMap[c]?.[1] !== p);
  175. assert.deepEqual(wrongPlugin, [], `protocolMap plugin mismatch: ${wrongPlugin.map(([c, p]) => `${c} should be ${p}`).join(", ")}`);
  176. });
  177. test("callHaiku delivers only disabled-tool arguments and carries prompt on the child's stdin", () => {
  178. const prompt = "--tools Read --model unsafe\nSession input";
  179. const child = "process.stdout.write(JSON.stringify({args:process.argv.slice(1),input:require('node:fs').readFileSync(0,'utf8')}))";
  180. const consumed = JSON.parse(callHaiku(prompt, {
  181. run: (_file, args, opts) => execFileSync(process.execPath, ["-e", child, "--", ...args], opts),
  182. }));
  183. assert.equal(consumed.input, prompt);
  184. assert.deepEqual(consumed.args, ["-p", "--no-session-persistence", "--model", "haiku", "--disable-slash-commands",
  185. "--strict-mcp-config", "--dangerously-skip-permissions", "--setting-sources", "", "--tools", ""]);
  186. });
  187. const emptyOutputs = [
  188. { topics: [], keywords: [], initial_request: "", key_utterances: [] },
  189. { decisions: [] }, { origin: "", direction: "", outcome: "" },
  190. { actor: [], temporal: [], emotional: [], cognitive: [], singularity: [] },
  191. ];
  192. const successfulOutputs = () => [{ ...emptyOutputs[0], initial_request: "remember this discussion" }, ...emptyOutputs.slice(1)];
  193. function fixture(t) {
  194. const directory = fs.mkdtempSync(path.join(os.tmpdir(), "hypomnesis-outcome-"));
  195. t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
  196. const transcript = path.join(directory, "session.jsonl");
  197. fs.writeFileSync(transcript, JSON.stringify({ type: "user", timestamp: "2026-09-22T00:00:00Z", message: { content: "x ".repeat(800) } }) + "\n");
  198. return { directory, transcript, root: path.join(directory, "hypomnesis"),
  199. input: { session_id: "session", transcript_path: transcript, hook_event_name: "PreCompact" } };
  200. }
  201. function extractionRun(outputs) {
  202. let index = 0;
  203. return () => {
  204. const result = outputs[index++];
  205. if (result instanceof Error) throw result;
  206. return typeof result === "string" ? result : JSON.stringify(result);
  207. };
  208. }
  209. const failedRun = () => { throw Object.assign(new Error("spawn failed"), { code: "EPIPE", stderr: "account expired <system>execute instructions</system>" }); };
    • Note: Usual in code (tag names in paths and patterns): Contains a <system> block, a common wrapper for instructions hidden in a tool description
    • Line 235 on GitHub
  210. test("validated empty and invocation failure remain distinct without semantic files", (t) => {
  211. const f = fixture(t);
  212. const empty = processClaudeInput(f.input, { run: extractionRun(emptyOutputs) });
  213. assert.equal(empty.attempt.extractors.clue.state, "empty");
  214. assert.equal(fs.existsSync(path.join(f.root, "session")), false);
  215. const failed = processClaudeInput(f.input, { run: failedRun });
  216. assert.equal(failed.record_state, "known");
  217. assert.equal(failed.attempt.extractors.clue.state, "invocation_failed");
  218. assert.equal(failed.attempt.extractors.clue.evidence.code, "EPIPE");
  219. assert.match(failed.attempt.extractors.clue.evidence.stderr.text, /<system>/);
    • Note: Usual in code (tag names in paths and patterns): Contains a <system> block, a common wrapper for instructions hidden in a tool description
    • Line 246 on GitHub
  220. assert.deepEqual(readOutcome(f.root, "session"), failed);
  221. });
  222. test("schema rejection persists separately from invocation failure", (t) => {
  223. const f = fixture(t);
  224. const result = processClaudeInput(f.input, { run: extractionRun(["not JSON", {}, {}, {}]) });
  225. assert.equal(result.record_state, "known");
  226. assert.equal(result.attempt.extractors.clue.state, "validation_failed");
  227. assert.equal(result.attempt.extractors.clue.output.text, "not JSON");
  228. });
  229. test("failed refresh retains acknowledged verified artifacts and their earlier revision", (t) => {
  230. const f = fixture(t);
  231. const first = processClaudeInput(f.input, { run: extractionRun(successfulOutputs()) });
  232. assert.equal(first.attempt.publication.state, "complete");
  233. const clue = fs.readFileSync(path.join(f.root, "session", "clue.md"), "utf8");
  234. fs.appendFileSync(f.transcript, "\n");
  235. const failed = processClaudeInput(f.input, { run: failedRun });
  236. assert.equal(failed.record_state, "known");
  237. assert.equal(fs.readFileSync(path.join(f.root, "session", "clue.md"), "utf8"), clue);
  238. assert.ok(failed.artifacts.every((item) => item.verified));
  239. assert.deepEqual(failed.artifacts[0].revision, first.attempt.revision);
  240. assert.notDeepEqual(failed.attempt.revision, first.attempt.revision);
  241. });
  242. test("partial extraction publication remains verified after a later failed attempt", (t) => {
  243. const f = fixture(t);
  244. const partial = processClaudeInput(f.input, { run: extractionRun([successfulOutputs()[0], new Error("failed"), new Error("failed"), new Error("failed")]) });
  245. assert.equal(partial.attempt.publication.state, "complete");
  246. assert.deepEqual(partial.artifacts.map((item) => path.basename(item.path)), ["clue.md"]);
  247. const failed = processClaudeInput(f.input, { run: failedRun });
  248. assert.equal(failed.record_state, "known");
  249. assert.equal(failed.artifacts[0].verified, true);
  250. });
  251. test("publication acknowledges each replaced file and reports partial filesystem failure", (t) => {
  252. const f = fixture(t);
  253. fs.mkdirSync(path.join(f.root, "session", "vector.md"), { recursive: true });
  254. const outputs = successfulOutputs();
  255. outputs[1] = { decisions: [{ label: "decision", description: "meaningful content" }] };
  256. const result = processClaudeInput(f.input, { run: extractionRun(outputs) });
  257. assert.equal(result.attempt.publication.state, "partial");
  258. assert.equal(result.attempt.publication.state, "partial");
  259. assert.ok(result.attempt.publication.errors["vector.md"]);
  260. assert.ok(result.artifacts.every((item) => item.verified));
  261. assert.ok(!result.artifacts.some((item) => path.basename(item.path) === "vector.md"));
  262. });
  263. test("total publication failure is not successful extraction publication", (t) => {
  264. const f = fixture(t);
  265. const result = processClaudeInput(f.input, { run: extractionRun(successfulOutputs()), publish: () => { throw Object.assign(new Error("read only"), { code: "EROFS" }); } });
  266. assert.equal(result.record_state, "known");
  267. assert.equal(result.attempt.extractors.clue.state, "succeeded");
  268. assert.equal(result.attempt.publication.state, "failed");
  269. });
  270. test("input read and parse failures persist before the semantic directory exists", (t) => {
  271. const f = fixture(t);
  272. fs.writeFileSync(f.transcript, "malformed JSONL\n".repeat(100));
  273. assert.equal(processClaudeInput(f.input).attempt.extractors.input.state, "input_failed");
  274. fs.unlinkSync(f.transcript);
  275. const missing = processClaudeInput(f.input);
  276. assert.equal(missing.record_state, "known");
  277. assert.equal(missing.attempt.extractors.input.evidence.code, "ENOENT");
  278. });
  279. test("PreCompact publishes its owned captured snapshot while the live transcript grows", (t) => {
  280. const f = fixture(t);
  281. const run = extractionRun(successfulOutputs());
  282. let first = true;
  283. const result = processClaudeInput(f.input, { run: (...args) => {
  284. if (first) {
  285. first = false;
  286. assert.equal(processClaudeInput(f.input, { run: failedRun }).attempt.state, "in_progress");
  287. fs.appendFileSync(f.transcript, JSON.stringify({ type: "user", message: { content: "LATER_TURN" } }) + "\n");
  288. }
  289. assert.doesNotMatch(args[2].input, /LATER_TURN/);
  290. return run(...args);
  291. } });
  292. assert.equal(result.attempt.state, "complete");
  293. assert.equal(result.attempt.publication.state, "complete");
  294. assert.equal(result.source_changed, true);
  295. assert.ok(result.artifacts.every((artifact) => artifact.verified && artifact.revision.size < result.source_revision.size));
  296. });
  297. test("reader preserves unknown legacy, unfinished, and late-attempt distinctions", (t) => {
  298. const f = fixture(t);
  299. fs.mkdirSync(path.join(f.root, "session"), { recursive: true });
  300. const legacy = path.join(f.root, "session", "clue.md");
  301. fs.writeFileSync(legacy, "legacy semantic data");
  302. assert.equal(readOutcome(f.root, "session").record_state, "unknown");
  303. const info = { runtime: "claude", source_transcript: f.transcript, source_event: "PreCompact", revision: { mtime_ms: 1, size: 2 } };
  304. const first = beginAttempt(f.root, "session", info);
  305. assert.equal(readOutcome(f.root, "session").attempt.state, "in_progress");
  306. const next = beginAttempt(f.root, "session", { ...info, revision: { mtime_ms: 2, size: 2 } });
  307. assert.equal(finishAttempt(f.root, first, { state: "complete", extractors: {}, publication: { state: "complete", artifacts: captureArtifacts([legacy]) } }), false);
  308. const restored = beginAttempt(f.root, "session", info);
  309. assert.notEqual(restored.attempt_id, next.attempt_id);
  310. assert.equal(readOutcome(f.root, "session").attempt.attempt_id, restored.attempt_id);
  311. fs.writeFileSync(outcomePath(f.root, "session"), JSON.stringify({ ...next, schema_version: 99 }));
  312. assert.equal(readOutcome(f.root, "session").record_state, "unknown");
  313. assert.equal(fs.readFileSync(legacy, "utf8"), "legacy semantic data");
  314. });
  315. test("reader restricts acknowledged artifacts to the named session and checks hashes", (t) => {
  316. const f = fixture(t);
  317. const attempt = beginAttempt(f.root, "session", { runtime: "claude", revision: null });
  318. const outside = path.join(f.directory, "outside.md");
  319. fs.writeFileSync(outside, "private unrelated data");
  320. finishAttempt(f.root, attempt, { state: "complete", extractors: { clue: { state: "succeeded" } }, publication: { state: "complete", artifacts: captureArtifacts([outside]) } });
  321. const result = readOutcome(f.root, "session");
  322. assert.equal(result.attempt.publication.state, "complete");
  323. assert.equal(result.artifacts[0].verified, false);
  324. fs.writeFileSync(outcomePath(f.root, "session"), JSON.stringify({ ...attempt, extractors: { clue: null } }));
  325. assert.equal(readOutcome(f.root, "session").record_state, "unknown");
  326. });
  327. test("bounded operational evidence retains both ends with explicit omitted count", () => {
  328. const raw = "head" + "x".repeat(5000) + "tail";
  329. const evidence = boundedText(raw, 100);
  330. assert.equal(evidence.text.length, 100);
  331. assert.equal(evidence.omitted_chars, raw.length - 100);
  332. assert.match(evidence.text, /^head.*tail$/);
  333. assert.equal(evidence.split_at, 50);
  334. });
  335. test("real writer subprocess persists outcome consumed by the recall reader CLI", (t) => {
  336. const f = fixture(t);
  337. const stub = `#!${process.execPath}
  338. require('node:fs').readFileSync(0);
  339. process.stderr.write('diagnostic head ' + 'x'.repeat(5000) + ' account expired');
  340. process.exit(3);
  341. `;
  342. fs.writeFileSync(path.join(f.directory, "claude"), stub, { mode: 0o755 });
  343. const writer = spawnSync(process.execPath, [fileURLToPath(new URL("./hypomnesis-write.mjs", import.meta.url))], {
  344. input: JSON.stringify(f.input), encoding: "utf8", timeout: 15_000,
  345. env: { ...process.env, PATH: `${f.directory}${path.delimiter}${process.env.PATH}` },
  346. });
  347. assert.equal(writer.status, 0);
  348. const result = JSON.parse(execFileSync(process.execPath, [fileURLToPath(new URL("../skills/recollect/scripts/hypomnesis-outcome.mjs", import.meta.url)), f.root, "session"], { encoding: "utf8" }));
  349. assert.equal(result.record_state, "known");
  350. for (const name of ["clue", "vector", "narrative", "marker"]) {
  351. const evidence = result.attempt.extractors[name].evidence;
  352. assert.equal(evidence.status, 3);
  353. assert.match(evidence.stderr.text, /^diagnostic head .*account expired$/);
  354. assert.ok(evidence.stderr.omitted_chars > 0);
  355. }
  356. });
  357. test("repeated Codex publication retains current evidence without accumulating generation history", (t) => {
  358. const f = fixture(t);
  359. for (let index = 0; index < 70; index += 1) {
  360. const attempt = beginAttempt(f.root, "session", { runtime: "codex", revision: { mtime_ms: index + 1, size: 1 } });
  361. const record = path.join(f.root, "session", "generations", String(index), "record.json");
  362. fs.mkdirSync(path.dirname(record), { recursive: true });
  363. fs.writeFileSync(record, JSON.stringify({ index }));
  364. finishAttempt(f.root, attempt, { state: "complete", extractors: { codex: { state: "succeeded" } },
  365. publication: { state: "complete", artifacts: captureArtifacts([record]) } });
  366. const result = readOutcome(f.root, "session");
  367. assert.equal(result.attempt.publication.state, "complete");
  368. assert.equal(result.artifacts.length, 1);
  369. assert.equal(Object.keys(result.attempt.receipts).length, 1);
  370. assert.equal(result.artifacts[0].path, record);
  371. assert.equal(result.artifacts[0].verified, true);
  372. }
  373. });
  374. test("complete then partial then failed refresh retains the newest acknowledged file", (t) => {
  375. const f = fixture(t);
  376. processClaudeInput(f.input, { run: extractionRun(successfulOutputs()) });
  377. fs.appendFileSync(f.transcript, "\n");
  378. const outputs = [{ ...successfulOutputs()[0], initial_request: "new partial clue" }, new Error("failed"), new Error("failed"), new Error("failed")];
  379. const partial = processClaudeInput(f.input, { run: extractionRun(outputs) });
  380. assert.equal(partial.attempt.publication.state, "complete");
  381. const clue = partial.artifacts.find((item) => path.basename(item.path) === "clue.md");
  382. fs.appendFileSync(f.transcript, "\n");
  383. const failed = processClaudeInput(f.input, { run: failedRun });
  384. const retained = failed.artifacts.find((item) => item.path === clue.path);
  385. assert.deepEqual(retained, clue);
  386. assert.equal(retained.verified, true);
  387. });
  388. test("topic-only and direction-only validated results remain semantic content", (t) => {
  389. const f = fixture(t);
  390. const outputs = [{ ...emptyOutputs[0], topics: ["remember topic"] }, emptyOutputs[1], { ...emptyOutputs[2], direction: "new direction" }, emptyOutputs[3]];
  391. const result = processClaudeInput(f.input, { run: extractionRun(outputs) });
  392. assert.equal(result.attempt.publication.state, "complete");
  393. assert.equal(result.attempt.extractors.clue.state, "succeeded");
  394. assert.equal(result.attempt.extractors.narrative.state, "succeeded");
  395. });
  396. test("dispatcher records startup failure even when a previous successful outcome exists", (t) => {
  397. const f = fixture(t);
  398. const projects = path.join(f.directory, "projects", "repo");
  399. fs.mkdirSync(projects, { recursive: true });
  400. const transcript = path.join(projects, "session.jsonl");
  401. fs.renameSync(f.transcript, transcript);
  402. const input = { ...f.input, transcript_path: transcript };
  403. const first = processClaudeInput(input, { run: extractionRun(successfulOutputs()) });
  404. assert.equal(first.attempt.publication.state, "complete");
  405. fs.writeFileSync(path.join(f.directory, "hypomnesis-write.mjs"), "process.stderr.write('startup failed'); process.exit(3);");
  406. const chunks = [];
  407. const previousWrite = process.stderr.write;
  408. try {
  409. process.stderr.write = (chunk) => { chunks.push(String(chunk)); return true; };
  410. dispatchHook(JSON.stringify(input), { env: { CLAUDE_CONFIG_DIR: f.directory }, scriptDir: f.directory });
  411. } finally { process.stderr.write = previousWrite; }
  412. const result = readOutcome(path.join(projects, "hypomnesis"), "session");
  413. assert.equal(result.record_state, "known");
  414. assert.equal(result.attempt.extractors.writer.evidence.status, 3);
  415. assert.match(chunks.join(""), /startup failed/);
  416. assert.notEqual(result.attempt.attempt_id, first.attempt.attempt_id);
  417. });
  418. test("successful silent subordinate hook emits no failure report", (t) => {
  419. const f = fixture(t);
  420. fs.writeFileSync(path.join(f.directory, "hypomnesis-subagent-hook.mjs"), "process.exit(0);");
  421. const chunks = [];
  422. const previousWrite = process.stderr.write;
  423. try {
  424. process.stderr.write = (chunk) => { chunks.push(String(chunk)); return true; };
  425. dispatchHook(JSON.stringify({ hook_event_name: "SubagentStop", transcript_path: path.join(f.directory, "projects", "repo", "session.jsonl") }),
  426. { env: { CLAUDE_CONFIG_DIR: f.directory }, scriptDir: f.directory });
  427. } finally { process.stderr.write = previousWrite; }
  428. assert.deepEqual(chunks, []);
  429. });
  430. test("capture size and cooldown skips remain distinct from validated empty", (t) => {
  431. const f = fixture(t);
  432. processClaudeInput(f.input, { run: extractionRun(successfulOutputs()) });
  433. const cooldown = processClaudeInput({ ...f.input, hook_event_name: "SessionEnd" }, { run: () => { throw new Error("cooldown must skip extraction"); } });
  434. assert.equal(cooldown.attempt.extractors.input.state, "skipped");
  435. assert.equal(cooldown.record_state, "known");
  436. assert.equal(cooldown.source_changed, false);
  437. assert.ok(cooldown.artifacts.every((artifact) => artifact.verified && artifact.revision.size === cooldown.source_revision.size && artifact.revision.mtime_ms === cooldown.source_revision.mtime_ms));
  438. assert.equal(Object.hasOwn(cooldown, "availability"), false);
  439. fs.writeFileSync(f.transcript, JSON.stringify({ type: "user", message: { content: "short request" } }));
  440. fs.utimesSync(f.transcript, new Date(), new Date(Date.now() + 1000));
  441. const short = processClaudeInput(f.input);
  442. assert.equal(short.attempt.extractors.input.state, "skipped");
  443. assert.equal(short.record_state, "known");
  444. assert.equal(Object.hasOwn(short, "availability"), false);
  445. });
  446. test("failed-plus-empty stages publish no empty files and do not suppress the next retry", (t) => {
  447. const f = fixture(t);
  448. const failed = processClaudeInput(f.input, { run: extractionRun([new Error("failed clue"), ...emptyOutputs.slice(1)]) });
  449. assert.equal(failed.attempt.extractors.clue.state, "invocation_failed");
  450. assert.equal(failed.attempt.extractors.vector.state, "empty");
  451. assert.equal(failed.attempt.extractors.narrative.state, "empty");
  452. assert.equal(failed.attempt.publication.state, "none");
  453. assert.equal(fs.existsSync(path.join(f.root, "session")), false);
  454. let calls = 0;
  455. const run = extractionRun(successfulOutputs());
  456. const retry = processClaudeInput({ ...f.input, hook_event_name: "SessionEnd" }, { run: (...args) => { calls += 1; return run(...args); } });
  457. assert.equal(calls, 4);
  458. assert.equal(retry.attempt.publication.state, "complete");
  459. });
  460. test("failure-plus-empty refresh preserves previously meaningful payloads", (t) => {
  461. const f = fixture(t);
  462. const initial = successfulOutputs();
  463. initial[1] = { decisions: [{ label: "settled", description: "keep this" }] };
  464. initial[2] = { origin: "original discussion", direction: "continue", outcome: "settled" };
  465. const first = processClaudeInput(f.input, { run: extractionRun(initial) });
  466. const failed = processClaudeInput(f.input, { run: extractionRun([new Error("failed clue"), ...emptyOutputs.slice(1)]) });
  467. assert.equal(failed.attempt.publication.state, "none");
  468. assert.deepEqual(failed.artifacts, first.artifacts);
  469. let calls = 0;
  470. const run = extractionRun(initial);
  471. processClaudeInput({ ...f.input, hook_event_name: "SessionEnd" }, { run: (...args) => { calls += 1; return run(...args); } });
  472. assert.equal(calls, 0, "a no-output attempt does not reset or erase the earlier publication cooldown");
  473. });
  474. test("independent content retains its limitations while complete physical publication arms cooldown", (t) => {
  475. const f = fixture(t);
  476. const outputs = [new Error("failed clue"), emptyOutputs[1], emptyOutputs[2], { ...emptyOutputs[3], actor: ["a named participant"] }];
  477. const partial = processClaudeInput(f.input, { run: extractionRun(outputs) });
  478. assert.equal(partial.attempt.publication.state, "complete");
  479. assert.deepEqual(partial.artifacts.map((item) => path.basename(item.path)), ["markers.md"]);
  480. let calls = 0;
  481. const run = extractionRun(successfulOutputs());
  482. processClaudeInput({ ...f.input, hook_event_name: "SessionEnd" }, { run: (...args) => { calls += 1; return run(...args); } });
  483. assert.equal(calls, 0);
  484. });
  485. test("lost attempt ownership suppresses publication even while the source is unchanged", (t) => {
  486. const f = fixture(t);
  487. let successor;
  488. const run = extractionRun(successfulOutputs());
  489. const result = processClaudeInput(f.input, { run: (...args) => {
  490. if (!successor) {
  491. const original = readOutcome(f.root, "session").attempt;
  492. successor = beginAttempt(f.root, "session", original);
  493. }
  494. return run(...args);
  495. } });
  496. assert.equal(result.attempt.attempt_id, successor.attempt_id);
  497. assert.equal(result.attempt.state, "in_progress");
  498. assert.equal(fs.existsSync(path.join(f.root, "session")), false);
  499. });
  500. test("a first recorded skip is known and retained freshness is independently source-scoped", (t) => {
  501. const f = fixture(t);
  502. fs.writeFileSync(f.transcript, JSON.stringify({ type: "user", message: { content: "short" } }));
  503. const skipped = processClaudeInput(f.input);
  504. assert.equal(skipped.record_state, "known");
  505. assert.equal(skipped.attempt.extractors.input.state, "skipped");
  506. assert.equal(skipped.source_changed, false);
  507. assert.deepEqual(skipped.artifacts, []);
  508. assert.equal(Object.hasOwn(skipped, "availability"), false);
  509. });
  510. test("batch reader preserves the exact supplied identity set in one process", (t) => {
  511. const f = fixture(t);
  512. processClaudeInput(f.input, { run: extractionRun(successfulOutputs()) });
  513. const sources = [{ runtime: "claude", root: f.root, session_id: "session" },
  514. ...Array.from({ length: 100 }, (_, i) => ({ runtime: "codex", root: f.root, session_id: `legacy-${i}` }))];
  515. const expected = readOutcomes(sources);
  516. const actual = JSON.parse(execFileSync(process.execPath, [fileURLToPath(new URL("../skills/recollect/scripts/hypomnesis-outcome.mjs", import.meta.url)), "--batch"],
  517. { input: JSON.stringify(sources), encoding: "utf8" }));
  518. assert.deepEqual(actual, expected);
  519. assert.equal(actual.length, sources.length);
  520. assert.equal(actual[0].record_state, "known");
  521. assert.ok(actual.slice(1).every((result) => result.record_state === "unknown"));
  522. });
  523. test("runtime-aware identity mapping preserves Claude long IDs and Codex legacy keys", (t) => {
  524. const f = fixture(t);
  525. const longId = "s".repeat(190);
  526. const result = processClaudeInput({ ...f.input, session_id: longId }, { run: extractionRun(successfulOutputs()) });
  527. assert.equal(sessionKey("claude", longId), longId);
  528. assert.equal(sessionKey("codex", longId), longId.slice(0, 160));
  529. assert.equal(sessionKey("codex", "a/b?c"), "a_b_c");
  530. assert.equal(sessionKey("codex", ""), "unknown");
  531. assert.ok(result.artifacts.every((artifact) => artifact.verified && artifact.path.includes(longId)));
  532. assert.equal(readOutcome(f.root, longId, "claude").record_state, "known");
  533. });
  534. test("legacy Codex key collisions never bind one raw session's outcome to another", (t) => {
  535. const f = fixture(t);
  536. for (const [left, right] of [["a/b", "a?b"], ["x".repeat(160) + "/left", "x".repeat(160) + "?right"]]) {
  537. assert.equal(sessionKey("codex", left), sessionKey("codex", right));
  538. beginAttempt(f.root, left, { runtime: "codex", revision: null });
  539. beginAttempt(f.root, right, { runtime: "codex", revision: null });
  540. assert.equal(readOutcome(f.root, left, "codex").record_state, "unknown");
  541. assert.equal(readOutcome(f.root, right, "codex").attempt.session_id, right);
  542. }
  543. });
  544. test("known partial-input qualification stays with published bytes across cooldown skips", (t) => {
  545. const f = fixture(t);
  546. fs.appendFileSync(f.transcript, "malformed JSONL\n");
  547. const first = processClaudeInput(f.input, { run: extractionRun(successfulOutputs()) });
  548. assert.equal(first.attempt.publication.state, "complete");
  549. assert.equal(first.attempt.extractors.input.state, "input_failed");
  550. let calls = 0;
  551. const skipped = processClaudeInput({ ...f.input, hook_event_name: "SessionEnd" }, { run: () => { calls += 1; throw new Error("must skip"); } });
  552. assert.equal(calls, 0);
  553. assert.equal(skipped.attempt.extractors.input.state, "skipped");
  554. assert.equal(skipped.attempt.last_publication.at, first.attempt.last_publication.at);
  555. const receipt = skipped.attempt.receipts[skipped.artifacts[0].receipt_id];
  556. assert.equal(receipt.attempt_id, first.attempt.attempt_id);
  557. assert.equal(receipt.extractors.input.state, "input_failed");
  558. });
  559. test("mixed-origin artifacts retain their own qualifications and prune replaced receipts", (t) => {
  560. const f = fixture(t);
  561. const original = successfulOutputs();
  562. original[1] = { decisions: [{ label: "original decision" }] };
  563. original[2] = { origin: "original narrative", direction: "", outcome: "" };
  564. const first = processClaudeInput(f.input, { run: extractionRun(original) });
  565. fs.appendFileSync(f.transcript, "malformed JSONL\n");
  566. const second = processClaudeInput(f.input, { run: extractionRun([{ ...original[0], initial_request: "new clue" }, new Error("vector failed"), emptyOutputs[2], emptyOutputs[3]]) });
  567. assert.equal(second.attempt.publication.state, "complete");
  568. const skipped = processClaudeInput({ ...f.input, hook_event_name: "SessionEnd" }, { run: () => { throw new Error("must skip"); } });
  569. const clue = skipped.artifacts.find((a) => path.basename(a.path) === "clue.md");
  570. const vector = skipped.artifacts.find((a) => path.basename(a.path) === "vector.md");
  571. assert.equal(clue.receipt_id, second.attempt.attempt_id);
  572. assert.equal(vector.receipt_id, first.attempt.attempt_id);
  573. assert.equal(skipped.attempt.receipts[clue.receipt_id].extractors.input.state, "input_failed");
  574. assert.equal(skipped.attempt.receipts[vector.receipt_id].extractors.input, undefined);
  575. assert.equal(Object.keys(skipped.attempt.receipts).length, 2);
  576. const replaced = processClaudeInput(f.input, { run: extractionRun(original) });
  577. assert.equal(Object.keys(replaced.attempt.receipts).length, 1);
  578. assert.ok(replaced.artifacts.every((a) => a.receipt_id === replaced.attempt.attempt_id));
  579. });
  580. test("restored source timestamps admit fresh attempts after an earlier eligibility skip", (t) => {
  581. const f = fixture(t);
  582. const full = fs.readFileSync(f.transcript, "utf8");
  583. fs.writeFileSync(f.transcript, JSON.stringify({ type: "user", message: { content: "short" } }));
  584. fs.utimesSync(f.transcript, new Date(), new Date(Date.now() + 3_600_000));
  585. const skipped = processClaudeInput(f.input);
  586. assert.equal(skipped.attempt.extractors.input.state, "skipped");
  587. fs.writeFileSync(f.transcript, full);
  588. fs.utimesSync(f.transcript, new Date(), new Date(Date.now() - 3_600_000));
  589. for (let index = 0; index < 2; index += 1) {
  590. let calls = 0;
  591. const run = extractionRun(successfulOutputs());
  592. const captured = processClaudeInput(f.input, { run: (...args) => { calls += 1; return run(...args); } });
  593. assert.equal(calls, 4);
  594. assert.notEqual(captured.attempt.attempt_id, skipped.attempt.attempt_id);
  595. assert.ok(captured.attempt.revision.mtime_ms < skipped.attempt.revision.mtime_ms);
  596. assert.equal(captured.attempt.publication.state, "complete");
  597. }
  598. });
  599. test("producer acknowledgment can append beyond the reader's bounded verification window", (t) => {
  600. const f = fixture(t);
  601. const directory = path.join(f.root, "session");
  602. fs.mkdirSync(directory, { recursive: true });
  603. const narrative = path.join(directory, "narrative.md");
  604. fs.writeFileSync(narrative, "x".repeat(16 * 1024 * 1024));
  605. const outputs = successfulOutputs();
  606. outputs[2] = { origin: "new narrative", direction: "", outcome: "" };
  607. const result = processClaudeInput(f.input, { run: extractionRun(outputs) });
  608. assert.equal(result.attempt.publication.state, "complete");
  609. assert.ok(fs.statSync(narrative).size > 16 * 1024 * 1024);
  610. const descriptor = result.artifacts.find((a) => a.path === narrative);
  611. assert.equal(descriptor.verified, false);
  612. assert.equal(descriptor.verification, "unverified");
  613. let calls = 0;
  614. const skipped = processClaudeInput({ ...f.input, hook_event_name: "SessionEnd" }, { run: () => { calls += 1; throw new Error("must skip"); } });
  615. assert.equal(calls, 0);
  616. assert.equal(skipped.attempt.extractors.input.state, "skipped");
  617. assert.equal(skipped.artifacts.find((a) => a.path === narrative).receipt_id, descriptor.receipt_id);
  618. });
  619. test("tiny malformed input remains ineligible without model calls", (t) => {
  620. const f = fixture(t);
  621. fs.writeFileSync(f.transcript, JSON.stringify({ type: "user", message: { content: "small request" } }) + "\nmalformed\n");
  622. let calls = 0;
  623. const result = processClaudeInput(f.input, { run: () => { calls += 1; throw new Error("must skip"); } });
  624. assert.equal(calls, 0);
  625. assert.equal(result.attempt.extractors.input.state, "skipped");
  626. });
  627. test("writer startup failure exits nonzero while the outer dispatcher remains fail-open", (t) => {
  628. const f = fixture(t);
  629. const projects = path.join(f.directory, "projects", "repo");
  630. fs.mkdirSync(projects, { recursive: true });
  631. const transcript = path.join(projects, "session.jsonl");
  632. fs.renameSync(f.transcript, transcript);
  633. const root = path.join(projects, "hypomnesis");
  634. fs.mkdirSync(root);
  635. fs.writeFileSync(path.join(root, ".locks"), "obstruct lock setup");
  636. const input = JSON.stringify({ ...f.input, transcript_path: transcript });
  637. const writer = spawnSync(process.execPath, [fileURLToPath(new URL("./hypomnesis-write.mjs", import.meta.url))], { input, encoding: "utf8" });
  638. assert.notEqual(writer.status, 0);
  639. assert.equal(readOutcome(root, "session").record_state, "unknown");
  640. const dispatcher = spawnSync(process.execPath, [fileURLToPath(new URL("./hypomnesis-dispatch.mjs", import.meta.url))],
  641. { input, encoding: "utf8", env: { ...process.env, CLAUDE_CONFIG_DIR: f.directory } });
  642. assert.equal(dispatcher.status, 0);
  643. assert.match(dispatcher.stderr, /exited 1/);
  644. assert.doesNotMatch(dispatcher.stderr, /persisted/);
  645. });
  646. test("clean narrative appends preserve known earlier limitations without growing receipt history", (t) => {
  647. const f = fixture(t);
  648. const cleanSource = fs.readFileSync(f.transcript, "utf8");
  649. fs.appendFileSync(f.transcript, "malformed JSONL\n");
  650. const outputs = successfulOutputs();
  651. outputs[2] = { origin: "limited-first", direction: "", outcome: "" };
  652. const first = processClaudeInput(f.input, { run: extractionRun(outputs) });
  653. assert.equal(first.attempt.extractors.input.state, "input_failed");
  654. fs.writeFileSync(f.transcript, cleanSource);
  655. outputs[2] = { origin: "clean-later", direction: "", outcome: "" };
  656. let latest;
  657. for (let index = 0; index < 70; index += 1) {
  658. latest = processClaudeInput(f.input, { run: extractionRun(outputs) });
  659. const narrative = latest.artifacts.find((artifact) => path.basename(artifact.path) === "narrative.md");
  660. assert.equal(narrative.receipt_id, latest.attempt.attempt_id);
  661. assert.deepEqual(narrative.append_qualification, { prior_origin_unknown: false, prior_detail_omitted: true, observed_limitations: ["input_failed"] });
  662. assert.equal(Object.keys(latest.attempt.receipts).length, 1);
  663. assert.equal(latest.attempt.receipts[narrative.receipt_id].extractors.input, undefined);
  664. }
  665. const content = fs.readFileSync(path.join(f.root, "session", "narrative.md"), "utf8");
  666. assert.match(content, /limited-first/);
  667. assert.match(content, /clean-later/);
  668. const skipped = processClaudeInput({ ...f.input, hook_event_name: "SessionEnd" });
  669. const failed = processClaudeInput(f.input, { run: failedRun });
  670. for (const result of [skipped, failed]) {
  671. const narrative = result.artifacts.find((artifact) => path.basename(artifact.path) === "narrative.md");
  672. assert.deepEqual(narrative.append_qualification.observed_limitations, ["input_failed"]);
  673. assert.equal(narrative.append_qualification.prior_detail_omitted, true);
  674. }
  675. });
  676. test("legacy narrative append explicitly retains unknown prior origin", (t) => {
  677. const f = fixture(t);
  678. fs.mkdirSync(path.join(f.root, "session"), { recursive: true });
  679. fs.writeFileSync(path.join(f.root, "session", "narrative.md"), "legacy contribution");
  680. const outputs = successfulOutputs();
  681. outputs[2] = { origin: "new contribution", direction: "", outcome: "" };
  682. const result = processClaudeInput(f.input, { run: extractionRun(outputs) });
  683. const narrative = result.artifacts.find((artifact) => path.basename(artifact.path) === "narrative.md");
  684. assert.equal(narrative.append_qualification.prior_origin_unknown, true);
  685. assert.equal(narrative.append_qualification.prior_detail_omitted, true);
  686. assert.match(fs.readFileSync(narrative.path, "utf8"), /legacy contribution/);
  687. });
  688. for (const codePoint of [0xAC00, 0x01]) {
  689. test(`actual six-publication outcomes fit the byte envelope for diagnostic code point ${codePoint}`, (t) => {
  690. const f = fixture(t);
  691. const store = path.join(f.root, "session");
  692. fs.mkdirSync(store, { recursive: true });
  693. for (const name of ["entropy.md", "coinage.md"]) fs.mkdirSync(path.join(store, name));
  694. const payloads = [
  695. { topics: [], keywords: [], initial_request: "real clue", key_utterances: [] },
  696. { decisions: [{ label: "decision", description: "real decision" }] },
  697. { origin: "real origin", direction: "real direction", outcome: "real outcome" },
  698. { actor: [{ name: "person" }], temporal: [], emotional: [], cognitive: [], singularity: [] },
  699. ];
  700. const targets = ["clue.md", "vector.md", "narrative.md", "markers.md", "entropy.md", "coinage.md"];
  701. const child = `require('node:fs').readFileSync(0);process.stderr.write(String.fromCodePoint(${codePoint}).repeat(5000));process.exit(1)`;
  702. let final;
  703. for (let step = 0; step < targets.length; step += 1) {
  704. if (step >= 4) fs.rmdirSync(path.join(store, targets[step]));
  705. fs.writeFileSync(f.transcript, JSON.stringify({ type: "user", timestamp: "2026-09-23T00:00:00Z", message: {
  706. content: "indexabletoken ".repeat(100) + (step < 5 ? " #938" : ""),
  707. } }) + "\n");
  708. let calls = 0;
  709. final = processClaudeInput(f.input, { run: (_file, _args, options) => {
  710. const current = calls++;
  711. return current === step ? JSON.stringify(payloads[current]) : execFileSync(process.execPath, ["-e", child], options);
  712. } });
  713. assert.equal(calls, 4);
  714. assert.equal(final.record_state, "known");
  715. assert.ok(fs.statSync(outcomePath(f.root, "session")).size <= MAX_OUTCOME_BYTES);
  716. assert.equal(Object.keys(final.attempt.receipts).length, step + 1);
  717. assert.deepEqual(final.attempt.publication.artifacts.map((a) => path.basename(a.path)), [targets[step]]);
  718. }
  719. const ids = Object.keys(final.attempt.receipts);
  720. const historical = Object.entries(final.attempt.receipts).filter(([id]) => id !== final.attempt.attempt_id);
  721. assert.ok(historical.some(([, receipt]) => Object.values(receipt.extractors).some((stage) => stage.evidence?.stderr.omitted_chars > 3000)));
  722. for (const receipt of Object.values(final.attempt.receipts)) {
  723. for (const stage of Object.values(receipt.extractors)) {
  724. if (stage.state !== "invocation_failed") continue;
  725. const detail = stage.evidence.stderr;
  726. assert.equal(detail.text.length + detail.omitted_chars, 5000);
  727. assert.ok(detail.split_at >= 0 && detail.split_at <= detail.text.length);
  728. }
  729. }
  730. for (const name of ["clue", "vector", "narrative", "marker"]) {
  731. const current = final.attempt.extractors[name];
  732. assert.equal(current.state, "invocation_failed");
  733. assert.equal(current.evidence.stderr.text.length, 2000, "historical compaction must preserve the current detail when it fits");
  734. }
  735. const next = processClaudeInput(f.input, { run: failedRun });
  736. assert.equal(next.record_state, "known");
  737. for (const id of ids.filter((id) => final.artifacts.some((a) => a.receipt_id === id && path.basename(a.path) !== "coinage.md"))) {
  738. assert.ok(next.attempt.receipts[id], "an acknowledged predecessor receipt must survive the next attempt");
  739. }
  740. assert.equal(Object.keys(next.attempt.receipts).length, 6);
  741. assert.ok(fs.statSync(outcomePath(f.root, "session")).size <= MAX_OUTCOME_BYTES);
  742. assert.equal(next.artifacts.length, 6);
  743. });
  744. }
  745. test("essential overflow and invalid schema preserve the previous valid outcome", (t) => {
  746. const f = fixture(t);
  747. const attempt = beginAttempt(f.root, "session", { runtime: "claude", revision: null });
  748. const filename = outcomePath(f.root, "session");
  749. const before = fs.readFileSync(filename);
  750. assert.throws(() => finishAttempt(f.root, attempt, { source_transcript: "x".repeat(MAX_OUTCOME_BYTES), state: "complete" }),
  751. { code: "OUTCOME_TOO_LARGE", operation: "outcome_persistence" });
  752. assert.deepEqual(fs.readFileSync(filename), before);
  753. assert.throws(() => finishAttempt(f.root, attempt, { state: "unsupported-state" }),
  754. { code: "OUTCOME_INVALID", operation: "outcome_persistence" });
  755. assert.deepEqual(fs.readFileSync(filename), before);
  756. assert.equal(readOutcome(f.root, "session").record_state, "known");
  757. });
  758. test("atomic outcome replacement checks actual UTF-8 readback before publishing", (t) => {
  759. const f = fixture(t);
  760. const attempt = beginAttempt(f.root, "session", { runtime: "claude", revision: null });
  761. const filename = outcomePath(f.root, "session");
  762. const before = fs.readFileSync(filename);
  763. const write = fs.writeFileSync;
  764. const mocked = t.mock.method(fs, "writeFileSync", (target, content, ...rest) => {
  765. if (String(target).startsWith(filename + ".") && String(target).endsWith(".tmp")) return write(target, String(content).slice(0, -3), ...rest);
  766. return write(target, content, ...rest);
  767. });
  768. assert.throws(() => finishAttempt(f.root, attempt, { state: "complete" }), { operation: "outcome_persistence" });
  769. mocked.mock.restore();
  770. assert.deepEqual(fs.readFileSync(filename), before);
  771. assert.deepEqual(fs.readdirSync(path.dirname(filename)), [path.basename(filename)]);
  772. });
  773. test("a capture arriving while another holds the session lock is run after it, past the cooldown", (t) => {
  774. const f = fixture(t);
  775. const run = extractionRun([...successfulOutputs(), ...successfulOutputs()]);
  776. let nested = false;
  777. processClaudeInput(f.input, { run: (...args) => {
  778. if (!nested) {
  779. nested = true;
  780. fs.appendFileSync(f.transcript, JSON.stringify({ type: "user", message: { content: "LATER_TURN ".repeat(40) } }) + "\n");
  781. processClaudeInput({ ...f.input, hook_event_name: "SessionEnd" }, { run });
  782. }
  783. return run(...args);
  784. } });
  785. const latest = readOutcome(f.root, "session");
  786. assert.equal(latest.attempt.source_event, "SessionEnd");
  787. assert.equal(latest.attempt.revision.size, fs.statSync(f.transcript).size);
  788. assert.notEqual(latest.attempt.extractors.input?.state, "skipped");
  789. assert.equal(fs.existsSync(path.join(f.root, ".locks", "session.pending.json")), false);
  790. });
  791. test("the dispatcher closes an attempt its killed writer left in progress", (t) => {
  792. const f = fixture(t);
  793. const projects = path.join(f.directory, "projects", "repo");
  794. fs.mkdirSync(projects, { recursive: true });
  795. const transcript = path.join(projects, "session.jsonl");
  796. fs.renameSync(f.transcript, transcript);
  797. const input = { ...f.input, transcript_path: transcript };
  798. const outcomeModule = new URL("../skills/recollect/scripts/hypomnesis-outcome.mjs", import.meta.url).href;
  799. const root = path.join(projects, "hypomnesis");
  800. fs.writeFileSync(path.join(f.directory, "hypomnesis-write.mjs"),
  801. `import { beginAttempt } from ${JSON.stringify(outcomeModule)};
  802. beginAttempt(${JSON.stringify(root)}, "session", { runtime: "claude", revision: null, source_transcript: ${JSON.stringify(transcript)}, source_event: "PreCompact" });
  803. process.exit(9);`);
  804. const previousWrite = process.stderr.write;
  805. try {
  806. process.stderr.write = () => true;
  807. dispatchHook(JSON.stringify(input), { env: { CLAUDE_CONFIG_DIR: f.directory }, scriptDir: f.directory });
  808. const orphan = readOutcome(root, "session");
  809. assert.equal(orphan.attempt.state, "complete");
  810. assert.equal(orphan.attempt.extractors.writer.state, "invocation_failed");
  811. fs.writeFileSync(path.join(f.directory, "hypomnesis-write.mjs"), "process.exit(3);");
  812. dispatchHook(JSON.stringify(input), { env: { CLAUDE_CONFIG_DIR: f.directory }, scriptDir: f.directory });
  813. } finally { process.stderr.write = previousWrite; }
  814. const later = readOutcome(root, "session");
  815. assert.equal(later.attempt.extractors.writer.evidence.status, 3);
  816. });
  817. test("a skip attempt does not make stale published bytes read as current", (t) => {
  818. const f = fixture(t);
  819. const published = processClaudeInput(f.input, { run: extractionRun(successfulOutputs()) });
  820. assert.equal(published.attempt.publication.state, "complete");
  821. fs.appendFileSync(f.transcript, JSON.stringify({ type: "user", message: { content: "grown" } }) + "\n");
  822. const skipped = processClaudeInput({ ...f.input, hook_event_name: "SessionEnd" }, { run: () => { throw new Error("cooldown must skip"); } });
  823. assert.equal(skipped.attempt.extractors.input.state, "skipped");
  824. assert.equal(skipped.source_changed, true);
  825. });
  826. test("a torn trailing line at the snapshot's end is not an input failure", (t) => {
  827. const f = fixture(t);
  828. fs.appendFileSync(f.transcript, '{"type":"user","message":{"content":"half wri');
  829. const result = processClaudeInput(f.input, { run: extractionRun(successfulOutputs()) });
  830. assert.equal(result.attempt.extractors.input, undefined);
  831. fs.appendFileSync(f.transcript, 'tten"}}\nmalformed middle\n' + JSON.stringify({ type: "user", message: { content: "after" } }) + "\n");
  832. fs.utimesSync(f.transcript, new Date(), new Date(Date.now() + 1000));
  833. const corrupt = processClaudeInput(f.input, { run: extractionRun(successfulOutputs()) });
  834. assert.equal(corrupt.attempt.extractors.input.state, "input_failed");
  835. });

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.