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
+ }
@@ -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))
@@ -220,3 +220,144 @@ export function formatCandidates(candidates, limit = 10) {
220
220
  }
221
221
  return lines.join("\n");
222
222
  }
223
+ // ── Workflow-run → instinct bridge ───────────────────────────────────────────
224
+ // A native Workflow run (Opus 4.8 orchestration / ultracode) is recorded in the
225
+ // observation feed as a `tool: "Workflow"` row whose input_summary holds
226
+ // {"script":"..."} — truncated (~500 chars), but meta.name/description/phases sit
227
+ // at the head of the script and survive. The output_summary holds
228
+ // {"status","runId",...} with status "async_launched": the feed captures the
229
+ // LAUNCH, not the result. So a workflow's success is never read from the Workflow
230
+ // row itself — it is inferred from a following verify-exit-0 in the same feed.
231
+ //
232
+ // Unlike findCandidates (which needs a pattern recurring across >=2 sessions to
233
+ // reject coincidence), a Workflow script is an AUTHORED recipe: one verified run
234
+ // warrants a draft, so the session/occurrence thresholds do not apply here.
235
+ const WORKFLOW_TOOL = "Workflow";
236
+ // Pull meta.name / meta.description / meta.phases[].title out of a (possibly
237
+ // truncated) workflow script embedded as JSON in the observation input_summary.
238
+ // Fail-closed: returns null unless a name is recoverable — a recipe with no
239
+ // identity is never fabricated.
240
+ function parseWorkflowScript(inputSummary) {
241
+ if (!inputSummary)
242
+ return null;
243
+ let script = "";
244
+ try {
245
+ const parsed = JSON.parse(inputSummary);
246
+ if (typeof parsed.script === "string")
247
+ script = parsed.script;
248
+ }
249
+ catch {
250
+ // input_summary may itself be truncated mid-JSON; recover the script field loosely.
251
+ const m = inputSummary.match(/"script"\s*:\s*"((?:[^"\\]|\\.)*)/);
252
+ if (m) {
253
+ try {
254
+ script = JSON.parse(`"${m[1]}"`);
255
+ }
256
+ catch {
257
+ script = m[1].replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\'/g, "'");
258
+ }
259
+ }
260
+ }
261
+ if (!script)
262
+ return null;
263
+ // Scope name/description to the meta head (text before `phases:`) so a phase
264
+ // object's own description: is never mistaken for meta.description; scope phase
265
+ // titles to the phases array literal so inline agent/step title: fields are not
266
+ // captured. The capture classes exclude quotes and newlines, so a hostile
267
+ // name/description cannot inject lines into the draft YAML — serializeDraft emits
268
+ // trigger as a quoted scalar.
269
+ const phasesAt = script.search(/\bphases\s*:/);
270
+ const metaHead = phasesAt >= 0 ? script.slice(0, phasesAt) : script;
271
+ const name = (metaHead.match(/\bname\s*:\s*['"]([^'"\r\n]+)['"]/) ?? [])[1] ?? "";
272
+ if (!name)
273
+ return null; // fail closed: no recipe identity
274
+ const description = (metaHead.match(/\bdescription\s*:\s*['"]([^'"\r\n]+)['"]/) ?? [])[1] ?? "";
275
+ const phasesBlock = (script.match(/\bphases\s*:\s*\[([^\]]*)\]/) ?? [])[1] ?? "";
276
+ const phases = [];
277
+ const phaseRe = /\btitle\s*:\s*['"]([^'"\r\n]+)['"]/g;
278
+ let pm;
279
+ while ((pm = phaseRe.exec(phasesBlock)) !== null)
280
+ phases.push(pm[1]);
281
+ return { name, description, phases };
282
+ }
283
+ // A single verify-exit-0 Bash row: a verify/test/build command whose output is not
284
+ // failing. Mirrors classifyTrajectorySuccess's verify branch for one observation.
285
+ function isVerifySuccessRow(observation) {
286
+ if ((observation.tool ?? "") !== "Bash")
287
+ return false;
288
+ const input = (observation.input_summary ?? "").toString();
289
+ const output = (observation.output_summary ?? "").toString();
290
+ return VERIFY_CMD.test(input) && !FAILURE_MARKER.test(output) && (output === "" || SUCCESS_MARKER.test(output));
291
+ }
292
+ /**
293
+ * Detect the most recent completed-and-verified Workflow run in an observation
294
+ * list. Returns null (fail closed) unless: a `tool: "Workflow"` row carries a
295
+ * parseable script with a name, AND a verify-exit-0 row follows it in the feed.
296
+ * The trailing verify is the only success signal — the Workflow row records the
297
+ * launch, never the result.
298
+ */
299
+ export function workflowRunFromObservations(observations) {
300
+ let wfIndex = -1;
301
+ let meta = null;
302
+ for (let i = observations.length - 1; i >= 0; i -= 1) {
303
+ if ((observations[i].tool ?? "") !== WORKFLOW_TOOL)
304
+ continue;
305
+ const parsed = parseWorkflowScript((observations[i].input_summary ?? "").toString());
306
+ if (parsed) {
307
+ wfIndex = i;
308
+ meta = parsed;
309
+ break;
310
+ }
311
+ }
312
+ if (wfIndex === -1 || !meta)
313
+ return null;
314
+ const wfSession = (observations[wfIndex].session ?? "").toString();
315
+ // The verify that proves the run must follow the Workflow row in the SAME session.
316
+ // A verify from an unrelated later task (different session) does not count — the
317
+ // run is asynchronous, so an interleaved verify could otherwise falsely prove it.
318
+ let verifyCommand = "";
319
+ for (let i = wfIndex + 1; i < observations.length; i += 1) {
320
+ const row = observations[i];
321
+ if ((row.session ?? "").toString() !== wfSession)
322
+ continue;
323
+ if (isVerifySuccessRow(row)) {
324
+ verifyCommand = (row.input_summary ?? "").toString();
325
+ break;
326
+ }
327
+ }
328
+ if (!verifyCommand)
329
+ return null; // fail closed: no evidence the run's output landed
330
+ return { name: meta.name, description: meta.description, phases: meta.phases, verifyCommand };
331
+ }
332
+ /**
333
+ * Turn a verified Workflow run into a DRAFT instinct. The script's phase outline is
334
+ * a real skeleton (not a placeholder n-gram), but the human still edits the body
335
+ * before promoting. Reuses serializeDraft and the drafts/ ladder; the
336
+ * `draft-workflow-` id prefix marks the source and stays filesystem-safe.
337
+ */
338
+ export function draftFromWorkflowRun(run) {
339
+ // Cap the slug so a hostile/huge meta.name cannot produce a path that trips
340
+ // ENAMETOOLONG on write; strip a trailing hyphen left by the cut.
341
+ const slug = slugifyNgram([run.name]).slice(0, 120).replace(/-+$/, "") || "workflow";
342
+ const phaseLine = run.phases.length > 0 ? run.phases.join(" → ") : "(phases not captured)";
343
+ const lines = [
344
+ `When this situation recurs, the workflow "${run.name}" handled it end to end and its output passed verification.`,
345
+ "",
346
+ ];
347
+ if (run.description)
348
+ lines.push(`Intent: ${run.description}`);
349
+ lines.push(`Phases: ${phaseLine}`);
350
+ lines.push(`Verified by: ${run.verifyCommand}`);
351
+ lines.push("", "Replace this with the concrete steps, preconditions, and gotchas before promoting —", "the phase outline is the skeleton, not the full recipe.");
352
+ return {
353
+ id: `draft-workflow-${slug}`,
354
+ trigger: `Auto-detected from a verified workflow run: ${run.name}${run.description ? ` — ${run.description}` : ""}`,
355
+ body: lines.join("\n"),
356
+ confidence: DRAFT_CONFIDENCE,
357
+ domain: "workflow",
358
+ ngram: run.phases.length > 0 ? run.phases : [run.name],
359
+ occurrences: 1,
360
+ sessions: 1,
361
+ outcome: "workflow-verified",
362
+ };
363
+ }
@@ -18,7 +18,7 @@ skill set on disk.
18
18
  ## Tier 1 — beginner-mode pairing
19
19
  - `deploy-receipt` — Enforces Law 4 (Verify Before Reporting) of the 7 Laws of AI Agent Discipline at the deploy seam. A merge into a branch that auto-deploys is not "done" until the deploy provider reports the merged commit SHA running and a healthcheck endpoint returns 200. Companion to the vendored `finishing-a-development-branch` skill — does not replace it, runs after it for projects on Railway, Cloudflare Workers, Vercel, Netlify, Fly.io, or any other auto-deploy target.
20
20
  - `gateguard` — Enforces Law 1 (Research Before Executing) of the 7 Laws of AI Agent Discipline. Fact-forcing gate that blocks Edit/Write/Bash (including MultiEdit) and demands concrete investigation (importers, data schemas, user instruction) before allowing the action. Measurably improves output quality by +2.25 points vs ungated agents.
21
- - `para-memory-files` — Enforces Law 5 (Reflect After Every Session) and Law 7 (Learn From Every Session) of the 7 Laws of AI Agent Discipline by giving the agent a durable file-based memory it can read on resume and write at session end. File-based memory system using Tiago Forte's PARA method. Use this skill whenever you need to store, retrieve, update, or organize knowledge across sessions. Covers three memory layers: (1) Knowledge graph in PARA folders with atomic YAML facts, (2) Daily notes as raw timeline, (3) Tacit knowledge about user patterns. Also handles planning files, memory decay, weekly synthesis, and recall via qmd. Trigger on any memory operation: saving facts, writing daily notes, creating entities, running weekly synthesis, recalling past context, or managing plans.
21
+ - `model-forward` — Enforces all 7 Laws as a standing stance go with Claude Code and the model, not against it. Skills are scaffolding that merges into the model over time; the durable core is goal-driven execution (the higher the stated goal, the better) plus self-discipline guardrails.
22
22
  - `recall` — Enforces Law 1 (Research Before Executing) of the 7 Laws of AI Agent Discipline. Makes past sessions first-class research material by searching the observation log with BM25 ranking, so 'have I hit this before?' is answerable before re-deriving a fix or repeating a mistake.
23
23
  - `tdd-workflow` — Enforces Law 3 (One Thing at a Time) and Law 4 (Verify Before Reporting) of the 7 Laws of AI Agent Discipline. Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.
24
24
  - `verification-loop` — Enforces Law 4 (Verify Before Reporting) of the 7 Laws of AI Agent Discipline. A comprehensive verification system for agent coding sessions covering build, types, lint, tests, security, and diff with a PASS/FAIL report.
@@ -6,7 +6,7 @@ description: "Install structured self-improvement loops with instinct-based lear
6
6
 
7
7
  # continuous-improvement
8
8
 
9
- You follow the continuous-improvement framework. These 7 laws govern all your work.
9
+ You follow the continuous-improvement framework. These 7 laws make every task sharper — each is a capability that compounds: research deeper, plan tighter, verify with evidence, reflect, and learn so the same lesson is never re-taught.
10
10
 
11
11
  ## Law 1: Research Before Executing
12
12
 
@@ -136,7 +136,7 @@ This gate is what catches the squash-merge / ahead-of-origin trap recorded in th
136
136
 
137
137
  ### Today: runtime hook + skill (zero install beyond the plugin)
138
138
 
139
- `hooks/gateguard.mjs` is bundled with this plugin and wired as the first PreToolUse hook in `plugins/continuous-improvement/hooks/hooks.json`. When you install the plugin, the runtime gate is live — no extra config, no opt-in. The hook reads tool input from stdin, classifies it through a data-driven routing table (Read/Grep/Glob → allow, Write/Edit/MultiEdit → mutating-file gate, Bash → destructive-pattern check), and emits `{decision, reason?}` on stdout. Per-session state lives at `~/.claude/instincts/<project-hash>/gateguard-session.json` (override via `GATEGUARD_SESSION_DIR` for tests) and caps cumulative clearances at `MAX_CLEARED_FILES = 50`.
139
+ `hooks/gateguard.mjs` is bundled with this plugin and wired as the first PreToolUse hook in `plugins/continuous-improvement/hooks/hooks.json`. When you install the plugin, the runtime gate is live — no extra config, no opt-in. The hook reads tool input from stdin, classifies it through a data-driven routing table (Read/Grep/Glob → allow, Write/Edit/MultiEdit → mutating-file gate, Bash → destructive-pattern check), and emits `{decision, reason?}` on stdout. Per-session state lives at `~/.claude/instincts/<project-hash>/sessions/<session-id>/gateguard-session.json` — scoped by the stdin `session_id` so the cap never bleeds across concurrent sessions (it falls back to the unscoped `<project-hash>/` dir when no session id is present, and `GATEGUARD_SESSION_DIR` overrides it for tests). The cap is `MAX_CLEARED_FILES = 50` per session, and the state self-heals after `STATE_TTL_MS` so a stale gate never needs a manual `rm`.
140
140
 
