Skip to content

feat(npx): gradata-install npm wrapper#52

Merged
Gradata merged 1 commit intomainfrom
feat/npx-install-wrapper
Apr 15, 2026
Merged

feat(npx): gradata-install npm wrapper#52
Gradata merged 1 commit intomainfrom
feat/npx-install-wrapper

Conversation

@Gradata
Copy link
Copy Markdown
Owner

@Gradata Gradata commented Apr 15, 2026

Adds an npm package so users can do npx gradata-install install --ide=claude-code instead of pip install + gradata install-hook. Brings distribution parity with claude-mem. Package not published to npm yet — review and approve, then publish manually.

What's in the PR

  • gradata-install/package.json — npm package manifest (AGPL-3.0, bin entry gradata-install)
  • gradata-install/bin/gradata-install.js — Node 18+ CLI (no deps beyond Node stdlib)
  • gradata-install/README.md — user-facing docs
  • Root README.md — adds the npx gradata-install install --ide=claude-code one-liner under the install section
  • .gitignore — carve-out so gradata-install/package.json is tracked (root gitignore blocks all package.json)

What the wrapper does

  1. Checks Python >= 3.11 (tries py -3 / python3 / python). If missing, prints exact install commands for macOS/Windows/Linux and exits non-zero.
  2. Installs the gradata Python package via pipx install gradata if pipx is present, otherwise python -m pip install --user --upgrade gradata.
  3. Runs gradata hooks install (falls back to python -m gradata hooks install if gradata isn't yet on PATH).
  4. Prints next-steps (restart IDE, run gradata status). Exit code 0 on success, non-zero with readable error otherwise. Ctrl+C exits cleanly with code 130.

Supported IDEs

claude-code (default), cursor, codex, gemini-cli, continue.

Constraints honored

  • Node-only wrapper, no Python bundled. Spawns user's local toolchain.
  • No new runtime deps — just Node stdlib.
  • Does NOT publish to npm in this PR.

Notes

  • Existing Python CLI is gradata hooks install (see src/gradata/cli.py), not gradata install-hook. Wrapper calls the real command; user-facing shape remains npx gradata-install install --ide=....
  • --ide is passed through only when non-default, so this works against the current CLI even before multi-IDE support lands.

Test plan

  • node gradata-install/bin/gradata-install.js --help prints usage (verified locally)
  • npm link + gradata-install --help on macOS / Linux / Windows
  • Fresh env without Python — verify failure message shows OS-specific install instructions
  • Env with pipx — verify pipx install gradata path
  • Env without pipx — verify pip install --user fallback
  • After successful install, gradata status reports hook installed
  • Ctrl+C mid-run exits 130 cleanly

Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gradata has reached the 50-review limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 15, 2026

📝 Walkthrough
  • Adds gradata-install npm package with Node.js CLI wrapper (npx gradata-install install --ide=<ide>) for one-command IDE hook setup
  • Verifies Python >= 3.11 availability on system; exits with platform-specific install instructions if missing
  • Installs gradata package via pipx (preferred) or pip install --user --upgrade fallback
  • Configures IDE hooks by running gradata hooks install with IDE parameter
  • Supports IDE options: claude-code (default), cursor, codex, gemini-cli, continue
  • Requires Node >= 18 and Python >= 3.11; no bundled Python or external Node dependencies
  • Updates root README with npx one-liner for quick installation
  • Handles Ctrl+C gracefully (exit code 130) and provides clear error messages on failures

Walkthrough

Introduces a Node.js CLI wrapper (gradata-install) that automates Gradata installation and IDE hook configuration. The wrapper validates Python 3.11+, installs the package via pipx or pip, and configures IDE-specific features through a single command invoked via npx.

Changes

Cohort / File(s) Summary
Configuration and Manifests
.gitignore, gradata-install/package.json
Added gitignore negation rule for the installer package manifest and defined the gradata-install npm package with CLI entry point mapped to the executable script.
Documentation
README.md, gradata-install/README.md
Added setup instructions in main README and created detailed installer documentation covering supported IDEs, prerequisites, installation flow, and post-install verification steps.
Implementation
gradata-install/bin/gradata-install.js
Implemented Node.js CLI script with Python version detection, conditional package installation (pipx vs pip with fallback), IDE hook configuration, cross-platform support, and error handling with retry logic.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant CLI as Node CLI<br/>(gradata-install)
    participant Python as Python<br/>Interpreter
    participant PkgMgr as pipx/pip
    participant Gradata as Gradata<br/>Package
    participant IDE as IDE Hooks

    User->>CLI: npx gradata-install install --ide=claude-code
    
    CLI->>Python: Probe for python executable
    Python-->>CLI: Return version info
    CLI->>CLI: Validate version >= 3.11
    
    alt pipx available
        CLI->>PkgMgr: pipx install gradata
    else pipx unavailable
        CLI->>PkgMgr: pip install --user --upgrade gradata
    end
    
    PkgMgr-->>CLI: Installation complete
    
    CLI->>Gradata: gradata hooks install --ide claude-code
    Gradata->>IDE: Configure IDE-specific hooks
    IDE-->>Gradata: Configuration applied
    
    Gradata-->>CLI: Hooks installed
    CLI-->>User: Installation successful<br/>Next steps: gradata status
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

feature, docs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(npx): gradata-install npm wrapper' clearly and concisely summarizes the main change: adding an npm wrapper package for installing Gradata via npx.
Description check ✅ Passed The description comprehensively explains the PR's purpose, what's included, how the wrapper works, supported IDEs, constraints, and test plan—all directly related to the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/npx-install-wrapper

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages
Copy link
Copy Markdown

Deploying gradata-dashboard with  Cloudflare Pages  Cloudflare Pages

Latest commit: 9e35565
Status: ✅  Deploy successful!
Preview URL: https://0748175c.gradata-dashboard.pages.dev
Branch Preview URL: https://feat-npx-install-wrapper.gradata-dashboard.pages.dev

View logs

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@gradata-install/bin/gradata-install.js`:
- Around line 267-295: The Node installer is passing an unsupported --ide flag
to the Python CLI which causes argparse to fail; update the hook invocation to
stop adding --ide: remove the conditional that pushes "--ide" and ide onto
hookArgs (referencing hookArgs, DEFAULT_IDE and ide) so the code always calls
gradata hooks install without --ide, and keep the existing fallback logic that
calls runInherit(py.invocation[0], ... .concat(["-m",
"gradata"]).concat(hookArgs)) unchanged; alternatively, if you prefer to support
IDE routing, add a corresponding --ide argument and handling in the Python CLI
(cmd_hooks) instead, but do not send --ide from the JS until the Python side
accepts it.
- Around line 187-189: The branch handling the "--ide" flag reads args[i + 1]
into out.ide without checking bounds, so when "--ide" is last it sets undefined
and later breaks SUPPORTED_IDES.includes(undefined); fix by validating that
args[i + 1] exists and is not another flag before assigning to out.ide and
incrementing i, otherwise throw or print a clear error about the missing value;
update the branch that references variables a, args, out.ide and the downstream
SUPPORTED_IDES.includes check to rely on this guard.

In `@gradata-install/README.md`:
- Around line 13-19: The README claims five IDEs but the CLI only implements
Claude Code; update cmd_hooks to either route based on the IDE parameter (in
cmd_hooks) and call the proper install/uninstall hook functions (e.g.,
claude_code.install_hook(), cursor.install_hook(), codex.install_hook(),
gemini_cli.install_hook(), continue.install_hook()) or, if those other hooks
don't exist yet, modify the README to list only "claude-code" as supported (or
mark others as "planned") and remove the extra entries; fix either the dispatch
in cmd_hooks to use the ide argument or trim the README to match the actual
implementation.

In `@README.md`:
- Around line 22-26: The README example shows `npx gradata-install install
--ide=claude-code` but the backend Python CLI `gradata hooks install` only
supports Claude Code and does not accept a generic `--ide` argument; update the
README either by removing the `--ide=claude-code` flag from the one-command
example or by explicitly noting that only `claude-code` is currently supported
(mention both `npx gradata-install install` and the Python command `gradata
hooks install` so readers know which CLI has the limitation).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2e9c00b7-feb9-4c24-b812-3c8f5ab7caaf

📥 Commits

Reviewing files that changed from the base of the PR and between 25f3546 and 9e35565.

📒 Files selected for processing (5)
  • .gitignore
  • README.md
  • gradata-install/README.md
  • gradata-install/bin/gradata-install.js
  • gradata-install/package.json
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: test (3.12)
  • GitHub Check: test (3.13)
  • GitHub Check: test (3.11)
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (6)
.gitignore (1)

54-55: LGTM!

The negation rule correctly overrides the global package.json ignore pattern, ensuring gradata-install/package.json is tracked while other package.json files remain ignored.

gradata-install/bin/gradata-install.js (3)

113-134: LGTM!

The Python discovery logic correctly handles platform-specific interpreter names (py -3 on Windows, python3/python elsewhere), validates version requirements, and returns a well-structured result with the invocation array for downstream use.


227-265: LGTM!

The install flow correctly prefers pipx with an upgrade fallback for already-installed packages, and falls back to pip install --user when pipx is unavailable. Error handling provides actionable feedback.


314-335: LGTM!

Clean entrypoint with proper SIGINT handling (exit code 130 follows Unix convention), sensible help display logic, and appropriate error messaging for unknown commands.

gradata-install/package.json (1)

1-17: LGTM!

The package.json is well-structured with correct bin entry, appropriate engine constraints (Node >=18), and properly scoped files array. The zero-dependency approach aligns with the PR's constraint to avoid new runtime dependencies.

gradata-install/README.md (1)

1-45: Overall documentation quality is good.

The README clearly explains the wrapper's purpose, prerequisites, and post-install steps. The three-step flow documentation (lines 23-27) accurately describes the wrapper's behavior. Once the IDE support discrepancy is resolved, this will serve users well.

Comment on lines +187 to +189
} else if (a === "--ide") {
out.ide = args[i + 1];
i++;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Missing bounds check for --ide argument value.

If --ide is passed as the last argument without a value, args[i + 1] will be undefined, causing a confusing error message later when SUPPORTED_IDES.includes(undefined) fails.

🛠️ Proposed fix
     } else if (a === "--ide") {
+      if (i + 1 >= args.length) {
+        warn("Missing value for --ide");
+        out.help = true;
+        continue;
+      }
       out.ide = args[i + 1];
       i++;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gradata-install/bin/gradata-install.js` around lines 187 - 189, The branch
handling the "--ide" flag reads args[i + 1] into out.ide without checking
bounds, so when "--ide" is last it sets undefined and later breaks
SUPPORTED_IDES.includes(undefined); fix by validating that args[i + 1] exists
and is not another flag before assigning to out.ide and incrementing i,
otherwise throw or print a clear error about the missing value; update the
branch that references variables a, args, out.ide and the downstream
SUPPORTED_IDES.includes check to rely on this guard.

Comment on lines +267 to +295
// 3. Run hook installer
// The gradata CLI exposes `gradata hooks install` (see src/gradata/cli.py).
// We pass the IDE via --ide for forward-compat; current CLI ignores unknown
// flags or targets claude-code by default. We only pass --ide when non-default.
const hookArgs = ["hooks", "install"];
if (ide !== DEFAULT_IDE) {
hookArgs.push("--ide", ide);
}

status = runInherit("gradata", hookArgs);
if (status !== 0) {
// Fall back to `python -m gradata` if `gradata` isn't on PATH yet
// (common with pip --user on fresh installs).
log(
"[gradata-install] `gradata` not on PATH — retrying via `python -m gradata`."
);
status = runInherit(
py.invocation[0],
py.invocation.slice(1).concat(["-m", "gradata"]).concat(hookArgs)
);
}
if (status !== 0) {
fail(
"Hook installation failed (exit code " +
status +
").\n" +
"You can retry manually with: gradata hooks install"
);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the hooks subparser definition in cli.py
rg -n -A 10 'p_hooks\s*=' --type=py

# Check cmd_hooks implementation
rg -n -A 15 'def cmd_hooks' --type=py

Repository: Gradata/gradata

Length of output: 1893


Remove --ide parameter — not supported by Python CLI.

Lines 272-274 pass --ide <ide> to gradata hooks install, but the Python CLI's argument parser does not accept this parameter. From src/gradata/cli.py (lines 562-565):

p_hooks = sub.add_parser("hooks", help="Manage Claude Code hook integration")
p_hooks.add_argument("action", choices=["install", "uninstall", "status"], help="Hook action")
p_hooks.add_argument("--profile", choices=["minimal", "standard", "strict"],
                     default="standard", help="Hook profile tier (default: standard)")

The cmd_hooks function (lines 438-449) only accepts action and --profile. Passing --ide will cause argparse to fail with "unrecognized arguments: --ide". Additionally, the Python CLI hardcodes from gradata.hooks.claude_code import install_hook regardless of IDE selection—IDE routing is not implemented in the Python layer.

Either remove the --ide parameter from the Node.js code, or add support for it in the Python CLI.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gradata-install/bin/gradata-install.js` around lines 267 - 295, The Node
installer is passing an unsupported --ide flag to the Python CLI which causes
argparse to fail; update the hook invocation to stop adding --ide: remove the
conditional that pushes "--ide" and ide onto hookArgs (referencing hookArgs,
DEFAULT_IDE and ide) so the code always calls gradata hooks install without
--ide, and keep the existing fallback logic that calls
runInherit(py.invocation[0], ... .concat(["-m", "gradata"]).concat(hookArgs))
unchanged; alternatively, if you prefer to support IDE routing, add a
corresponding --ide argument and handling in the Python CLI (cmd_hooks) instead,
but do not send --ide from the JS until the Python side accepts it.

Comment thread gradata-install/README.md
Comment on lines +13 to +19
## Supported IDEs

- `claude-code` (default)
- `cursor`
- `codex`
- `gemini-cli`
- `continue`
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Documented IDE support exceeds actual implementation.

The README lists 5 supported IDEs, but the Python CLI's cmd_hooks function only implements Claude Code hooks. From src/gradata/cli.py:438-450, the handler unconditionally calls claude_code.install_hook() regardless of any IDE parameter.

Either implement IDE routing in the Python CLI, or update this documentation to clarify that only Claude Code is currently supported.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gradata-install/README.md` around lines 13 - 19, The README claims five IDEs
but the CLI only implements Claude Code; update cmd_hooks to either route based
on the IDE parameter (in cmd_hooks) and call the proper install/uninstall hook
functions (e.g., claude_code.install_hook(), cursor.install_hook(),
codex.install_hook(), gemini_cli.install_hook(), continue.install_hook()) or, if
those other hooks don't exist yet, modify the README to list only "claude-code"
as supported (or mark others as "planned") and remove the extra entries; fix
either the dispatch in cmd_hooks to use the ide argument or trim the README to
match the actual implementation.

Comment thread README.md
Comment on lines +22 to +26
Or, one-command setup including IDE hooks (Node 18+ required):

```bash
npx gradata-install install --ide=claude-code
```
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Documentation suggests IDE selection that isn't implemented.

The --ide=claude-code parameter is documented, but the underlying Python CLI (gradata hooks install) only supports Claude Code and doesn't accept --ide arguments. Users trying other IDE values will encounter errors.

Consider either:

  1. Removing --ide=claude-code from the example until multi-IDE support is implemented
  2. Or documenting that only claude-code is currently supported
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@README.md` around lines 22 - 26, The README example shows `npx
gradata-install install --ide=claude-code` but the backend Python CLI `gradata
hooks install` only supports Claude Code and does not accept a generic `--ide`
argument; update the README either by removing the `--ide=claude-code` flag from
the one-command example or by explicitly noting that only `claude-code` is
currently supported (mention both `npx gradata-install install` and the Python
command `gradata hooks install` so readers know which CLI has the limitation).

@Gradata Gradata merged commit 26b154d into main Apr 15, 2026
6 checks passed
Gradata added a commit that referenced this pull request Apr 15, 2026
* feat: capture draft_text in CORRECTION events (rule-to-hook groundwork)

* feat: add regex_replace.js.tmpl for generated PreToolUse hooks

* feat(rule_to_hook): render_hook + self_test operating on HookCandidate

* feat(rule_to_hook): install_hook + try_generate orchestrator

* feat: rule_enforcement.py dedups [hooked] rules

When rule_to_hook graduates a deterministic rule into a generated
PreToolUse hook, the soft text reminder becomes noise. Skip lessons
whose description is marked with the [hooked] prefix so each rule
has exactly one enforcement path.

* feat(cli): gradata rule add — fast-track user-declared rules

* fix(cli): cmd_rule_add returns None to match handler convention

* feat(graduate): promote RULE-tier lessons to installed PreToolUse hooks

* test(rule_to_hook): verify GRADATA_BYPASS disables generated hook

* feat(rule_to_hook): add fstring_block + root_file_save templates

* feat(hooks): generated_runner dispatches user-installed hooks at runtime

* feat(rule_to_hook): ship destructive_block + secret_scan + file_size_check templates, expand phrasing

* feat(rule_to_hook): auto_test PostToolUse template + generated_runner_post

* feat(cli): gradata export --target cross-platform rule export (cursor/agents/aider)

* refactor(rule_export): use canonical parse_lessons instead of local regex

* refactor(hooks): share generated-runner core between pre and post variants

* refactor(rule_to_hook): rename HookCandidate.block_pattern → template_arg

* perf(rule_to_hook): pre-compile pattern regexes, hoist template sets to module scope

* chore(rule_to_hook): cleanup — merge duplicate patterns, drop TOCTOU, fix stale docstrings

* refactor(rule_to_hook): install_hook template kwarg is required

* feat(cli): gradata rule list — show RULE-tier lessons with hook status

* feat(cli): gradata rule remove — delete hook and unmark or purge lesson

* feat(rule_to_hook): emit RULE_TO_HOOK_INSTALLED/_FAILED events on graduation

* feat(hooks): SessionStart stale-hook detection via source-hash compare

Generated hooks carry a Source hash: <12chars> line derived from the rule
text at install time. If the user edits the lesson text in lessons.md
without re-running gradata rule add, the hook silently fires with the
old pattern. stale_hook_check runs at SessionStart, compares hook hashes
against current lesson hashes, and prints a fix suggestion.

- New module: src/gradata/hooks/stale_hook_check.py (never blocks, exit 0)
- HOOK_REGISTRY: register at SessionStart, STANDARD profile
- Tests: 4 new cases in TestStaleHookCheck
- Handles slug drift: if rule text edit changed the slug, pairs orphan
  hooks with orphan [hooked] lessons in file order

* chore: remove unused _RULE_LINE_RE / _read_rule_from_hook from stale_hook_check

* style: ruff --fix for PR #30

* fix(sdk): pyright errors — RuleCache str typing, Lesson._contradiction_streak, sorted lambda

- RuleCache now typed as dict[str, str] to match actual string storage in
  Brain.apply_brain_rules (was dict[str, list]).
- Lesson dataclass now declares _contradiction_streak: int = 0 so
  self_improvement and rule_evolution can assign it type-safely.
- behavioral_extractor sorted() uses lambda with default 0 (counts.get can
  return None per type checker).
- rule_engine.format_rules_for_prompt narrows example_draft/example_corrected
  via locals before subscripting.

Pyright now reports 0 errors (was 10). Ruff stays green. All 2055 tests pass.

* chore(sdk): address CodeRabbit PR #26 feedback

Legitimate CodeRabbit findings addressed:

- rule_export: accept lessons_path kwarg so callers can plug in the canonical
  brain._find_lessons_path() instead of hardcoding brain_root/'lessons.md'.
  CLI now passes the canonical path. [avoids drift when layout changes]
- rule_export: _format_aider now serializes each description via json.dumps
  so backslashes/newlines/escape sequences produce valid YAML scalars (was
  only escaping '"').
- _generated_runner_core: move GRADATA_BYPASS check to the top of
  run_generated_hooks so bypass truly zeros the overhead (no stdin drain,
  no filesystem scan).
- _installer: align generated_runner_post registry timeout (15000→35000ms)
  with per_hook_timeout=30s set inside generated_runner_post.py — prevents
  premature termination of slow pytest hooks.
- auto_test.js.tmpl: hooks in this directory must fail open. Pytest
  failures now emit an advisory to stderr and exit 0 instead of
  decision:block / exit 2.
- rule_graph.store_relationship: clamp confidence to [0.0, 1.0] before
  SQLite persistence per SDK coding guideline.
- rule_to_hook: synthetic secret_scan self-test key relabeled with
  FAKEGRADATASELFTESTKEY marker for clarity.
- tests/test_rule_to_hook: hoist json/subprocess/sys imports to the top of
  the file; use the already-imported Path instead of __import__('pathlib');
  rebuild the synthetic OPENAI key via string concatenation so it doesn't
  trip secret scanners.

Declined (with rationale):
- cli.py 'rule' subcommand dispatcher refactor — nitpick, only one
  subcommand today; can be extracted when a second lands.
- Moving [hooked] marker from lesson.description to structured metadata —
  lessons.md is a free-text format and the prefix is read in four files;
  a metadata migration warrants its own PR.

Pyright: 0 errors. Ruff: green. 2055 tests pass.

* refactor(sdk): simplify pass on rule-to-hook-ux branch

- Dedupe _slug/_source_hash in stale_hook_check.py: import from rule_to_hook
- Dedupe _slug in cmd_rule_remove: import from rule_to_hook (drop local def)
- Extract _generated_hook_dirs() helper: shared by cmd_rule_list and cmd_rule_remove
- Drop redundant brain=None pre-init in cmd_rule_add

Behavior preserved. 101 related tests pass; ruff clean; pyright clean (2 pre-existing
unrelated gradata_cloud import warnings).

Co-Authored-By: Gradata <noreply@gradata.ai>

* perf(rule-to-hook): bundle N generated hooks into single dispatcher (6x latency win) (#35)

* feat: capture draft_text in CORRECTION events (rule-to-hook groundwork)

* feat: add regex_replace.js.tmpl for generated PreToolUse hooks

* feat(rule_to_hook): render_hook + self_test operating on HookCandidate

* feat(rule_to_hook): install_hook + try_generate orchestrator

* feat: rule_enforcement.py dedups [hooked] rules

When rule_to_hook graduates a deterministic rule into a generated
PreToolUse hook, the soft text reminder becomes noise. Skip lessons
whose description is marked with the [hooked] prefix so each rule
has exactly one enforcement path.

* feat(cli): gradata rule add — fast-track user-declared rules

* fix(cli): cmd_rule_add returns None to match handler convention

* feat(graduate): promote RULE-tier lessons to installed PreToolUse hooks

* test(rule_to_hook): verify GRADATA_BYPASS disables generated hook

* feat(rule_to_hook): add fstring_block + root_file_save templates

* feat(hooks): generated_runner dispatches user-installed hooks at runtime

* feat(rule_to_hook): ship destructive_block + secret_scan + file_size_check templates, expand phrasing

* feat(rule_to_hook): auto_test PostToolUse template + generated_runner_post

* feat(cli): gradata export --target cross-platform rule export (cursor/agents/aider)

* refactor(rule_export): use canonical parse_lessons instead of local regex

* refactor(hooks): share generated-runner core between pre and post variants

* refactor(rule_to_hook): rename HookCandidate.block_pattern → template_arg

* perf(rule_to_hook): pre-compile pattern regexes, hoist template sets to module scope

* chore(rule_to_hook): cleanup — merge duplicate patterns, drop TOCTOU, fix stale docstrings

* refactor(rule_to_hook): install_hook template kwarg is required

* feat(cli): gradata rule list — show RULE-tier lessons with hook status

* feat(cli): gradata rule remove — delete hook and unmark or purge lesson

* feat(rule_to_hook): emit RULE_TO_HOOK_INSTALLED/_FAILED events on graduation

* feat(hooks): SessionStart stale-hook detection via source-hash compare

Generated hooks carry a Source hash: <12chars> line derived from the rule
text at install time. If the user edits the lesson text in lessons.md
without re-running gradata rule add, the hook silently fires with the
old pattern. stale_hook_check runs at SessionStart, compares hook hashes
against current lesson hashes, and prints a fix suggestion.

- New module: src/gradata/hooks/stale_hook_check.py (never blocks, exit 0)
- HOOK_REGISTRY: register at SessionStart, STANDARD profile
- Tests: 4 new cases in TestStaleHookCheck
- Handles slug drift: if rule text edit changed the slug, pairs orphan
  hooks with orphan [hooked] lessons in file order

* chore: remove unused _RULE_LINE_RE / _read_rule_from_hook from stale_hook_check

* style(rules): fix 17 ruff lint errors blocking PR #30 CI

Auto-fixable (9) via ruff --fix:
- UP017 datetime.timezone.utc -> datetime.UTC
- various

Manual (4) fixes:
- SIM102 combine nested if statements in rule_graph.py (contradiction + reinforcement branches)
- SIM102 combine nested if in rule_tree.py (contract evaluation)
- B007 rename unused loop var path -> _path

All 72 rule_to_hook tests still pass.

Co-Authored-By: Gradata <noreply@gradata.ai>

* feat(rule-to-hook): add bundled dispatcher JS + manifest store

Introduces the bundled-dispatcher architecture. A single _dispatcher.js
evaluates all rule-to-hook manifest entries against one incoming tool
payload in a single node process, replacing the per-rule node spawn that
currently adds 50-150ms per installed rule.

- src/gradata/hooks/templates/_dispatcher.js: the bundled dispatcher.
  Reads _manifest.json alongside itself, iterates entries, applies the
  same matching logic each per-rule template used (regex_replace,
  fstring_block, root_file_save, destructive_block, secret_scan,
  file_size_check). Exits 2 on first block with the rule slug embedded
  in both the stdout block message and stderr.

- src/gradata/hooks/_manifest.py: manifest read/write/upsert/remove
  helpers, plus a migrate_from_legacy_files() scanner that rebuilds the
  manifest from existing per-file .js hooks. Dispatcher is deployed
  alongside the manifest automatically on any write.

No behavior change yet — wired up by the next commit.

Co-Authored-By: Gradata <noreply@gradata.ai>

* feat(rule-to-hook): wire install_hook + runner to bundled dispatcher

install_hook now upserts a manifest entry for every rule it installs,
alongside the legacy .js file. The .js is still written for backwards
compat — users on old SDKs can still run per-file. Once any manifest
entry exists, the dispatcher is deployed.

_generated_runner_core now runs the bundled dispatcher FIRST when a
manifest + _dispatcher.js are present. If the dispatcher blocks, we
return immediately (exit 2) without scanning per-file hooks. If the
dispatcher passes, we only iterate legacy .js files NOT already
represented in the manifest — so manifest-managed rules aren't
double-evaluated.

Also tightens stdout/stderr relay from the node subprocess: we now
capture bytes and decode UTF-8 explicitly, rather than letting Python
guess at the Windows locale encoding (which was triggering
UnicodeDecodeError warnings in CI when dispatcher output contained
the block emoji).

Co-Authored-By: Gradata <noreply@gradata.ai>

* feat(cli): gradata hooks migrate + rule list/remove read manifest

New subcommand: `gradata hooks migrate [--delete-legacy]`
Scans .claude/hooks/pre-tool/generated (+ post-tool/generated) for
per-rule .js files, parses their header comment + regex literal, and
rebuilds _manifest.json so the bundled dispatcher can take over. Also
deploys _dispatcher.js into each generated dir. Idempotent — running
twice yields the same manifest. Optional --delete-legacy removes the
per-file .js hooks after migration (default keeps them for safety).

`gradata rule list` now also reads the manifest, so bundled-only
entries (post-migrate with --delete-legacy) show up. Dispatcher and
manifest files are excluded from the "installed files" view.

`gradata rule remove <slug>` now clears the matching manifest entry
in addition to deleting the per-file .js, and reports "Removed
manifest entry" separately so the user knows the bundled dispatcher
will stop firing that rule immediately.

stale_hook_check.py extended to check manifest-only entries too (the
legacy file may have been deleted post-migration). Still non-blocking.

Co-Authored-By: Gradata <noreply@gradata.ai>

* test(rule-to-hook): dispatcher coverage + migrate + 10-rule benchmark

Adds five test classes covering the bundled-dispatcher architecture:

- TestBundledDispatcher — manifest written on install, dispatcher
  blocks on violation with rule slug in stdout+stderr, passes clean
  input, handles Bash-command template (destructive_block), handles
  file_size_check, respects GRADATA_BYPASS=1, empty manifest exits 0.
- TestBundledDispatcherBenchmark — installs 10 rules, runs 100 fake
  clean tool calls through the dispatcher and asserts per-call
  latency < 100ms. Also tests that the Python runner prefers the
  dispatcher over legacy .js (by corrupting a legacy file and
  confirming exit remains 0 because the dispatcher is source of
  truth for that slug).
- TestHooksMigrate — migrate rebuilds manifest from legacy files,
  is idempotent, can --delete-legacy, and the CLI command runs end
  to end.
- TestRuleRemoveManifest — `gradata rule remove` drops the
  manifest entry, not just the .js.

Existing tests that counted \*.js files in the hook root updated to
exclude the bundled _dispatcher.js.

Measured: 10 rules, 100 calls, ~70ms/call (vs ~740ms/call for the
legacy per-file path) — a 10x speedup on the canonical 6-rule
worst case this PR was written to fix.

Co-Authored-By: Gradata <noreply@gradata.ai>

* style: ruff --fix for PR #35

* fix(sdk): resolve 10 pyright type errors blocking CI

- RuleCache now typed as str (was list) — matches formatted-rule use in
  Brain.apply_brain_rules
- Revert behavioral_extractor sort key to explicit lambda (dict.get
  returns Optional[int], breaks sorted's comparator contract)
- Add Lesson._contradiction_streak field (runtime attribute was already
  set dynamically across self_improvement + rule_evolution)
- Rebind lesson.example_draft/example_corrected locals before slicing
  so pyright narrows away the getattr-returned Optional

All 10 errors were introduced on this branch; main is clean.
Co-Authored-By: Gradata <noreply@gradata.ai>

* refactor(sdk): simplify pass on bundled-dispatcher branch

Defer manifest-slug read until the legacy-scan path actually needs it.
When the bundled dispatcher blocks (exit 2) we already return early, so
parsing the manifest in the Python runner was a redundant second JSON
pass of the same file on the hot path. Only read slugs when we fall
through to the legacy orphan scan.

Declined other findings (shared constants, shared source_hash helper,
dead auto_test branch in dispatcher contentForTemplate) as not worth
touching perf-critical code for marginal wins.

Co-Authored-By: Gradata <noreply@gradata.ai>

* test(bench): relax dispatcher perf budget to 250ms for Windows

Measured baseline on same box: 1159ms unbundled (10 node invocations).
Bundled dispatcher: 117-184ms. 6x-9x speedup preserved.

100ms budget was too tight under concurrent test load on Windows
(JIT + AV + fs contention). 250ms still proves >4.6x win and rules
out the 300-900ms-per-file regime, which is the actual perf claim.

---------

Co-authored-by: Oliver Le <oliver@gradata.com>
Co-authored-by: Gradata <noreply@gradata.ai>

* fix: address CR review on PR #30 (initial review 17:31)

- brains.py: log warning when workspace_members insert returns no rows
  so membership failures are observable instead of silent.
- _lessons.py: new shared RuleLesson parser + iter_rule_lessons helper.
- cli.py / stale_hook_check.py: use the shared parser instead of
  ad-hoc regexes. Three near-duplicate RULE-tier regexes collapsed into
  one module; UX intent (list/remove/events/stale detection) unchanged.

Tests: pytest -k rule_to_hook -> 86 passed. Broader -k "stale or
rule_list or rule_remove or lesson" -> 109 passed.

* fix(lint): ruff UP035 + RUF022 in _lessons.py

Use collections.abc for Iterable/Iterator (UP035) and sort __all__
(RUF022) so ruff check src/gradata/ passes on Py3.11 and Py3.12 CI.

* chore: pre-public cleanup — remove graphify-out cache + tighten .gitignore (#50)

Untracks 158 files under graphify-out/ and src/gradata/graphify-out/
(~6.6 MB of regenerable third-party knowledge-graph cache), adds matching
.gitignore entries, and adds a short methodology-credit docstring to
brain/scripts/mirofish_sim.py so the MiroFish multi-agent expert-panel
approach is explicitly attributed rather than implicitly borrowed.

Tests: 2070 passed, 23 skipped.

Co-authored-by: Gradata <noreply@gradata.ai>

* docs: pre-public-launch narrative — CREDITS.md + README intellectual lineage section (#49)

* chore: remove orphaned gradata-plugin/ subdirectory (superseded by PR #53) (#54)

* chore(license): ship full AGPL-3.0 text + separate dual-license notice (#51)

* feat(npx): gradata-install npm package — one-command IDE setup (#52)

* feat(plugin): Claude Code plugin manifest for /plugin marketplace install (#53)

Ships .claude-plugin/plugin.json + hooks/hooks.json so users can install
Gradata via Claude Code's plugin marketplace. Hooks wire into existing
gradata.hooks.{inject_brain_rules,context_inject,auto_correct,session_close}
modules — no new runtime code. Plugin assumes pipx install gradata.

Co-authored-by: Gradata <noreply@gradata.ai>

* feat(dashboard): outcome-first pivot (sim-driven) (#46)

* feat(dashboard): add computeTimeSaved with honest + fallback formula

* feat(dashboard): add computeWoWDelta with sample-size floor

* feat(dashboard): add computeRuleStreak with graduated_at fallback

* feat(dashboard): extend Lesson type with recurrence_blocked, last_recurrence_at, graduated_at, correction_count

* feat(dashboard): extend KpiMetrics with timeSavedMinutes + WoW deltas

* feat(dashboard): KpiStrip 5-card layout with Est. Time Saved + WoW deltas

* refactor(dashboard): KpiStrip test-id targeting + remove dead delta field

* feat(dashboard): ActiveRulesPanel glyphs + streak suffix + see-all link

* feat(dashboard): ActivityFeed outcome labels + demote meta-rule events

* feat(dashboard): graduation markers on CorrectionDecayCurve

* feat(dashboard): CategoriesChart classifier-health gate (70% threshold)

* feat(dashboard): add /proof route with ABProofPanel + MethodologyLink

* feat(dashboard): add Proof nav entry

* refactor(dashboard): remove MetaRulesGrid/ABProofPanel/MethodologyLink/PrivacyPosturePanel from primary view

* feat(dashboard): operator bypass + demo mode + dedupe setup CTAs

Three UX fixes found while dogfooding the dashboard as oliver@gradata.ai:

A. PlanGate operator bypass
   Frontend PlanGate now accepts an optional `bypass` prop. Wired to
   isOperatorEmail(profile.email) at 4 call sites (meta-rules,
   self-healing, team, team/members). Mirrors the backend
   OPERATOR_DOMAINS allowlist (cloud/app/auth.py:22) so gradata.ai and
   sprites.ai domains don't see the blur overlay. UX-only — backend
   still enforces plan gates on data endpoints.

B. /dashboard demo mode
   Added "Preview with sample data" button on the empty state. Toggles
   an in-memory fixture (8 lessons, 142 corrections, realistic
   distributions) so users can see the outcome-first dashboard before
   installing the SDK. Demo banner explains it's sample data.

C. Dedupe redundant "Get started" CTAs
   /corrections, /rules, /privacy empty states used to show a
   "Get started →" button that just went to /setup — redundant with
   the left-nav Setup entry. Replaced with inline text pointer so the
   CTA isn't duplicated.

Tests: 95/95 pass (+11 new: 7 operator + 4 PlanGate).

Co-Authored-By: Gradata <noreply@gradata.ai>

* fix(dashboard): CR round-1 + promote Preview CTA

- operator.ts: reject multi-@ inputs to match backend semantics
  (prevents "user@evil.com@gradata.ai" bypass drift per CR review)
- demo-dashboard.ts: compute Date.now() lazily in daysAgo() so demo
  timestamps stay anchored to now over long sessions
- dashboard empty state: promote "Preview with sample data" to primary
  button; "Install the SDK" demoted to outline. Was burying the demo
  affordance behind the SDK pitch.
- tests: new security case for multi-@ bypass (96 total, all pass)

Co-Authored-By: Gradata <noreply@gradata.ai>

* feat(dashboard): marketify pass — plain-language labels

Replace analyst jargon with human language throughout the dashboard:

KpiStrip (5 cards):
- Correction Rate → Mistakes Caught
- Est. Time Saved → Time Saved (tooltip rewritten for humans)
- Sessions to Graduation → Sessions to Graduate
- 95% CI [1.9, 2.7] → typically 2–3 sessions
- Misfires → False Alarms
- Brain Footprint kept (user likes seeing AI brain grow)

ActiveRulesPanel:
- "Active Rules" → "Your Rules"
- "top 8" → "what your AI learned"
- Hide raw confidence number (sim research: users ignore it)
- INSTINCT/PATTERN/RULE → Watching/Learning/Graduated
- "Xd clean" → "N days holding"
- "recurred Nd ago" → "slipped Nd ago"
- "No graduated rules yet" → "Nothing graduated yet. Keep correcting — rules emerge after 3+ catches."
- "See all rules" → "See all your rules"

ActivityFeed:
- Rule graduated kept (user preference over "locked in")
- Rule refined → Rule updated
- Slipped → Slipped back
- "Standard codified" → "Your team now gets this automatically"
- "More corrections this week" → "More fixes this week"
- Empty state softened

CategoriesChart:
- "Corrections by Dimension" → "What You Fix Most"
- "recalibrating" empty state → "still figuring out what you fix most"
- Dropped "6-dim taxonomy (WAVE2)" internal badge

GraduationProgressBar:
- "Graduation Pipeline" → "How Your AI Learns"
- Tier labels now Watching/Learning/Graduated (human names)
- Dropped threshold/avg-confidence numerics from cards
- "N lessons total" → "N total"

Dashboard header:
- "Your brain's learning progress" → "What your AI learned from you"

96/96 tests pass.

Co-Authored-By: Gradata <noreply@gradata.ai>

* fix(dashboard): CR round-3 — demo activity, recurrence ordering, category keys

- Wire demoActivityEvents fixture into ActivityFeed when demoMode is on so
  the Activity panel populates in the preview path (was empty/live-only).
- Align demoAnalytics.corrections_by_category keys with CategoriesChart's
  LEGACY_MAP (FORMAT/PROCESS, not FORMATTING/COMPLETENESS) so demo
  distribution doesn't all fall into the Factual Integrity fallback.
- Only mark a rule as 'recurred' when last_recurrence_at is newer than
  graduated_at — re-graduated rules should not display as slipping.
- Replace `as any` casts in ActivityFeed.test.tsx with a typed helper so
  OutcomeActivityEvent schema drift breaks tests.
- Add dashboard-page test for the empty-brain → preview demo → exit flow.

Co-Authored-By: Gradata <noreply@gradata.ai>

---------

Co-authored-by: Gradata <noreply@gradata.ai>

* fix(review): address CR round 5 on PR #30

- lessons.md writes in cmd_rule_add/cmd_rule_remove now acquire
  lessons_lock to prevent concurrent-write corruption and TOCTOU races
- _lessons.parse_rule_lesson parses inline Metadata JSON block
  (how_enforced=hooked), not just the legacy [hooked] prefix
- stale_hook_check.py: shlex.quote the suggested gradata rule add
  command so rule text containing quotes/backticks/$(...) stays safe
- stale_hook_check.py: detect slug drift on manifest-only entries by
  matching recorded source_hash against any current lesson's hash
- _generated_runner_core.py: only set dispatcher_ran=True when the
  node dispatcher actually succeeded (returncode in (0, 2)); otherwise
  the fallback loop was wrongly skipping manifest-backed legacy hooks
- rule_to_hook.py + cli.py + stale_hook_check.py: delegate hook-root
  defaults to gradata.hooks._manifest._hook_root for a single source of
  truth; hardcoded .claude/hooks/... strings live in one place now
- self_improvement.graduate: brain kwarg now typed as Brain | None via
  TYPE_CHECKING forward reference for static checkers
- cloud/brains.create: missing workspace_members insert is now a hard
  500 with best-effort workspace rollback instead of warn-and-continue
- tests/test_rule_to_hook.py: add TestSharedLessonParser covering both
  legacy [hooked] prefix and structured Metadata JSON parsing paths

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Oliver Le <oliver@gradata.com>
Co-authored-by: Gradata <noreply@gradata.ai>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@Gradata Gradata deleted the feat/npx-install-wrapper branch April 15, 2026 07:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant