continuous-improvement 3.11.0 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/CHANGELOG.md +65 -1
  3. package/QUICKSTART.md +1 -1
  4. package/README.md +39 -18
  5. package/SKILL.md +1 -1
  6. package/bin/check-skill-count.mjs +32 -1
  7. package/bin/check-test-imports-only.mjs +1 -1
  8. package/bin/check-tool-count.mjs +129 -0
  9. package/bin/generate-plugin-manifests.mjs +3 -1
  10. package/bin/harvest-friction.mjs +1 -1
  11. package/bin/install.mjs +77 -3
  12. package/bin/mcp-server.mjs +66 -9
  13. package/bin/plan-pack.mjs +77 -0
  14. package/bin/unified-cli.mjs +55 -410
  15. package/commands/harvest.md +1 -1
  16. package/commands/model-forward.md +13 -0
  17. package/commands/production-readiness-review.md +53 -0
  18. package/commands/ship.md +57 -0
  19. package/commands/superpowers.md +1 -1
  20. package/hooks/companion-preference.mjs +31 -19
  21. package/hooks/gateguard.mjs +59 -25
  22. package/hooks/hook-pack.mjs +110 -0
  23. package/hooks/recall-briefing.mjs +167 -0
  24. package/lib/gateguard-state.mjs +62 -13
  25. package/lib/goal-state.mjs +13 -9
  26. package/lib/hook-pack-gate.mjs +65 -0
  27. package/lib/install-targets.mjs +121 -0
  28. package/lib/plan-review-packet.mjs +96 -0
  29. package/lib/plugin-metadata.mjs +33 -7
  30. package/lib/recall-briefing.mjs +57 -0
  31. package/lib/recall-index.mjs +2 -2
  32. package/lib/skill-distill.mjs +141 -0
  33. package/llms.txt +2 -2
  34. package/package.json +6 -4
  35. package/plugins/beginner.json +3 -3
  36. package/plugins/continuous-improvement/.claude-plugin/marketplace.json +2 -2
  37. package/plugins/continuous-improvement/.claude-plugin/plugin.json +2 -2
  38. package/plugins/continuous-improvement/README.md +1 -1
  39. package/plugins/continuous-improvement/agents/README.md +3 -3
  40. package/plugins/continuous-improvement/bin/mcp-server.mjs +66 -9
  41. package/plugins/continuous-improvement/commands/harvest.md +1 -1
  42. package/plugins/continuous-improvement/commands/model-forward.md +13 -0
  43. package/plugins/continuous-improvement/commands/production-readiness-review.md +53 -0
  44. package/plugins/continuous-improvement/commands/ship.md +57 -0
  45. package/plugins/continuous-improvement/commands/superpowers.md +1 -1
  46. package/plugins/continuous-improvement/hooks/companion-preference.mjs +31 -19
  47. package/plugins/continuous-improvement/hooks/gateguard.mjs +59 -25
  48. package/plugins/continuous-improvement/hooks/hook-pack.mjs +110 -0
  49. package/plugins/continuous-improvement/hooks/hooks.json +16 -1
  50. package/plugins/continuous-improvement/hooks/recall-briefing.mjs +167 -0
  51. package/plugins/continuous-improvement/lib/gateguard-state.mjs +62 -13
  52. package/plugins/continuous-improvement/lib/goal-state.mjs +13 -9
  53. package/plugins/continuous-improvement/lib/hook-pack-gate.mjs +65 -0
  54. package/plugins/continuous-improvement/lib/plugin-metadata.mjs +33 -7
  55. package/plugins/continuous-improvement/lib/recall-briefing.mjs +57 -0
  56. package/plugins/continuous-improvement/lib/recall-index.mjs +2 -2
  57. package/plugins/continuous-improvement/lib/skill-distill.mjs +141 -0
  58. package/plugins/continuous-improvement/skills/README.md +1 -1
  59. package/plugins/continuous-improvement/skills/continuous-improvement/SKILL.md +1 -1
  60. package/plugins/continuous-improvement/skills/gateguard/SKILL.md +4 -4
  61. package/plugins/continuous-improvement/skills/goal-monitor/SKILL.md +1 -1
  62. package/plugins/continuous-improvement/skills/handoff/SKILL.md +0 -1
  63. package/plugins/continuous-improvement/skills/model-forward/SKILL.md +44 -0
  64. package/plugins/continuous-improvement/skills/superpowers/SKILL.md +1 -1
  65. package/plugins/expert.json +6 -2
  66. package/skills/README.md +4 -2
  67. package/skills/gateguard.md +4 -4
  68. package/skills/goal-monitor.md +1 -1
  69. package/skills/handoff.md +0 -1
  70. package/skills/model-forward.md +44 -0
  71. package/skills/superpowers.md +1 -1
  72. package/lib/compound-engineering.mjs +0 -831
  73. package/lib/pm-skills.mjs +0 -1274
  74. package/lib/unified-plugin.mjs +0 -924
  75. package/plugins/continuous-improvement/skills/para-memory-files/SKILL.md +0 -108
  76. package/skills/para-memory-files.md +0 -108
@@ -2,20 +2,25 @@
2
2
  * Gateguard per-session state.
3
3
  *
4
4
  * State file: <sessionDir>/gateguard-session.json. sessionDir resolves to