141
141
  Smoke-test the runtime gate after install: ask Claude to write a throwaway file with no research first. The hook should return a `block` decision with a fact-list reason; Claude should pause rather than write.
142
142
 
@@ -150,10 +150,10 @@ The block reason prints the exact `gateguard-session.json` path and the clearanc
150
150
 
151
151
  The inline `_gateguard_facts_presented: true` retry still works on harnesses that forward unknown tool params, but Claude Code's strict tool schema (`additionalProperties: false`) rejects it with `InputValidationError` — use one of the above on Claude Code.
152
152
 
153
- ### V1 honest limitations (not mitigated, documented)
153
+ ### Limitations and guarantees
154
154
 
155
- - **Honor system.** Clearance is recorded by `ci_gateguard_clear`, the `gateguard-clear.mjs` CLI, a manual state-file write, or the inline `_gateguard_facts_presented` flag where the harness allows it (see "Clearing the gate" above). The hook can't verify the investigation actually happened; the 50-file cap bounds damage from stuck loops or rogue agents.
156
- - **State-file deletion.** `rm`-ing the session state resets every gate. Acceptable because the session itself is the trust boundary.
155
+ - **Honor system.** Clearance is recorded by `ci_gateguard_clear`, the `gateguard-clear.mjs` CLI, a manual state-file write, or the inline `_gateguard_facts_presented` flag where the harness allows it (see "Clearing the gate" above). The hook can't verify the investigation actually happened; the 50-file cap — counted per session — bounds damage from stuck loops or rogue agents.
156
+ - **State-file deletion / self-heal.** `rm`-ing the session state resets every gate. Because state is scoped per session (`sessions/<session-id>/`), the session is a real trust boundary, not one shared across concurrent runs. A stale state file also self-heals once its `created_at` ages past `STATE_TTL_MS`, so a manual `rm` is rarely needed.
157
157
  - **Parallel-hook race.** Two simultaneous hook invocations can race the read+write of the state file. Acceptable trade-off vs Windows atomic-rename complexity.
158
158
 
159
159
  **MultiEdit per-file gating.** The hook clears and checks every `edits[]` path individually, so a mixed-clearance batch blocks until *all* edited files are cleared or facts are presented. The block reason now names the whole batch, not just the first uncleared path.
@@ -77,5 +77,5 @@ ci_goal_check goal_file=docs/x.md # score against a specific plan file
77
77
  ## Pairs With
78
78
 
79
79
  - **`proceed-with-the-recommendation`** (orchestrator, Law 2) — run a goal check at phase boundaries to confirm the plan still matches the work.
80
- - **`para-memory-files`** / planning-with-files — the `## Goal` section this skill reads is the same one those workflows write.
80
+ - **planning-with-files** — the `## Goal` section this skill reads is the same one that workflow writes.
81
81
  - **`strategic-compact`** — before compacting a long session, a goal check confirms what the session was actually about.
@@ -51,7 +51,6 @@ Anything that is already captured elsewhere gets a path or URL pointer, not a du
51
51
  ## Companion / alternative skills
52
52
 
53
53
  - [`strategic-compact`](./strategic-compact.md) — compact the current session at a phase boundary instead of writing a handoff doc. Use when the session continues with the same agent.
54
- - [`para-memory-files`](./para-memory-files.md) — durable cross-session memory under `~/.claude/memory/`. Use for classified facts (user, project, feedback, reference), not per-session handoff briefs.
55
54
  - `superpowers:writing-plans` — produce the plan doc the handoff can reference instead of duplicating.
56
55
 
57
56
  ## Attribution