jez 0.1.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.
data/lib/jez/check.rb ADDED
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jez
4
+ # Launches diagnostics on Jez's pinned Ruby from the caller's directory.
5
+ class Check
6
+ HELP = <<~HELP
7
+ Usage: jez check [--strict] [--base REVISION] [--flog-limit SCORE] [--flay-mass MASS] [PATH...]
8
+
9
+ Report regressions in changed Ruby files. Pass paths to check a specific scope.
10
+ Use --strict to check thresholds across the scope, including duplication.
11
+
12
+ Options:
13
+ --strict Check the scope against the quality thresholds
14
+ --base REVISION Compare against REVISION (default HEAD)
15
+ --flog-limit SCORE Highest Flog score a method may have (default 20)
16
+ --flay-mass MASS Smallest duplicated mass Flay reports (default 16)
17
+ -h, --help Show this help
18
+ HELP
19
+ # A mise startup failure can return 1 or 2 on its own.
20
+ RUNNER_CODES = { 0 => 0, 1 => 10, 2 => 20 }.freeze
21
+ CLEAN_ENV = %w[RUBYOPT RUBYLIB BUNDLER_SETUP BUNDLER_VERSION GEM_HOME GEM_PATH].to_h { |key| [key, nil] }.freeze
22
+
23
+ def run(argv)
24
+ return help if %w[--help -h].include?(argv.first)
25
+
26
+ status = launch(argv)
27
+ RUNNER_CODES.key(status) || tool_error("mise could not run diagnostics (exit #{status || "unknown"})")
28
+ rescue SystemCallError => error
29
+ tool_error(error.message)
30
+ end
31
+
32
+ private
33
+
34
+ def help
35
+ puts HELP
36
+ 0
37
+ end
38
+
39
+ def launch(argv)
40
+ runner = File.join(ROOT, "scripts/check.rb")
41
+ pid = Process.spawn(CLEAN_ENV, "mise", "-C", ROOT, "exec", "--", "ruby", "-C", Dir.pwd, runner, *argv)
42
+ Process.wait2(pid).last.exitstatus
43
+ end
44
+
45
+ def tool_error(message)
46
+ warn "jez check: #{message} (set up the optional analyzers with #{File.join(ROOT, "bin/install")})"
47
+ 2
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,135 @@
1
+ module Jez
2
+ # Recommends a design mode and offers optional examples and planning prompts.
3
+ class Decision
4
+ HELP = "Usage: jez decide\nChoose a design mode, compare examples, or sketch a plan.".freeze
5
+
6
+ # The recommendation, example, and planning prompts for one kind of change.
7
+ class Mode < Data.define(:name, :label, :reason, :next_step, :example, :questions)
8
+ BY_CHOICE = {
9
+ "1" => [
10
+ "Precise",
11
+ "Fix a bug",
12
+ "Change what an existing method does while keeping its interface the same.",
13
+ "Write a test for the result the caller should get.",
14
+ "The second reader is told they are first in line. Fix the position they receive.",
15
+ {
16
+ "Existing interface" => "Which method or interface will you change?",
17
+ "Caller result" => "What result should the caller get?",
18
+ "Verification" => "What test or command will check that result?"
19
+ }.freeze
20
+ ],
21
+ "2" => [
22
+ "Progressive",
23
+ "Refactor existing code",
24
+ "Change how the code is organized while preserving its behavior.",
25
+ "Identify one caller and a behavior to check before and after the change.",
26
+ "Adding a request and expiring one both use the same sorting rule. " \
27
+ "Define it once and check that readers keep their order.",
28
+ {
29
+ "Scope" => "Which code do you plan to reorganize?",
30
+ "Behavior to preserve" => "What behavior do callers depend on today?",
31
+ "Verification" => "What test or command will check that behavior before and after?"
32
+ }.freeze
33
+ ],
34
+ "3" => [
35
+ "Pragmatic",
36
+ "Build a new feature",
37
+ "Agree on how it should work, then implement the simplest case.",
38
+ "Write down the first thing someone should be able to do with the feature.",
39
+ "Add a waiting list for a book. Start with two readers signing up and receiving positions 1 and 2.",
40
+ {
41
+ "Caller result" => "Who needs this capability, and what result do they need first?",
42
+ "First case" => "What is the simplest case that delivers that result?",
43
+ "Verification" => "How will you test that case from the caller’s perspective?"
44
+ }.freeze
45
+ ]
46
+ }.transform_values { |attributes| new(*attributes) }.freeze
47
+
48
+ def recommendation = ["", heading, "", next_step]
49
+ def choice_details = [heading, reason]
50
+ def example_details = [label, example]
51
+
52
+ private
53
+
54
+ def heading = "#{name} — #{label}"
55
+ end
56
+
57
+ MODES = Mode::BY_CHOICE
58
+
59
+ def initialize(input: $stdin, output: $stdout)
60
+ @input = input
61
+ @output = output
62
+ end
63
+
64
+ def run
65
+ mode = choose_mode
66
+ @output.puts(*mode.recommendation)
67
+ explore(mode)
68
+ 0
69
+ rescue EOFError
70
+ @output.puts "Decision session ended before the current step was complete."
71
+ 1
72
+ end
73
+
74
+ private
75
+
76
+ def choose_mode
77
+ show_choices
78
+ loop do
79
+ choice = read_choice("Enter 1, 2, or 3 to choose, or ? for examples.") || raise(EOFError)
80
+ mode = MODES[choice]
81
+ return mode if mode
82
+
83
+ show_examples if choice == "?"
84
+ end
85
+ end
86
+
87
+ def show_choices
88
+ show_modes("What kind of change do you need?", &:choice_details)
89
+ end
90
+
91
+ def explore(mode)
92
+ loop do
93
+ case read_choice("\nEnter to finish · c to compare examples · p to sketch a plan").to_s
94
+ when "" then return
95
+ when "c" then show_examples
96
+ when "p" then return print_plan(mode)
97
+ end
98
+ end
99
+ end
100
+
101
+ def show_examples
102
+ show_modes("", "Examples using a library waiting list", &:example_details)
103
+ end
104
+
105
+ def show_modes(*heading)
106
+ @output.puts(*heading, "")
107
+ MODES.each do |number, mode|
108
+ label, detail = yield mode
109
+ @output.puts " #{number} #{label}", " #{detail}"
110
+ end
111
+ @output.puts ""
112
+ end
113
+
114
+ def print_plan(mode)
115
+ answers = mode.questions.transform_values { |question| ask(question) }
116
+ @output.puts "", "Design plan (#{mode.name})"
117
+ answers.each { |label, answer| @output.puts "#{label}: #{answer}" }
118
+ end
119
+
120
+ def ask(question)
121
+ loop do
122
+ answer = read_choice(question) || raise(EOFError)
123
+ return answer unless answer.empty?
124
+
125
+ @output.puts "Enter a response to continue."
126
+ end
127
+ end
128
+
129
+ def read_choice(prompt)
130
+ @output.puts prompt
131
+ @output.flush
132
+ @input.gets&.strip
133
+ end
134
+ end
135
+ end
@@ -0,0 +1,23 @@
1
+ require "jez/hooks_file"
2
+
3
+ module Jez
4
+ # A coding agent that can run the ratchet after each edit: where its hooks
5
+ # live, which edit tools to match, what its hook handlers add, and anything the
6
+ # user must do before a new hook runs.
7
+ Harness = Data.define(:name, :hooks_path, :matcher, :handler_fields, :follow_up)
8
+
9
+ # The harnesses jez can install into.
10
+ class Harness
11
+ def self.all
12
+ [
13
+ new(name: "claude", hooks_path: File.join(Dir.home, ".claude", "settings.json"),
14
+ matcher: "Edit|Write|MultiEdit", handler_fields: {}, follow_up: nil),
15
+ new(name: "codex", hooks_path: File.join(Dir.home, ".codex", "hooks.json"),
16
+ matcher: "^apply_patch$", handler_fields: { "statusMessage" => "jez check" },
17
+ follow_up: "Codex skips new or changed hooks until you trust them with /hooks.")
18
+ ]
19
+ end
20
+
21
+ def hooks_file(path = hooks_path) = HooksFile.new(path, matcher:, handler_fields:)
22
+ end
23
+ end
@@ -0,0 +1,80 @@
1
+ require "fileutils"
2
+ require "json"
3
+ require "shellwords"
4
+
5
+ module Jez
6
+ # A coding agent's hooks file, edited so jez check runs after
7
+ # each edit. Unrelated settings and hooks are left as they are, and the file is
8
+ # replaced atomically through any symlink so a managed target stays managed.
9
+ class HooksFile
10
+ EVENT = "PostToolUse".freeze
11
+ HOOK_NAME = "ruby-ratchet".freeze
12
+ TIMEOUT = 120
13
+
14
+ def initialize(path, matcher:, handler_fields: {})
15
+ @path = path
16
+ @matcher = matcher
17
+ @handler_fields = handler_fields
18
+ end
19
+
20
+ # Returns :added, :updated, or :unchanged.
21
+ def install_hook(command)
22
+ original = read
23
+ settings = parse(original)
24
+ status = remove_ratchet_hooks(settings) ? :updated : :added
25
+ text = with_hook(settings, command)
26
+ text == original ? :unchanged : save(text, status)
27
+ end
28
+
29
+ private
30
+
31
+ def read = File.exist?(@path) ? File.read(@path) : ""
32
+
33
+ def parse(text) = text.strip.empty? ? {} : JSON.parse(text)
34
+
35
+ def with_hook(settings, command)
36
+ groups(settings) << { "matcher" => @matcher, "hooks" => [hook(command)] }
37
+ "#{JSON.pretty_generate(settings)}\n"
38
+ end
39
+
40
+ def groups(settings)
41
+ (settings["hooks"] ||= {})[EVENT] ||= []
42
+ end
43
+
44
+ def hook(command) = { "type" => "command", "command" => command, "timeout" => TIMEOUT, **@handler_fields }
45
+
46
+ # Drops any earlier ratchet hook, wherever it pointed, and any group it leaves empty.
47
+ def remove_ratchet_hooks(settings)
48
+ found = false
49
+ groups(settings).each do |group|
50
+ found = true if group.fetch("hooks", []).reject! { |entry| ratchet?(entry) }
51
+ end
52
+ groups(settings).reject! { |group| group.fetch("hooks", nil)&.empty? }
53
+ found
54
+ end
55
+
56
+ def ratchet?(entry)
57
+ command = entry.fetch("command", "")
58
+ File.basename(Shellwords.split(command).first.to_s) == HOOK_NAME
59
+ rescue ArgumentError
60
+ false
61
+ end
62
+
63
+ def save(text, status)
64
+ write(text)
65
+ status
66
+ end
67
+
68
+ def write(text)
69
+ target = File.exist?(@path) ? File.realpath(@path) : File.expand_path(@path)
70
+ FileUtils.mkdir_p(File.dirname(target))
71
+ temporary = "#{target}.#{Process.pid}.tmp"
72
+ File.write(temporary, text, perm: permissions(target))
73
+ File.rename(temporary, target)
74
+ ensure
75
+ FileUtils.rm_f(temporary) if temporary
76
+ end
77
+
78
+ def permissions(target) = File.exist?(target) ? File.stat(target).mode & 0o777 : 0o644
79
+ end
80
+ end
@@ -0,0 +1,187 @@
1
+ require "fileutils"
2
+ require "optparse"
3
+
4
+ module Jez
5
+ # Installs the bundled skill into the user locations for the selected agents.
6
+ class Installer
7
+ # Agent discovery, installation directory, and identifier for Vercel skills.
8
+ Target = Data.define(:label, :vercel_id, :commands, :config_dirs, :skills_dir)
9
+
10
+ # Links the skill directly when the Vercel CLI is unavailable.
11
+ class SymlinkInstallation
12
+ def initialize(destinations)
13
+ @destinations = destinations
14
+ end
15
+
16
+ def paths = @destinations.values
17
+
18
+ def preview
19
+ @destinations.each { |name, path| puts "Would install Jez for #{name} at #{path}." }
20
+ 0
21
+ end
22
+
23
+ def install
24
+ @destinations.each do |name, path|
25
+ FileUtils.mkdir_p(File.dirname(path))
26
+ File.symlink(ROOT, path)
27
+ puts "Installed Jez for #{name} at #{path}."
28
+ end
29
+ 0
30
+ end
31
+ end
32
+
33
+ # Invokes the Vercel CLI and accounts for its shared store for other agents.
34
+ class VercelInstallation
35
+ def initialize(executable, destinations, shared_path)
36
+ @executable = executable
37
+ @destinations = destinations
38
+ @shared_path = shared_path
39
+ end
40
+
41
+ def paths = @destinations.values + [@shared_path]
42
+
43
+ def preview
44
+ puts "Would install Jez with Vercel skills for #{names.join(", ")}."
45
+ 0
46
+ end
47
+
48
+ def install
49
+ puts "Installing Jez with Vercel skills for #{names.join(", ")}."
50
+ $stdout.flush
51
+ return 0 if system(@executable, "add", ROOT, "--global", "--skill", "jez", "--agent", *agents, "--yes")
52
+
53
+ warn "jez install: Vercel skills installation failed."
54
+ 1
55
+ end
56
+
57
+ private
58
+
59
+ def names = @destinations.keys
60
+
61
+ def agents = names.map { |name| TARGETS.fetch(name).vercel_id }
62
+ end
63
+
64
+ TARGETS = {
65
+ claude: Target.new("Claude Code", "claude-code", %w[claude], %w[.claude], ".claude/skills"),
66
+ codex: Target.new("Codex", "codex", %w[codex], %w[.codex], ".agents/skills"),
67
+ antigravity: Target.new("Antigravity", "antigravity", %w[agy antigravity],
68
+ %w[.gemini/antigravity-cli .gemini/antigravity], ".gemini/config/skills")
69
+ }.freeze
70
+
71
+ BANNER = <<~HELP.chomp.freeze
72
+ Usage: jez install [--claude] [--codex] [--antigravity] [--dry-run]
73
+ Without agent flags, install for detected agents.
74
+ HELP
75
+
76
+ # Installation cannot proceed with the selected agents or destination.
77
+ class InstallError < StandardError; end
78
+ private_constant :InstallError
79
+
80
+ def initialize
81
+ @home = Dir.home
82
+ @required_files = ["SKILL.md", *Dir.glob("references/**/*.md", base: ROOT)]
83
+ end
84
+
85
+ def run(argv)
86
+ install_selected(parse(argv))
87
+ rescue OptionParser::ParseError => error
88
+ fail_with(error.message, status: 2)
89
+ rescue SystemCallError, InstallError => error
90
+ fail_with(error.message)
91
+ end
92
+
93
+ private
94
+
95
+ def install_selected(options)
96
+ installation = prepare_installation(selected_targets(options.keys))
97
+ return 0 unless installation
98
+
99
+ options[:"dry-run"] ? installation.preview : installation.install
100
+ end
101
+
102
+ def parse(argv)
103
+ flags = {}
104
+ option_parser.parse!(argv, into: flags)
105
+ raise OptionParser::InvalidArgument, argv.join(" ") unless argv.empty?
106
+
107
+ flags
108
+ end
109
+
110
+ def option_parser
111
+ descriptions = TARGETS.map { |name, target| ["--#{name}", "Install for #{target.label}"] }
112
+ descriptions << ["--dry-run", "Preview without installing"]
113
+ OptionParser.new(BANNER) do |parser|
114
+ descriptions.each { |flag, description| parser.on(flag, description) }
115
+ end
116
+ end
117
+
118
+ def selected_targets(explicit_flags)
119
+ names = TARGETS.keys & explicit_flags
120
+ names = detected_targets if names.empty?
121
+ return names unless names.empty?
122
+
123
+ raise InstallError, "No supported agent detected. Pass --claude, --codex, or --antigravity."
124
+ end
125
+
126
+ def prepare_installation(names)
127
+ pending = pending_destinations(names)
128
+ return if pending.empty?
129
+
130
+ installation = installation_for(pending)
131
+ conflict = installation.paths.find { |path| conflicting_path?(path) }
132
+ raise InstallError, "Refusing to overwrite existing data at #{conflict}." if conflict
133
+
134
+ installation
135
+ end
136
+
137
+ def pending_destinations(names)
138
+ destinations = names.to_h { |name| [name, destination(name)] }
139
+ destinations.reject do |name, path|
140
+ next false unless installed?(path)
141
+
142
+ puts "Jez is already installed for #{name} at #{path}."
143
+ true
144
+ end
145
+ end
146
+
147
+ def installation_for(pending)
148
+ skills_cli = executable("skills")
149
+ return VercelInstallation.new(skills_cli, pending, destination(:codex)) if skills_cli
150
+
151
+ SymlinkInstallation.new(pending)
152
+ end
153
+
154
+ def conflicting_path?(path)
155
+ (File.exist?(path) || File.symlink?(path)) && !installed?(path)
156
+ end
157
+
158
+ def detected_targets
159
+ TARGETS.keys.select do |name|
160
+ target = TARGETS.fetch(name)
161
+ target.commands.any? { |command| executable(command) } ||
162
+ target.config_dirs.any? { |path| File.directory?(File.join(@home, path)) }
163
+ end
164
+ end
165
+
166
+ def executable(name)
167
+ ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).filter_map do |directory|
168
+ path = File.expand_path(name, directory)
169
+ path if File.file?(path) && File.executable?(path)
170
+ end.first
171
+ end
172
+
173
+ def destination(name) = File.join(@home, TARGETS.fetch(name).skills_dir, "jez")
174
+
175
+ def installed?(path)
176
+ @required_files.all? do |relative|
177
+ installed = File.join(path, relative)
178
+ File.file?(installed) && FileUtils.compare_file(installed, File.join(ROOT, relative))
179
+ end
180
+ end
181
+
182
+ def fail_with(message, status: 1)
183
+ warn "jez install: #{message}"
184
+ status
185
+ end
186
+ end
187
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jez
4
+ VERSION = "0.1.0"
5
+ end
data/lib/jez.rb ADDED
@@ -0,0 +1,6 @@
1
+ require_relative "jez/version"
2
+
3
+ # The directory agents can load as the Jez skill.
4
+ module Jez
5
+ ROOT = File.expand_path("..", __dir__).freeze
6
+ end
@@ -0,0 +1,23 @@
1
+ module RubyQuality
2
+ # Measures the scope now, and at the base revision wherever the gate needs it,
3
+ # and collects the findings the gate reports.
4
+ class Check
5
+ # The gate's findings for a scope of paths, compared against a base revision.
6
+ Result = Data.define(:gate, :base, :paths, :findings) do
7
+ def passed? = findings.empty?
8
+ end
9
+
10
+ def initialize(repository:, gate:, measures:)
11
+ @repository = repository
12
+ @gate = gate
13
+ @measures = measures
14
+ end
15
+
16
+ def run(base:, paths:)
17
+ current = paths.map { |path| @repository.current(path) }
18
+ previous = paths.filter_map { |path| @repository.at(base, path) }
19
+ findings = @measures.flat_map { |measure| @gate.findings(measure, current:, base: previous) }
20
+ Result.new(gate: @gate.name, base:, paths:, findings:)
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,36 @@
1
+ module RubyQuality
2
+ # Command-line boundary: assembles the check, prints the report, and maps
3
+ # outcomes to exit codes (0 pass, 1 findings, 2 usage or tool error).
4
+ class Cli
5
+ def initialize(stdout: $stdout, stderr: $stderr, shell: Shell.new, directory: Dir.pwd)
6
+ @stdout = stdout
7
+ @stderr = stderr
8
+ @shell = shell
9
+ @directory = directory
10
+ end
11
+
12
+ def run(argv)
13
+ report(check(Options.parse(argv)))
14
+ rescue Error => error
15
+ hint = error.is_a?(ToolError) ? " (check optional analyzer setup)" : ""
16
+ @stderr.puts "jez check: #{error.message}#{hint}"
17
+ 2
18
+ end
19
+
20
+ private
21
+
22
+ def report(result)
23
+ @stdout.print Report.new(result)
24
+ result.passed? ? 0 : 1
25
+ end
26
+
27
+ def check(options)
28
+ repository = Repository.discover(directory: @directory, shell: @shell)
29
+ base = options.base
30
+ repository.verify(base)
31
+ toolchain = Toolchain.new(directory: repository.root, shell: @shell)
32
+ Check.new(repository:, gate: options.gate, measures: options.measures(toolchain))
33
+ .run(base:, paths: repository.scope(paths: options.paths, base:, from: @directory))
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,12 @@
1
+ module RubyQuality
2
+ # Base for failures reported as a usage or tool error rather than a gate result.
3
+ class Error < StandardError; end
4
+
5
+ # An argument or environment problem the caller must correct.
6
+ class UsageError < Error
7
+ def self.with_banner(error, banner) = new("#{error.message}\n#{banner}")
8
+ end
9
+
10
+ # An external tool or git failed in a way no gate can judge.
11
+ class ToolError < Error; end
12
+ end
@@ -0,0 +1,57 @@
1
+ module RubyQuality
2
+ # Decides which observations fail. Both gates fail only what is over its limit.
3
+ # Ratchet also lets anything stand that is no worse than the base revision;
4
+ # strict extends that allowance only to baselined measures.
5
+ class Gate
6
+ # An observation over its limit, judged without a base.
7
+ Breach = Data.define(:observation) do
8
+ def to_s = "#{observation.heading} #{observation.against_limit}"
9
+ end
10
+
11
+ # An observation over its limit and worse than it was at the base.
12
+ Regression = Data.define(:observation, :before) do
13
+ def to_s = "#{observation.heading} #{observation.display(before)} -> #{observation.against_limit}"
14
+ end
15
+
16
+ def self.named(name)
17
+ case name
18
+ when "ratchet" then new(name:, ratchets_everything: true)
19
+ when "strict" then new(name:, ratchets_everything: false)
20
+ else raise UsageError, "unknown gate #{name.inspect}"
21
+ end
22
+ end
23
+
24
+ attr_reader :name
25
+
26
+ def initialize(name:, ratchets_everything:)
27
+ @name = name
28
+ @ratchets_everything = ratchets_everything
29
+ end
30
+
31
+ # Measures across files, such as duplication, have no per-file base to ratchet
32
+ # against, so only strict runs them.
33
+ def measures(per_file:, across_files:) = @ratchets_everything ? per_file : per_file + across_files
34
+
35
+ def findings(measure, current:, base:)
36
+ observed = measure.observe(current)
37
+ return breaches(observed) unless compares_to_base?(measure)
38
+
39
+ regressions(observed, measure.observe(base).to_h { |observation| [observation.key, observation.value] })
40
+ end
41
+
42
+ private
43
+
44
+ def compares_to_base?(measure) = @ratchets_everything || measure.baselined?
45
+
46
+ def breaches(observed)
47
+ observed.select(&:over_limit?).map { |observation| Breach.new(observation:) }
48
+ end
49
+
50
+ def regressions(observed, before)
51
+ observed.filter_map do |observation|
52
+ previous = before.fetch(observation.key, 0)
53
+ Regression.new(observation:, before: previous) if observation.regressed_from?(previous)
54
+ end
55
+ end
56
+ end
57
+ end