5
- * GATEGUARD_SESSION_DIR (env override, used by tests) or
6
- * ~/.claude/instincts/<projectHash>/ in production.
5
+ * GATEGUARD_SESSION_DIR (env override, used by tests), or in production to
6
+ * ~/.claude/instincts/<projectHash>/sessions/<sessionId>/ when the hook passes
7
+ * the stdin session_id, falling back to ~/.claude/instincts/<projectHash>/ when
8
+ * no session id is available. Per-session scoping is what stops the clearance
9
+ * cap from bleeding across concurrent same-day sessions on a multi-Claude host.
7
10
  *
8
- * V1 limitations (documented for honesty, not mitigated in code):
11
+ * Limitations and guarantees:
9
12
  * - Honor system: clearance is granted whenever the agent sets
10
13
  * `_gateguard_facts_presented: true` in tool_input or has a prior per-file
11
14
  * marker. The hook cannot verify that real investigation occurred.
12
15
  * - State-file deletion: rm'ing the state file resets every gate in the
13
- * session. Defensible because the session itself is the trust boundary;
14
- * the cap below limits cumulative damage.
16
+ * session. Defensible because the session is the trust boundary — and with
17
+ * per-session scoping that boundary is now real, not just asserted.
18
+ * - Self-heal: loadState treats a file older than STATE_TTL_MS (or one with an
19
+ * unparseable created_at) as empty, so a stale gate never needs a manual rm.
15
20
  * - Concurrency: two parallel hook invocations can race the read+write.
16
21
  * Acceptable trade-off vs OS-specific atomic-rename complexity on Windows.
17
- * - Cap: MAX_CLEARED_FILES caps the number of distinct files a single
18
- * session can clear, bounding stuck-loop / rogue-agent damage.
22
+ * - Cap: MAX_CLEARED_FILES caps the distinct files ONE session can clear,
23
+ * bounding stuck-loop / rogue-agent damage without affecting other sessions.
19
24
  */
20
25
  import { createHash } from "node:crypto";
21
26
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
@@ -23,14 +28,36 @@ import { execFileSync } from "node:child_process";
23
28
  import { homedir } from "node:os";
24
29
  import { join } from "node:path";
25
30
  export const MAX_CLEARED_FILES = 50;
26
- export function resolveSessionDir() {
31
+ // A clearance file whose created_at is older than this self-heals to empty on
32
+ // the next load, so a stale gate never needs a manual rm. Long enough not to
33
+ // reset an active session mid-work; the real cross-session fix is the
34
+ // per-session dir in resolveSessionDir below.
35
+ export const STATE_TTL_MS = 12 * 60 * 60 * 1000; // 12h
36
+ // The root that holds every project's gateguard + instinct state. The MCP
37
+ // clearance route uses this to bound a caller-supplied state_path to this tree
38
+ // so a hostile argument can't turn the clear into an arbitrary-write primitive.
39
+ export function resolveInstinctsRoot() {
40
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
41
+ return join(home, ".claude", "instincts");
42
+ }
43
+ export function resolveSessionDir(sessionId) {
27
44
  const fromEnv = process.env.GATEGUARD_SESSION_DIR;
28
45
  if (fromEnv)
29
46
  return fromEnv;
30
- const home = process.env.HOME || process.env.USERPROFILE || homedir();
31
47
  const projectRoot = resolveProjectRoot();
32
48
  const projectHash = createHash("sha256").update(canonicalizeProjectRoot(projectRoot)).digest("hex").slice(0, 12);
33
- return join(home, ".claude", "instincts", projectHash);
49
+ const base = join(resolveInstinctsRoot(), projectHash);
50
+ const scoped = sanitizeSessionId(sessionId);
51
+ return scoped ? join(base, "sessions", scoped) : base;
52
+ }
53
+ // A session id flows into a directory name. Strip anything outside a safe
54
+ // alphabet so a hostile or malformed id can't traverse (`../`) or break the
55
+ // path, and cap the length. Returns "" for an absent/empty id, which the caller
56
+ // treats as "no session" — the legacy unscoped dir, preserving back-compat.
57
+ function sanitizeSessionId(sessionId) {
58
+ if (!sessionId)
59
+ return "";
60
+ return sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64);
34
61
  }
35
62
  function resolveProjectRoot() {
36
63
  const fromEnv = process.env.CLAUDE_PROJECT_DIR;
@@ -49,21 +76,43 @@ function resolveProjectRoot() {
49
76
  }
50
77
  return "global";
51
78
  }
79
+ function freshState() {
80
+ return { created_at: new Date().toISOString(), cleared_files: {} };
81
+ }
82
+ // A clearance file self-heals to empty once it ages out of STATE_TTL_MS, so a
83
+ // stale gate never needs a manual rm. An unparseable created_at fails closed
84
+ // (treated as expired) rather than living forever as a never-resetting gate.
85
+ function isExpired(createdAt) {
86
+ const created = Date.parse(createdAt);
87
+ if (Number.isNaN(created))
88
+ return true;
89
+ return Date.now() - created > STATE_TTL_MS;
90
+ }
52
91
  export function loadState(sessionDir) {
53
92
  const path = join(sessionDir, "gateguard-session.json");
54
93
  if (!existsSync(path)) {
55
- return { created_at: new Date().toISOString(), cleared_files: {} };
94
+ return freshState();
56
95
  }
57
96
  try {
58
97
  const raw = readFileSync(path, "utf8");
59
98
  const parsed = JSON.parse(raw);
99
+ // Absent created_at is treated as expired (fail closed), like an unparseable
100
+ // one — never a never-resetting gate. On expiry we persist the new epoch
101
+ // immediately so the cap re-applies from zero on the very next load;
102
+ // otherwise every load before the next clear would independently reset and a
103
+ // TTL-crossing session could clear well past MAX_CLEARED_FILES.
104
+ if (!parsed.created_at || isExpired(parsed.created_at)) {
105
+ const reset = freshState();
106
+ saveState(sessionDir, reset);
107
+ return reset;
108
+ }
60
109
  return {
61
- created_at: parsed.created_at ?? new Date().toISOString(),
110
+ created_at: parsed.created_at,
62
111
  cleared_files: parsed.cleared_files ?? {},
63
112
  };
64
113
  }
65
114
  catch {
66
- return { created_at: new Date().toISOString(), cleared_files: {} };
115
+ return freshState();
67
116
  }
68
117
  }
69
118
  export function saveState(sessionDir, state) {
@@ -19,11 +19,15 @@ const STOPWORDS = new Set([
19
19
  "make", "made", "adds", "new", "get", "got", "set", "also", "only", "each",
20
20
  "task", "goal", "plan", "work", "working", "build", "building", "code",
21
21
  ]);
22
- // 4 suits Latin/Cyrillic prose, but it silently drops most Korean/Thai words
23
- // (typically 2 chars) even though the Unicode splitter now keeps them — so the
24
- // goal-state half of the tokenizer fix is only partial for those scripts. A
25
- // script-aware floor is a logged follow-up (see CLAUDE.md Deferred).
22
+ // 4 suits Latin/Cyrillic/Thai prose (Thai combining marks are now kept; see
23
+ // extractKeywordsFromProse regex). Korean Hangul words are typically 2-3 chars
24
+ // but represent full concepts, so they get a script-aware floor of 2.
26
25
  const KEYWORD_MIN_LENGTH = 4;
26
+ function keywordMinLengthFor(word) {
27
+ if (/\p{Script=Hangul}/u.test(word))
28
+ return 2;
29
+ return KEYWORD_MIN_LENGTH;
30
+ }
27
31
  const KEYWORD_CAP = 20;
28
32
  const DEFAULT_WINDOW = 30;
29
33
  const DEFAULT_THRESHOLD = 0.3;
@@ -52,16 +56,16 @@ export function getSection(markdown, heading) {
52
56
  }
53
57
  /**
54
58
  * Tokenize prose into goal keywords: lowercase, split on any non-letter /
55
- * non-number (Unicode-aware, so accented Latin / Cyrillic / CJK survive), drop
56
- * stopwords, pure-digit tokens, and tokens shorter than KEYWORD_MIN_LENGTH.
57
- * Deduped, capped at KEYWORD_CAP.
59
+ * non-number / non-mark (Unicode-aware, so accented Latin / Cyrillic / CJK /
60
+ * Thai survive), drop stopwords, pure-digit tokens, and tokens shorter than
61
+ * KEYWORD_MIN_LENGTH. Deduped, capped at KEYWORD_CAP.
58
62
  */
59
63
  export function extractKeywordsFromProse(prose) {
60
64
  const seen = new Set();
61
65
  const out = [];
62
- for (const raw of prose.toLowerCase().split(/[^\p{L}\p{N}]+/u)) {
66
+ for (const raw of prose.toLowerCase().split(/[^\p{L}\p{N}\p{M}]+/u)) {
63
67
  const word = raw.trim();
64
- if (word.length < KEYWORD_MIN_LENGTH)
68
+ if (word.length < keywordMinLengthFor(word))
65
69
  continue;
66
70
  if (/^\p{N}+$/u.test(word))
67
71
  continue;
@@ -0,0 +1,65 @@
1
+ // hook-pack-gate.mts — Pure decision core for the enforcing-hook pack (v1).
2
+ //
3
+ // No I/O. Given a raw Bash command string, the resolved current branch, the
4
+ // staged-file count, and the operator's mode, decide allow / warn / block.
5
+ // The hook (src/hooks/hook-pack.mts) wires stdin + git subprocess calls around
6
+ // these functions; keeping them pure lets the unit tests cover every branch
7
+ // without spawning anything. Lives in lib/ so tests can import it (the
8
+ // test-imports-only invariant forbids importing from hooks/).
9
+ //
10
+ // Fail-open by construction: callers pass safe defaults (null branch, 0 staged)
11
+ // on any failure, and an unrecognized mode resolves to warn.
12
+ export const COMMIT_FILE_LIMIT = 15;
13
+ const ALLOW = { action: "allow", reason: "" };
14
+ export function parseMode(raw) {
15
+ const v = (raw ?? "warn").trim().toLowerCase();
16
+ return v === "block" || v === "off" ? v : "warn";
17
+ }
18
+ // Match `git push` / `git commit` at the start of the command or immediately
19
+ // after a shell separator (newline, ;, |, &). This deliberately does NOT match
20
+ // a mention like `echo git push`, where git is an argument, not the command.
21
+ export function classifyCommand(command) {
22
+ if (/(?:^|[\n;|&])\s*git\s+push\b/.test(command))
23
+ return "push";
24
+ if (/(?:^|[\n;|&])\s*git\s+commit\b/.test(command))
25
+ return "commit";
26
+ return "other";
27
+ }
28
+ export function isProtectedBranch(branch) {
29
+ return branch === "main" || branch === "master" || /^release\//.test(branch);
30
+ }
31
+ // Extract the explicit destination branch of a `git push`, or null when none is
32
+ // given (the caller should then fall back to the current branch). Handles
33
+ // `git push <remote> <branch>`, `git push -u <remote> <branch>`, and refspecs
34
+ // like `HEAD:main` (destination after the colon).
35
+ function parsePushTarget(command) {
36
+ const tokens = command.split(/\s+/).filter(Boolean);
37
+ const pushIdx = tokens.findIndex((t, i) => t === "push" && tokens[i - 1] === "git");
38
+ if (pushIdx === -1)
39
+ return null;
40
+ const operands = tokens.slice(pushIdx + 1).filter((t) => !t.startsWith("-"));
41
+ // operands[0] is the remote; operands[1] is the refspec. Fewer than two means
42
+ // no explicit branch (e.g. `git push` or `git push origin`).
43
+ if (operands.length < 2)
44
+ return null;
45
+ const refspec = operands[1];
46
+ return refspec.includes(":") ? (refspec.split(":").pop() ?? null) : refspec;
47
+ }
48
+ export function evaluatePush(command, currentBranch) {
49
+ if (/(?:^|\s)--dry-run\b/.test(command))
50
+ return { gated: false, branch: null };
51
+ const branch = parsePushTarget(command) ?? currentBranch;
52
+ if (!branch)
53
+ return { gated: false, branch: null };
54
+ return { gated: isProtectedBranch(branch), branch };
55
+ }
56
+ export function evaluateCommitSize(command, stagedCount) {
57
+ if (/(?:^|\s)--amend\b/.test(command))
58
+ return { gated: false };
59
+ return { gated: stagedCount > COMMIT_FILE_LIMIT };
60
+ }
61
+ export function decide(mode, gated, reason) {
62
+ if (!gated || mode === "off")
63
+ return ALLOW;
64
+ return { action: mode === "block" ? "block" : "warn", reason };
65
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Multi-platform install targets for the 7-Laws skill.
3
+ *
4
+ * Pure planning layer — no filesystem access. The installer
5
+ * (src/bin/install.mts) feeds in the SKILL.md text plus a reader callback and
6
+ * executes the returned write plan against the project root. Keeping this
7
+ * pure lets the per-target contracts be unit-tested without temp dirs.
8
+ *
9
+ * v1 contract (docs/plans/2026-06-11-multi-platform-installer.md):
10
+ * - Non-Claude targets receive the skill text only; hooks, the MCP server,
11
+ * and instinct learning stay Claude Code-only and every plan says so.
12
+ * - Shared files (GEMINI.md, AGENTS.md, .rules, CONVENTIONS.md,
13
+ * copilot-instructions.md) are merged through a managed block so existing
14
+ * user content is never clobbered and reinstalls are idempotent.
15
+ * - Own-file targets (cursor, windsurf) are written whole.
16
+ */
17
+ export const MANAGED_BEGIN = "<!-- continuous-improvement:begin (managed block — reinstall via `npx continuous-improvement install --target <name>`; edits inside are overwritten) -->";
18
+ export const MANAGED_END = "<!-- continuous-improvement:end -->";
19
+ const TARGET_SPECS = {
20
+ gemini: { label: "Gemini CLI", mode: "managed", relPath: "GEMINI.md" },
21
+ codex: { label: "Codex CLI (agents.md standard)", mode: "managed", relPath: "AGENTS.md" },
22
+ cursor: { label: "Cursor", mode: "whole", relPath: ".cursor/rules/continuous-improvement.mdc" },
23
+ windsurf: { label: "Windsurf", mode: "whole", relPath: ".windsurf/rules/continuous-improvement.md" },
24
+ zed: { label: "Zed", mode: "managed", relPath: ".rules" },
25
+ aider: { label: "Aider", mode: "managed", relPath: "CONVENTIONS.md" },
26
+ copilot: { label: "GitHub Copilot", mode: "managed", relPath: ".github/copilot-instructions.md" },
27
+ };
28
+ export const TARGET_IDS = ["claude", ...Object.keys(TARGET_SPECS)];
29
+ export function resolveTargets(csv) {
30
+ const targets = [];
31
+ const unknown = [];
32
+ for (const raw of csv.split(",")) {
33
+ const name = raw.trim().toLowerCase();
34
+ if (name === "")
35
+ continue;
36
+ if (!TARGET_IDS.includes(name)) {
37
+ if (!unknown.includes(name))
38
+ unknown.push(name);
39
+ continue;
40
+ }
41
+ if (!targets.includes(name))
42
+ targets.push(name);
43
+ }
44
+ return { targets, unknown };
45
+ }
46
+ export function stripFrontmatter(skillMd) {
47
+ if (!skillMd.startsWith("---\n") && !skillMd.startsWith("---\r\n"))
48
+ return skillMd;
49
+ const close = skillMd.indexOf("\n---", 3);
50
+ if (close === -1)
51
+ return skillMd;
52
+ const afterClose = skillMd.indexOf("\n", close + 1);
53
+ if (afterClose === -1)
54
+ return "";
55
+ return skillMd.slice(afterClose + 1).replace(/^\s*\n/, "");
56
+ }
57
+ export function mergeManagedBlock(existing, block) {
58
+ if (existing === null || existing.trim() === "") {
59
+ return `${block}\n`;
60
+ }
61
+ const beginAt = existing.indexOf(MANAGED_BEGIN);
62
+ const endAt = existing.indexOf(MANAGED_END);
63
+ if (beginAt !== -1 && endAt !== -1 && endAt > beginAt) {
64
+ const before = existing.slice(0, beginAt);
65
+ const after = existing.slice(endAt + MANAGED_END.length);
66
+ return `${before}${block}${after}`;
67
+ }
68
+ return `${existing.trimEnd()}\n\n${block}\n`;
69
+ }
70
+ function renderManagedBlock(skillMd) {
71
+ return `${MANAGED_BEGIN}\n${stripFrontmatter(skillMd).trim()}\n${MANAGED_END}`;
72
+ }
73
+ function renderCursorRule(skillMd) {
74
+ return [
75
+ "---",
76
+ "description: 7 Laws of AI Agent Discipline — continuous-improvement framework",
77
+ "alwaysApply: true",
78
+ "---",
79
+ "",
80
+ stripFrontmatter(skillMd).trim(),
81
+ "",
82
+ ].join("\n");
83
+ }
84
+ const AIDER_CONF_PATH = ".aider.conf.yml";
85
+ const AIDER_MINIMAL_CONF = [
86
+ "# Written by `npx continuous-improvement install --target aider`.",
87
+ "# Loads the 7 Laws conventions into every Aider session.",
88
+ "read: [CONVENTIONS.md]",
89
+ "",
90
+ ].join("\n");
91
+ export function planTargetWrites(targetId, skillMd, readExisting) {
92
+ if (targetId === "claude") {
93
+ throw new Error("claude is handled by the standard installer flow, not planTargetWrites");
94
+ }
95
+ const spec = TARGET_SPECS[targetId];
96
+ if (!spec) {
97
+ throw new Error(`Unknown install target: ${targetId}. Valid: ${TARGET_IDS.join(", ")}`);
98
+ }
99
+ const writes = [];
100
+ const notes = [
101
+ `${spec.label} gets the 7-Laws skill text only — hooks, the MCP server, and instinct learning are Claude Code-only.`,
102
+ ];
103
+ if (spec.mode === "whole") {
104
+ const content = targetId === "cursor" ? renderCursorRule(skillMd) : `${stripFrontmatter(skillMd).trim()}\n`;
105
+ writes.push({ relPath: spec.relPath, content });
106
+ }
107
+ else {
108
+ const block = renderManagedBlock(skillMd);
109
+ writes.push({ relPath: spec.relPath, content: mergeManagedBlock(readExisting(spec.relPath), block) });
110
+ }
111
+ if (targetId === "aider") {
112
+ const existingConf = readExisting(AIDER_CONF_PATH);
113
+ if (existingConf === null) {
114
+ writes.push({ relPath: AIDER_CONF_PATH, content: AIDER_MINIMAL_CONF });
115
+ }
116
+ else {
117
+ notes.push(`${AIDER_CONF_PATH} already exists — add CONVENTIONS.md to its \`read:\` list yourself (e.g. \`read: [CONVENTIONS.md]\`); the installer never rewrites an existing conf.`);
118
+ }
119
+ }
120
+ return { notes, writes };
121
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * plan-review-packet: turn a plan doc into a commentable review packet.
3
+ *
4
+ * Pure markdown transform — no IO. Splits a `docs/plans/*.md` plan into
5
+ * anchored sections, extracts a TLDR, and renders a packet a reviewer can
6
+ * comment on inline (one `> Comment (R#):` slot per section).
7
+ */
8
+ const TLDR_HEADINGS = new Set(["goal", "summary", "overview", "tldr"]);
9
+ const HEADING_RE = /^(#{1,6})\s+(.*\S)\s*$/;
10
+ function normalize(markdown) {
11
+ return markdown.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
12
+ }
13
+ /** Split a plan into reviewable level-2/3 sections, each with a stable [R#] anchor. */
14
+ export function splitSections(markdown) {
15
+ const lines = normalize(markdown).split("\n");
16
+ const sections = [];
17
+ let current = null;
18
+ let counter = 0;
19
+ const flush = () => {
20
+ if (!current)
21
+ return;
22
+ counter += 1;
23
+ sections.push({
24
+ heading: current.heading,
25
+ level: current.level,
26
+ anchor: `R${counter}`,
27
+ body: current.body.join("\n").trim(),
28
+ });
29
+ current = null;
30
+ };
31
+ for (const line of lines) {
32
+ const match = HEADING_RE.exec(line);
33
+ const level = match ? match[1].length : 0;
34
+ if (level === 1) {
35
+ flush();
36
+ }
37
+ else if (level === 2 || level === 3) {
38
+ flush();
39
+ current = { heading: match[2].trim(), level, body: [] };
40
+ }
41
+ else if (current) {
42
+ current.body.push(line);
43
+ }
44
+ }
45
+ flush();
46
+ return sections;
47
+ }
48
+ /** First non-empty, non-heading paragraph of a block of markdown. */
49
+ function firstParagraph(text) {
50
+ for (const block of text.split(/\n\s*\n/)) {
51
+ const kept = block
52
+ .split("\n")
53
+ .map((l) => l.trim())
54
+ .filter((l) => l.length > 0 && !/^#{1,6}(\s|$)/.test(l));
55
+ if (kept.length > 0)
56
+ return kept.join("\n");
57
+ }
58
+ return "";
59
+ }
60
+ /** Extract a one-glance TLDR: a Goal/Summary/Overview section, else the first paragraph. */
61
+ export function extractTldr(markdown) {
62
+ const goal = splitSections(markdown).find((s) => TLDR_HEADINGS.has(s.heading.trim().toLowerCase()));
63
+ if (goal)
64
+ return firstParagraph(goal.body);
65
+ return firstParagraph(normalize(markdown));
66
+ }
67
+ function extractTitle(markdown) {
68
+ for (const line of normalize(markdown).split("\n")) {
69
+ const match = /^#\s+(.*\S)\s*$/.exec(line);
70
+ if (match)
71
+ return match[1].trim();
72
+ }
73
+ return "Plan Review";
74
+ }
75
+ /** Render a commentable review packet from a plan doc. */
76
+ export function buildReviewPacket(markdown, options = {}) {
77
+ const title = extractTitle(markdown);
78
+ const tldr = extractTldr(markdown);
79
+ const sections = splitSections(markdown);
80
+ const out = [`# Review packet: ${title}`, ""];
81
+ if (options.source)
82
+ out.push(`Source: ${options.source}`);
83
+ out.push(`TLDR: ${tldr || "(none — skim the sections below)"}`, "");
84
+ out.push("> How to comment: reply under each `> Comment (R#):` line. The `[R#]` anchors are stable references you can cite back.", "", "---", "");
85
+ if (sections.length === 0) {
86
+ out.push("_No reviewable sections found in this plan._", "");
87
+ return out.join("\n");
88
+ }
89
+ for (const section of sections) {
90
+ out.push(`${"#".repeat(section.level)} ${section.heading} [${section.anchor}]`, "");
91
+ if (section.body)
92
+ out.push(section.body, "");
93
+ out.push(`> Comment (${section.anchor}):`, "");
94
+ }
95
+ return out.join("\n");
96
+ }
@@ -26,7 +26,7 @@ const KEYWORDS = [
26
26
  "transcript-linter",
27
27
  ];
28
28
  const CLAUDE_PLUGIN_CATEGORY = "productivity";
29
- const SHARED_PLUGIN_DESCRIPTION = "Stops Claude Code from skipping research, claiming 'done' without verifying, and repeating yesterday's mistakes. The 7 Laws of AI Agent Discipline 25 bundled skills, gating hooks, the Mulahazah auto-leveling instinct engine, and a GitHub Action transcript linter.";
29
+ const SHARED_PLUGIN_DESCRIPTION = "The persistent-memory and runtime-discipline layer for Claude Code. It remembers the corrections you already gave, grounds every edit in real facts before it lands, and through the Mulahazah engine — turns each fix into a reusable instinct, so a lesson learned once is applied automatically next time with no re-teaching. Built on the 7 Laws of AI Agent Discipline (research, plan, verify, reflect, learn) and shipped as 25 bundled skills, instinct-aware hooks, an MCP toolset for recall and reflection, and a GitHub Action transcript linter that feeds real work history back into sharper instincts.";
30
30
  // Four vendored upstream companions registered alongside the CI plugin.
31
31
  // Each entry points at a pinned-SHA snapshot under third-party/<name>/.
32
32
  // See third-party/MANIFEST.md for refresh recipes and per-snapshot
@@ -76,7 +76,7 @@ const THIRD_PARTY_COMPANIONS = [
76
76
  },
77
77
  {
78
78
  name: "oh-my-claudecode",
79
- description: "Multi-agent orchestration system for Claude Code — 39 skills + 19 agents covering audit, plan, build, verify, ship, release, retrospective, and ops. Includes ralph (autonomous PRD loop), release, ultrawork, ultraqa, team, trace, visual-verdict, debug, deep-dive, deep-interview, autopilot, autoresearch. Vendored snapshot at third-party/oh-my-claudecode/ pinned to upstream SHA aacde3e (v4.13.6). Heavy overlap with continuous-improvement /ralph and /superpowers — pick per task.",
79
+ description: "Multi-agent orchestration system for Claude Code — 38 skills + 19 agents covering audit, plan, build, verify, ship, release, retrospective, and ops. Includes ralph (autonomous PRD loop), release, ultrawork, ultraqa, team, trace, visual-verdict, debug, deep-dive, deep-interview, autopilot, autoresearch. Vendored snapshot at third-party/oh-my-claudecode/ pinned to upstream SHA aacde3e (v4.13.6). Heavy overlap with continuous-improvement /ralph and /superpowers — pick per task.",
80
80
  version: "4.13.6",
81
81
  source: "./third-party/oh-my-claudecode",
82
82
  author: {
@@ -143,6 +143,10 @@ const BEGINNER_TOOL_ENTRIES = [
143
143
  type: "string",
144
144
  description: "A single file path to clear (alternative to file_paths)",
145
145
  },
146
+ state_path: {
147
+ type: "string",
148
+ description: "State-file path from the GateGuard block reason (the session-scoped gateguard-session.json). Pass it verbatim so the clearance lands in the session the hook is reading; it must resolve inside ~/.claude/instincts/. Omitting it falls back to the unscoped canonical dir — safe only in legacy (no session id) contexts; when the hook is session-scoped, omitting it writes to the wrong dir and the retry will still block.",
149
+ },
146
150
  },
147
151
  required: [],
148
152
  },
@@ -373,15 +377,21 @@ const EXPERT_TOOL_ENTRIES = [
373
377
  required: ["id"],
374
378
  },
375
379
  },
380
+ {
381
+ name: "ci_distill_from_workflow",
382
+ description: "Draft a reusable instinct from the most recent completed-and-verified native Workflow run in this project's observation feed. A Workflow script is an authored recipe, so a single run whose output passed verification is enough — unlike ci_distill_candidates, which needs a pattern repeated across sessions. Writes a DRAFT to drafts/ (a skeleton you edit); it changes no behavior until promoted with ci_distill_promote. Returns a message when no verified workflow run is found.",
383
+ manifestWhat: "Draft a reusable instinct from a verified Workflow run",
384
+ inputSchema: { type: "object", properties: {}, required: [] },
385
+ },
376
386
  ];
377
387
  const MODE_METADATA = {
378
388
  beginner: {
379
- description: "Beginner mode: see what your agent learned, list its instincts, and request a session reflection. Bundles four discipline skills (gateguard, para-memory-files, tdd-workflow, verification-loop) so research, memory, tests, and verification happen by default.",
389
+ description: "Beginner mode: see what your agent learned, list its instincts, and request a session reflection. Bundles three grounding skills (gateguard, tdd-workflow, verification-loop) so research, memory, tests, and verification happen by default — every edit starts from facts, not guesses.",
380
390
  hooks: ["PreToolUse", "PostToolUse", "UserPromptSubmit"],
381
- hookDescription: "Silently captures every tool call as observations and routes prompts to the matching discipline skill via the route table. Lightweight and non-blocking.",
391
+ hookDescription: "Silently captures every tool call as observations and routes prompts to the matching skill via the route table. Lightweight and non-blocking.",
382
392
  },
383
393
  expert: {
384
- description: "Expert mode: tune confidence, manage instincts, and persist plans on disk. Adds safety, token-budget, and strategic-compact skills plus the /learn-eval command so long sessions stay disciplined and learnings survive context resets.",
394
+ description: "Expert mode: tune confidence, manage instincts, and persist plans on disk. Adds safety, token-budget, and strategic-compact skills plus the /learn-eval command so long sessions stay sharp and learnings survive context resets.",
385
395
  hooks: ["PreToolUse", "PostToolUse", "UserPromptSubmit", "SessionStart", "SessionEnd"],
386
396
  hookDescription: "Full hook suite: observation capture, lazy prompt routing, session-level instinct loading, and auto-reflection.",
387
397
  },
@@ -457,6 +467,11 @@ export function getPluginHooksConfig() {
457
467
  command: "node \"${CLAUDE_PLUGIN_ROOT}/hooks/companion-preference.mjs\"",
458
468
  timeout: 5,
459
469
  };
470
+ const hookPackCommand = {
471
+ type: "command",
472
+ command: "node \"${CLAUDE_PLUGIN_ROOT}/hooks/hook-pack.mjs\"",
473
+ timeout: 5,
474
+ };
460
475
  const observeCommand = {
461
476
  type: "command",
462
477
  command: "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/observe.sh\"",
@@ -482,8 +497,13 @@ export function getPluginHooksConfig() {
482
497
  command: "node \"${CLAUDE_PLUGIN_ROOT}/hooks/route-prompt.mjs\"",
483
498
  timeout: 5,
484
499
  };
500
+ const recallBriefingCommand = {
501
+ type: "command",
502
+ command: "node \"${CLAUDE_PLUGIN_ROOT}/hooks/recall-briefing.mjs\"",
503
+ timeout: 5,
504
+ };
485
505
  return {
486
- description: "Gateguard fact-forcing PreToolUse, companion-preference enforcement, observation, session lifecycle, 3-section-close discipline, goal-drift Stop gate, and UserPromptSubmit lazy-routing hooks for continuous-improvement.",
506
+ description: "Gateguard fact-forcing PreToolUse, companion-preference enforcement, observation, session lifecycle, 3-section-close discipline, goal-drift Stop gate, and UserPromptSubmit lazy-routing plus opt-in proactive recall-briefing hooks for continuous-improvement.",
487
507
  hooks: {
488
508
  // gateguard runs FIRST on PreToolUse so its block decision short-circuits
489
509
  // before companion-preference sees the call. companion-preference runs
@@ -496,9 +516,15 @@ export function getPluginHooksConfig() {
496
516
  // through with no output.
497
517
  PreToolUse: [
498
518
  { hooks: [gateguardCommand, companionPreferenceCommand] },
519
+ // hook-pack gates Bash `git push` to protected branches and oversized
520
+ // `git commit`s. The "Bash" matcher scopes it off the hot path for all
521
+ // non-Bash tools, so the two-subprocess note above still holds for
522
+ // Edit/Read/etc. Warn-default (CLAUDE_CI_HOOKPACK_GATE) — never blocks
523
+ // until the operator opts in.
524
+ { matcher: "Bash", hooks: [hookPackCommand] },
499
525
  ],
500
526
  PostToolUse: [{ hooks: [observeCommand] }],
501
- UserPromptSubmit: [{ hooks: [routePromptCommand] }],
527
+ UserPromptSubmit: [{ hooks: [routePromptCommand, recallBriefingCommand] }],
502
528
  SessionStart: [{ hooks: [sessionCommand] }],
503
529
  SessionEnd: [{ hooks: [sessionCommand] }],
504
530
  Stop: [{ hooks: [threeSectionCloseCommand, goalDriftStopCommand] }],
@@ -0,0 +1,57 @@
1
+ // recall-briefing.mts — Pure decision core for the proactive recall-briefing hook.
2
+ //
3
+ // No I/O. Given (enabled, already-briefed, prompt, ranked recall hits), decides
4
+ // whether to inject a one-time-per-session "you've touched related work before"
5
+ // system-reminder and renders it. The hook (src/hooks/recall-briefing.mts) does
6
+ // the filesystem work — read the prompt, read observations.jsonl, build the BM25
7
+ // index (recall-index.mts), track per-session state — then calls decideBriefing.
8
+ // Keeping the decision pure lets the unit tests cover every gate and boundary
9
+ // (disabled / already-briefed / empty-or-short prompt / no hits / malformed
10
+ // input) without touching the filesystem, per the repo lesson that green gates
11
+ // do not prove boundary safety.
12
+ //
13
+ // This is an amplifier, not a gate: it never blocks a prompt. It only surfaces
14
+ // prior context so the agent reuses a past fix instead of re-deriving it. It is
15
+ // opt-in (the hook checks an env flag) and fires at most once per session.
16
+ export const DEFAULT_MAX_HITS = 3;
17
+ export const DEFAULT_MIN_PROMPT_LENGTH = 12;
18
+ /** Render ranked hits as a compact UserPromptSubmit system-reminder. Pure string. */
19
+ export function formatBriefing(hits) {
20
+ const lines = [
21
+ "<system-reminder>",
22
+ "Recall briefing: this project has prior sessions that touched related work. Before re-deriving a fix, consider the `ci_recall` MCP tool (or `/recall`) for full context. Most relevant past activity:",
23
+ ];
24
+ for (const h of hits) {
25
+ const stamp = h && h.ts ? `[${h.ts}] ` : "";
26
+ const tool = (h && h.tool) || "(tool?)";
27
+ const snippet = ((h && h.snippet) || "").replace(/\s+/g, " ").trim();
28
+ lines.push(`- ${stamp}${tool}: ${snippet || "(no summary)"}`);
29
+ }
30
+ lines.push("</system-reminder>");
31
+ return lines.join("\n");
32
+ }
33
+ /**
34
+ * Decide whether to inject a recall briefing. Fails closed: any disabling
35
+ * condition (opted out, already briefed, prompt below the noise floor, no hits,
36
+ * malformed input) returns shouldBrief=false and never throws.
37
+ */
38
+ export function decideBriefing(params) {
39
+ const none = { shouldBrief: false, reminder: null };
40
+ if (!params || params.enabled !== true)
41
+ return none;
42
+ if (params.alreadyBriefed === true)
43
+ return none;
44
+ const prompt = typeof params.prompt === "string" ? params.prompt : "";
45
+ const minLen = typeof params.minPromptLength === "number" && params.minPromptLength >= 0
46
+ ? params.minPromptLength
47
+ : DEFAULT_MIN_PROMPT_LENGTH;
48
+ if (prompt.trim().length < minLen)
49
+ return none;
50
+ const maxHits = typeof params.maxHits === "number" && params.maxHits > 0
51
+ ? Math.floor(params.maxHits)
52
+ : DEFAULT_MAX_HITS;
53
+ const hits = Array.isArray(params.hits) ? params.hits.slice(0, maxHits) : [];
54
+ if (hits.length === 0)
55
+ return none;
56
+ return { shouldBrief: true, reminder: formatBriefing(hits) };
57
+ }
@@ -19,10 +19,10 @@ const BM25_K1 = 1.5;
19
19
  const BM25_B = 0.75;
20
20
  const DEFAULT_K = 5;
21
21
  const SNIPPET_RADIUS = 60;
22
- /** Lowercase, split on any non-letter / non-number (Unicode-aware), drop stopwords and tokens shorter than TOKEN_MIN_LENGTH. */
22
+ /** Lowercase, split on any non-letter / non-number / non-mark (Unicode-aware), drop stopwords and tokens shorter than TOKEN_MIN_LENGTH. */
23
23
  export function tokenize(text) {
24
24
  const out = [];
25
- for (const raw of text.toLowerCase().split(/[^\p{L}\p{N}]+/u)) {
25
+ for (const raw of text.toLowerCase().split(/[^\p{L}\p{N}\p{M}]+/u)) {
26
26
  if (raw.length < TOKEN_MIN_LENGTH)
27
27
  continue;
28
28
  if (STOPWORDS.has(raw))