sigmold 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 308ce3955eeccafd8e318f64c2fb7ab27eb9c88e99f2a76049e2a52be079f7d3
4
+ data.tar.gz: 0b13f8233fd9b5d41965bfc2112ae75d34f238b62d7e437a35cd0deb6c9f7bf4
5
+ SHA512:
6
+ metadata.gz: 57df0a1bf8281bb45fb65390cffc9f84cc9dcc0510f907d342152317205ac6c11845168d9a3c4de8565f5f5be13b8a4a9c76dd27404588d730851e5f1ac5ae10
7
+ data.tar.gz: cc84a543788ebfa583bdb8c508714db7cd199ff1502d97471b6b92343312daa54c09876747b34c39678d0190d0c15867c3ebf5943d2a396c6ca682e1c9f41b0c
data/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ## [0.1.0]
6
+
7
+ The first release.
8
+
9
+ - `sigmold holes` lists each `Sigmold.hole` left in the code, with the type it must become and the variables in scope. `Sigmold.absurd` makes Steep name a case a `case/when` leaves out.
10
+ - `sigmold strict` lists what lets code past its types: Steep diagnostics at any level, `untyped` in type comments, `steep:ignore`, and `untyped` in public signatures.
11
+ - `sigmold surface` lists the public methods `lib/` has and `sig/` does not declare, and the methods `sig/` declares public that `lib/` keeps private.
12
+ - `sigmold calls` runs the tests and lists the methods they call past `sig/`, and the declared methods no test calls.
13
+ - `sigmold check` runs holes, strict, surface, and calls as `sigmold.yml` says.
14
+ - `sigmold pour` has an agent write a file again from the public signature and the tests, and compares the rewrites that pass the tests with the original, or with each other when the file is still all holes. The agent may declare its private parts after a `private` line.
15
+ - `sigmold gaps` runs the same random calls, drawn from the signature, on each version and asks a question where they part: the calls as Ruby, what each version did, a test that makes each answer the contract, and the annotation that leaves it free.
16
+ - A signature leaves a step free with `%a{sigmold:free: <step>}` above a class or module, or `%a{sigmold:free: <outcome>}` on a method.
17
+ - `sigmold review` shows what a person reviews between two commits: the public part of `sig/`, the tests, and the dependencies the public signatures name.
18
+ - `sigmold deps` lists the classes each public signature names, and exits 1 on a cycle.
19
+ - `sigmold hide` makes the copy `pour` gives the agent, and prints its brief.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 meganemura
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.ja.md ADDED
@@ -0,0 +1,136 @@
1
+ # sigmold
2
+
3
+ Ruby のクラスを、先に RBS のシグネチャとテストで形づくり、コードはあとから流し込みます。
4
+ sigmold はその鋳型を調べます。
5
+ `sig/` もテストも `lib/` も、書くのはコーディングエージェントです。
6
+ 人は `sig/` とテストだけをレビューし、`lib/` がその鋳型に収まっているかは sigmold が調べます。
7
+
8
+ ## 進め方
9
+
10
+ 1. エージェントが `sig/` にシグネチャを書き、テストを書きます。本体はそれぞれ `Sigmold.hole("名前")` にしておきます。人は `sigmold review` でそれをレビューします。
11
+ 2. `sigmold holes` が、穴ごとになるべき型と、そこで使える変数をエージェントに教えます。
12
+ 3. 穴が埋まったら、`sigmold check` が通る必要があります。コードを鋳型に合わせて調べます。
13
+ - **holes**: 穴が残っていない。
14
+ - **strict**: コードが型をすり抜ける道がない。
15
+ - **surface**: `sig/` が `lib/` の public なメソッドをすべて、それだけを見せている。
16
+ - **calls**: テストが通り、`sig/` にあるものだけを呼び、そのすべてを呼んでいる。
17
+ 4. `sigmold pour` は、鋳型がコードを決めきっているかを確かめます。ファイルを隠し、エージェントに `sig/` とテストだけから書き直させ、元のコードと各書き直しに同じ乱数の呼び出しを流します。分かれた所が、持ち主への問いです。Ruby の呼び出しと、各版が何をしたかで出ます。約束にする(答えごとのテストが報告に出るので、エージェントがそれを足し、持ち主がレビューする)か、自由にするかを決めます。
18
+
19
+ ## コマンド
20
+
21
+ - `sigmold check [DIR]` は、`sigmold.yml` の通りに holes、strict、surface、calls を走らせます。
22
+
23
+ ```yaml
24
+ namespace: Shop # sig/ が形づくるモジュール
25
+ test: ruby -Ilib test/cart_test.rb # テストを走らせるコマンド
26
+ # require: shop # lib/ から読み込む名前が違うとき
27
+ # sig: [sig] # シグネチャのフォルダ
28
+ ```
29
+
30
+ - `sigmold holes [DIR]` は、穴ごとに Steep が求める型と、そこで使えるローカル変数を出します。
31
+ - `sigmold strict [DIR]` は、どのレベルの Steep の診断も、型コメントの `untyped`、`steep:ignore`、public なシグネチャの `untyped` も出します。Steepfile の既定では `case/in`(UnsupportedSyntax)はヒントとしか出ず、その中身を Steep は検査しません。シグネチャの `untyped` がわざとなら、`%a{sigmold:untyped}` を付けます。
32
+ - `sigmold surface NAMESPACE` は、`lib/` では public なのに `sig/` にないメソッドと、`sig/` では public なのに `lib/` では private なメソッドを出します。rbs-inline は `private_class_method :name` を読まないので、後者は起こります。
33
+ - `sigmold calls NAMESPACE -- テストのコマンド` は、テストを走らせ、テストが呼んだのに `sig/` が public と言っていない NAMESPACE のメソッドと、どのテストも呼んでいない宣言済みのメソッドを出します。テストの要らないものには `%a{sigmold:untested}` を付けます。
34
+ - `sigmold pour FILE --sig SIG --agent CMD --into DIR --test CMD --const CLASS [--times N]` は、FILE を N 回(既定は 2 回)書き直させます。毎回、FILE を除き SIG を公開面だけにしたチェックアウトの写しを使います。CMD は指示を標準入力と `SIGMOLD_BRIEF` で受け取ります。エージェントは、自分のコードの非公開の部分を SIG の `private` 行のあとに書いてよく、それでコードが `strict` を通ります。公開の部分を変えた書き直しは数えません。テストが通った書き直しを、`gaps` と同じように比べます。元のコードと比べますが、FILE がまだ穴だけなら書き直し同士で比べます。
35
+ - `sigmold gaps --const CLASS original=PATH rewrite=PATH...` は、どの版にも同じ乱数の呼び出しを流し、分かれた所をまとめます。呼び出しはシグネチャから作ります。まず `new`、次に public なインスタンスメソッドと特異メソッドを、引数の型から作った値で呼びます(モジュールは自分のメソッドだけ)。返ってきた名前空間のオブジェクトは、その読み出しメソッドが返す値で比べます。エラーはクラスで比べます。メッセージも比べるときは `--messages` を付けます。自由にする所はシグネチャに書くので、レビューする人は約束と並べて見られます。クラスの上に `%a{sigmold:free: new -> raises ArgumentError}`、メソッドに `%a{sigmold:free: returns}` と書きます。`--free FILE` にも、キーか所を 1 行ずつ書けます。`--explorer E.rb` を渡すと、作った呼び出しの代わりに自分の呼び出しを使います。
36
+ - `sigmold review [BASE [HEAD]] [--sig DIR]... [--tests DIR]...` は、BASE(既定は `HEAD`)から HEAD(既定は作業中のファイル)までの間で、人がレビューするものを見せます。`sig/` の公開部分とテスト(既定は `test/` と `spec/`)の差分です。公開のシグネチャが名前を出す依存が増減したら、`+ Shop::Cart -> Shop::Coupon` のように出します。`lib/` の変わったファイルと、非公開部分だけが変わったシグネチャは、名前だけを出します。
37
+ - `sigmold deps [--sig DIR]...` は、クラスごとに、公開のシグネチャが名前を出す他のクラスを並べます。C++ のヘッダーで include を読むのと同じです。依存が循環していれば 1 で終わります。
38
+ - `sigmold hide FILE --sig SIG --into DIR` は、`pour` がエージェントに渡す写しを作り、指示を出します。
39
+
40
+ どのコマンドも、何か見つけたら終了コード 1 なので、CI で「なし」を求められます。
41
+
42
+ ## 例
43
+
44
+ `examples/shop` は `sigmold check` が通る鋳型です。
45
+ 2 つのエージェントが、ここから `lib/shop.rb` を流し込みました。
46
+
47
+ ```
48
+ $ sigmold pour lib/shop.rb --sig sig/shop.rbs --agent "claude -p --permission-mode acceptEdits" \
49
+ --into /tmp/pour --test "ruby -Ilib test/cart_test.rb" --const Shop::Cart
50
+ rewrite1: written, tests pass (/tmp/pour/rewrite1/lib/shop.rb)
51
+ rewrite2: written, tests pass (/tmp/pour/rewrite2/lib/shop.rb)
52
+
53
+ 2000 runs, 56 differ, 1 questions
54
+
55
+ 1. What should the last line do? 56 runs part here.
56
+ cart = Shop::Cart.new
57
+ cart.add(Shop::Item.new(name: "b", price: 7), 8)
58
+ cart.add(Shop::Item.new(name: "b", price: -1), 12)
59
+ cart.total
60
+ original: => -20
61
+ rewrite1, rewrite2: => 44
62
+ the rewrites agree and the original differs: check the original
63
+ To make one the contract, a test:
64
+ like original:
65
+ cart = Shop::Cart.new
66
+ cart.add(Shop::Item.new(name: "b", price: 7), 8)
67
+ cart.add(Shop::Item.new(name: "b", price: -1), 12)
68
+ assert_equal(-20, cart.total)
69
+ like rewrite1, rewrite2:
70
+ cart = Shop::Cart.new
71
+ cart.add(Shop::Item.new(name: "b", price: 7), 8)
72
+ cart.add(Shop::Item.new(name: "b", price: -1), 12)
73
+ assert_equal(44, cart.total)
74
+ To leave it free, write this above the class in sig/:
75
+ %a{sigmold:free: total -> returns}
76
+ ```
77
+
78
+ シグネチャには「カートにある品を足すと数が増える」とありましたが、「同じ品」が何かは書いていませんでした。
79
+ 元のコードは名前で行をまとめて最新の値段を使い、2 つのエージェントは品全体でまとめました。
80
+ 持ち主はエージェントの読み方を選びました。
81
+ エージェントがそれをシグネチャに書き、報告にあったテストを足し、持ち主は `sigmold review` でそれをレビューしました。
82
+ そのあと 3 回書き直させると、3000 回の呼び出しすべてで元のコードと一致しました。
83
+ この鋳型は、このクラスを決めきっています。
84
+
85
+ ## コードの中で
86
+
87
+ ```ruby
88
+ # @rbs (Array[Item], Integer?) -> Integer
89
+ def total(items, coupon)
90
+ Sigmold.hole("total") # Steep: ::Sigmold::Hole は ::Integer にできない
91
+ end
92
+
93
+ # @rbs (Circle | Rect | Tri) -> Integer
94
+ def area(shape)
95
+ case shape
96
+ when Circle then shape.r * shape.r * 3
97
+ when Rect then shape.w * shape.h
98
+ else Sigmold.absurd(shape) # Steep: ::Tri は bot に渡せない
99
+ end
100
+ end
101
+ ```
102
+
103
+ `raise NotImplementedError` は Steep を黙って通ります。
104
+ 穴は型を教えてくれます。
105
+ Steep 2.1 は `case/in` を型検査しないので、全部の場合を書く分岐は `case/when` と `Sigmold.absurd` で書きます。
106
+
107
+ ## 入れ方
108
+
109
+ ```ruby
110
+ # Gemfile
111
+ gem "sigmold", require: false
112
+ gem "steep", require: false
113
+ ```
114
+
115
+ ```ruby
116
+ # Steepfile
117
+ target :lib do
118
+ signature "sig"
119
+ check "lib"
120
+ library "sigmold" # the type of Sigmold.hole; the gem ships its signatures
121
+ end
122
+ ```
123
+
124
+ `Sigmold.hole` を呼ぶコードには `require "sigmold/hole"` が要ります。
125
+ これは他に何も読み込みません。
126
+
127
+ ## 必要なもの
128
+
129
+ Ruby 3.3 以上。
130
+ `holes`、`strict`、`check` は Steep の型検査の仕組みを読むので、プロジェクトのバンドルに `steep` が要ります。
131
+ `surface`、`calls`、`gaps` は `rbs` を使います。Steep と一緒に入ります。
132
+ sigmold 自体は実行時の依存を持ちません。
133
+
134
+ ## ライセンス
135
+
136
+ MIT
data/README.md ADDED
@@ -0,0 +1,128 @@
1
+ # sigmold
2
+
3
+ Shape a Ruby class first, in RBS signatures and tests, and pour the code in later.
4
+ Coding agents write all of it: `sig/`, the tests, and `lib/`. People review only `sig/` and the tests, and sigmold checks that `lib/` stays in that mold.
5
+
6
+ ## The loop
7
+
8
+ 1. The agent writes the signature in `sig/` and the tests, and leaves each body as `Sigmold.hole("name")`. A person reviews them with `sigmold review`.
9
+ 2. `sigmold holes` tells the agent the type each hole must become and the variables in scope.
10
+ 3. When the holes are filled, `sigmold check` must pass. It holds the code to the mold:
11
+ - **holes**: no hole is left.
12
+ - **strict**: nothing lets the code past its types.
13
+ - **surface**: `sig/` shows every public method of `lib/`, and only those.
14
+ - **calls**: the tests pass, call only what `sig/` declares, and call all of it.
15
+ 4. `sigmold pour` asks whether the mold decides the code. It hides the file, has an agent write it again from `sig/` and the tests alone, and runs the same random calls on the original and on each rewrite. Each place where they part is a question for the owner, with the calls in Ruby and what each version did: make it a contract (the report offers the test for each answer; the agent adds it, and the owner reviews it), or mark it free.
16
+
17
+ ## Commands
18
+
19
+ - `sigmold check [DIR]` runs holes, strict, surface, and calls, as `sigmold.yml` says:
20
+
21
+ ```yaml
22
+ namespace: Shop # the module sig/ shapes
23
+ test: ruby -Ilib test/cart_test.rb # what runs its tests
24
+ # require: shop # what loads it from lib/, when the name differs
25
+ # sig: [sig] # the signature folders
26
+ ```
27
+
28
+ - `sigmold holes [DIR]` lists each hole with the type Steep wants there and the local variables in scope.
29
+ - `sigmold strict [DIR]` lists every Steep diagnostic at any level, `untyped` in type comments, `steep:ignore`, and `untyped` in public signatures. A Steepfile's defaults show `case/in` (UnsupportedSyntax) only as a hint, and Steep does not check its body. When `untyped` in a signature is meant, mark it `%a{sigmold:untyped}`.
30
+ - `sigmold surface NAMESPACE` lists public methods that `lib/` has and `sig/` does not declare, and methods that `sig/` declares public while `lib/` keeps them private. rbs-inline does not read `private_class_method :name`, so this happens.
31
+ - `sigmold calls NAMESPACE -- TEST COMMAND` runs the tests and lists the methods of NAMESPACE they call that `sig/` does not declare public, and the declared methods no test calls. Mark one that needs no test `%a{sigmold:untested}`.
32
+ - `sigmold pour FILE --sig SIG --agent CMD --into DIR --test CMD --const CLASS [--times N]` writes FILE again N times (2 by default), each in a copy of the checkout without FILE and with SIG cut to its public surface. CMD gets the brief on its standard input and in `SIGMOLD_BRIEF`. The agent may declare its private parts in SIG after a `private` line, so its code can pass `strict`; a rewrite that changes the public part does not count. The rewrites that pass the tests are compared as `gaps` does: with the original, or with each other when FILE is still all holes.
33
+ - `sigmold gaps --const CLASS original=PATH rewrite=PATH...` runs the same random calls on each version and groups where they part. The calls come from the signature: `new`, then public instance and singleton methods with values drawn from their parameter types (a module gets only its own methods). A returned object of the namespace counts by what its readers return. An error counts by its class; add `--messages` to compare its message too. A step you leave free is written in the signature, so the reviewer sees it next to the contract: `%a{sigmold:free: new -> raises ArgumentError}` above the class, or `%a{sigmold:free: returns}` on a method. `--free FILE` still takes keys or steps, one per line. `--explorer E.rb` replaces the drawn calls with your own.
34
+ - `sigmold review [BASE [HEAD]] [--sig DIR]... [--tests DIR]...` shows what a person reviews from BASE (`HEAD` by default) to HEAD (the working tree by default): the diff of the public part of `sig/` and of the tests (`test/` and `spec/` by default). It also lists the dependencies the public signatures name that came or went, such as `+ Shop::Cart -> Shop::Coupon`. It only names a changed file of `lib/`, and a signature whose private part alone changed.
35
+ - `sigmold deps [--sig DIR]...` lists the classes each class's public signature names, the way a reader of C++ headers reads the includes, and exits 1 on a cycle among them.
36
+ - `sigmold hide FILE --sig SIG --into DIR` makes the copy `pour` gives the agent, and prints the brief.
37
+
38
+ Each command exits 1 when it finds something, so CI can require none.
39
+
40
+ ## An example
41
+
42
+ `examples/shop` is a mold that `sigmold check` passes. Two agents poured `lib/shop.rb` from it:
43
+
44
+ ```
45
+ $ sigmold pour lib/shop.rb --sig sig/shop.rbs --agent "claude -p --permission-mode acceptEdits" \
46
+ --into /tmp/pour --test "ruby -Ilib test/cart_test.rb" --const Shop::Cart
47
+ rewrite1: written, tests pass (/tmp/pour/rewrite1/lib/shop.rb)
48
+ rewrite2: written, tests pass (/tmp/pour/rewrite2/lib/shop.rb)
49
+
50
+ 2000 runs, 56 differ, 1 questions
51
+
52
+ 1. What should the last line do? 56 runs part here.
53
+ cart = Shop::Cart.new
54
+ cart.add(Shop::Item.new(name: "b", price: 7), 8)
55
+ cart.add(Shop::Item.new(name: "b", price: -1), 12)
56
+ cart.total
57
+ original: => -20
58
+ rewrite1, rewrite2: => 44
59
+ the rewrites agree and the original differs: check the original
60
+ To make one the contract, a test:
61
+ like original:
62
+ cart = Shop::Cart.new
63
+ cart.add(Shop::Item.new(name: "b", price: 7), 8)
64
+ cart.add(Shop::Item.new(name: "b", price: -1), 12)
65
+ assert_equal(-20, cart.total)
66
+ like rewrite1, rewrite2:
67
+ cart = Shop::Cart.new
68
+ cart.add(Shop::Item.new(name: "b", price: 7), 8)
69
+ cart.add(Shop::Item.new(name: "b", price: -1), 12)
70
+ assert_equal(44, cart.total)
71
+ To leave it free, write this above the class in sig/:
72
+ %a{sigmold:free: total -> returns}
73
+ ```
74
+
75
+ The signature said "adding an item already in the cart adds to its quantity", but not what "the same item" is.
76
+ The original keyed lines by name and kept the newest price; both agents keyed them by the whole item.
77
+ The owner chose the agents' reading. An agent wrote it into the signature and added the test the report offered, and the owner reviewed them with `sigmold review`.
78
+ Three more rewrites then matched the original on all 3000 runs: the mold decides this class.
79
+
80
+ ## In the code
81
+
82
+ ```ruby
83
+ # @rbs (Array[Item], Integer?) -> Integer
84
+ def total(items, coupon)
85
+ Sigmold.hole("total") # Steep: Cannot allow method body have type ::Sigmold::Hole because declared as type ::Integer
86
+ end
87
+
88
+ # @rbs (Circle | Rect | Tri) -> Integer
89
+ def area(shape)
90
+ case shape
91
+ when Circle then shape.r * shape.r * 3
92
+ when Rect then shape.w * shape.h
93
+ else Sigmold.absurd(shape) # Steep: Cannot pass a value of type ::Tri as an argument of type bot
94
+ end
95
+ end
96
+ ```
97
+
98
+ `raise NotImplementedError` passes Steep in silence; a hole names its type.
99
+ Steep 2.1 does not type check `case/in`, so write exhaustive branches with `case/when` and `Sigmold.absurd`.
100
+
101
+ ## Install
102
+
103
+ ```ruby
104
+ # Gemfile
105
+ gem "sigmold", require: false
106
+ gem "steep", require: false
107
+ ```
108
+
109
+ ```ruby
110
+ # Steepfile
111
+ target :lib do
112
+ signature "sig"
113
+ check "lib"
114
+ library "sigmold" # the type of Sigmold.hole; the gem ships its signatures
115
+ end
116
+ ```
117
+
118
+ Code that calls `Sigmold.hole` needs `require "sigmold/hole"`, which loads nothing else.
119
+
120
+ ## Requirements
121
+
122
+ Ruby 3.3 or later. `holes`, `strict`, and `check` read Steep's type check service, so the project needs `steep` in its bundle. `surface`, `calls`, and `gaps` need `rbs`, which comes with Steep. sigmold itself has no runtime dependency.
123
+
124
+ ## License
125
+
126
+ MIT
127
+
128
+ [Japanese](README.ja.md)
data/exe/sigmold ADDED
@@ -0,0 +1,174 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # sigmold check [DIR]
5
+ # Runs holes, strict, surface, and calls as DIR/sigmold.yml says.
6
+ # Exit 1 when any of them finds something.
7
+ # sigmold holes [DIR] [--json]
8
+ # Lists each hole with the type it must become and the variables in scope.
9
+ # sigmold strict [DIR]
10
+ # Lists what lets code past its types: Steep diagnostics at any level,
11
+ # untyped type comments, steep:ignore, and untyped in public signatures.
12
+ # sigmold surface NAMESPACE [--require FEATURE]... [--sig DIR]...
13
+ # Lists public methods that lib/ has and sig/ does not declare, and
14
+ # methods sig/ declares public that lib/ keeps private.
15
+ # sigmold calls NAMESPACE [--sig DIR]... [--from DIR] -- TEST COMMAND
16
+ # Runs the tests and lists methods they call that sig/ does not declare
17
+ # public, and methods sig/ declares that no test calls.
18
+ # sigmold review [BASE [HEAD]] [--sig DIR]... [--tests DIR]...
19
+ # Shows what a person reviews from BASE (HEAD by default) to HEAD (the
20
+ # working tree by default): the public part of sig/, the tests, and the
21
+ # dependencies the public sig/ names. The code and the private parts of
22
+ # sig/ are only named.
23
+ # sigmold deps [--sig DIR]...
24
+ # Lists the classes each class's public signature names, and the cycles
25
+ # among them.
26
+ # sigmold hide FILE --sig SIG --into DIR
27
+ # Copies this checkout to DIR without FILE, with SIG cut to its public
28
+ # surface, and prints the brief for the agent that rewrites FILE.
29
+ # sigmold pour FILE --sig SIG --agent CMD --into DIR [--times N] [--test CMD] [--const CLASS]
30
+ # Has the agent write FILE again N times from the mold alone, runs the
31
+ # tests on each, and with --const compares them as gaps does. A FILE made
32
+ # of holes has no code yet, so the rewrites are compared with each other.
33
+ # sigmold gaps --const CLASS [--sig DIR | --explorer E.rb] LABEL=PATH... [--runs N] [--seed S] [--free FILE]
34
+ # Runs the same random calls on the original (the first LABEL=PATH) and
35
+ # each rewrite, and groups where they part into questions.
36
+ # Each command exits 1 when it finds something, so CI can require none.
37
+
38
+ $LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
39
+ require "sigmold"
40
+ require "optparse"
41
+
42
+ command = ARGV.shift
43
+ options = { runs: 2000, seed: 1, times: 2, from: "test" }
44
+ parser = OptionParser.new do |o|
45
+ o.on("--sig PATH") { options[:sig] = _1; (options[:sigs] ||= []) << _1 }
46
+ o.on("--require FEATURE") { (options[:requires] ||= []) << _1 }
47
+ o.on("--into DIR") { options[:into] = _1 }
48
+ o.on("--explorer PATH") { options[:explorer] = _1 }
49
+ o.on("--root NAME") { options[:root] = _1 }
50
+ o.on("--const NAME") { options[:const] = _1 }
51
+ o.on("--runs N", Integer) { options[:runs] = _1 }
52
+ o.on("--seed N", Integer) { options[:seed] = _1 }
53
+ o.on("--free PATH") { options[:free] = _1 }
54
+ o.on("--agent CMD") { options[:agent] = _1 }
55
+ o.on("--times N", Integer) { options[:times] = _1 }
56
+ o.on("--test CMD") { options[:test] = _1 }
57
+ o.on("--from DIR") { options[:from] = _1 }
58
+ o.on("--tests DIR") { (options[:tests] ||= []) << _1 }
59
+ o.on("--json") { options[:json] = true }
60
+ o.on("--messages") { options[:messages] = true }
61
+ end
62
+ rest = parser.parse(ARGV)
63
+
64
+ def git_files
65
+ files = `git ls-files -z`.split("\0")
66
+ abort "sigmold: run it in a git checkout" unless $?.success?
67
+ files
68
+ end
69
+
70
+ def gaps(options, labelled)
71
+ require "sigmold/explore"
72
+ abort "sigmold gaps: --const" unless options[:const]
73
+ # --const names the class in full, such as Shop::Cart; the module the file
74
+ # opens is its first part unless --root says otherwise. A name below
75
+ # --root, such as Cart, still works.
76
+ root = options[:root] || options[:const].split("::").first
77
+ full = options[:const] == root || options[:const].start_with?("#{root}::") ? options[:const] : "#{root}::#{options[:const]}"
78
+ below = full.delete_prefix(root).delete_prefix("::")
79
+ explorer =
80
+ if options[:explorer]
81
+ load File.expand_path(options[:explorer])
82
+ Object.const_get(:Explorer)
83
+ else
84
+ Sigmold::Explore.new(Sigmold::Signature.new(options[:sigs] || ["sig"]), full, root:, messages: options.fetch(:messages, false))
85
+ end
86
+ impls = labelled.map { |label, path| Sigmold::Impl.new(label, path, root:, const: below) }
87
+ abort "sigmold gaps: give the original and at least one rewrite" if impls.size < 2
88
+ free = options[:free] && File.exist?(options[:free]) ? File.readlines(options[:free], chomp: true).reject(&:empty?) : []
89
+ free += explorer.free if explorer.respond_to?(:free)
90
+ found = Sigmold::Comparison.new(explorer, impls, free:).run(runs: options[:runs], seed: options[:seed])
91
+ puts "not explored, no value of its parameter types can be drawn: #{explorer.skipped.join(', ')}" if explorer.respond_to?(:skipped) && explorer.skipped.any?
92
+ print Sigmold.report(found, impls, runs: options[:runs], explorer:)
93
+ found.empty?
94
+ end
95
+
96
+ case command
97
+ when "check"
98
+ require "sigmold/check"
99
+ ok = Dir.chdir(rest.fetch(0, ".")) { Sigmold::Check.run($stdout) }
100
+ exit(ok ? 0 : 1)
101
+ when "holes"
102
+ require "sigmold/holes"
103
+ require "json"
104
+ found = Sigmold::Holes.find(rest.fetch(0, "."))
105
+ options[:json] ? puts(JSON.pretty_generate(found.map(&:to_h))) : print(Sigmold::Holes.report(found))
106
+ exit(found.empty? ? 0 : 1)
107
+ when "strict"
108
+ require "sigmold/strict"
109
+ found = Sigmold::Strict.find(rest.fetch(0, "."))
110
+ print Sigmold::Strict.report(found)
111
+ exit(found.empty? ? 0 : 1)
112
+ when "surface"
113
+ require "sigmold/surface_check"
114
+ namespace = rest.fetch(0) { abort "sigmold surface: name the namespace, such as Shop" }
115
+ $LOAD_PATH.unshift(File.expand_path("lib"))
116
+ (options[:requires] || [namespace.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase]).each { require _1 }
117
+ found = Sigmold::SurfaceCheck.gaps(Object.const_get(namespace), sig: options[:sigs] || ["sig"], lib: "lib")
118
+ print Sigmold::SurfaceCheck.report(found)
119
+ exit(found.empty? ? 0 : 1)
120
+ when "calls"
121
+ require "sigmold/calls"
122
+ namespace = rest.shift or abort "sigmold calls: name the namespace, such as Shop"
123
+ abort "sigmold calls: give the test command after --" if rest.empty?
124
+ seen, status = Sigmold::Calls.record(namespace, rest, from: options[:from])
125
+ abort "sigmold calls: the tests called nothing in #{namespace} (exit #{status.exitstatus})" if seen.empty?
126
+ found = Sigmold::Calls.gaps(seen, Sigmold::Signature.new(options[:sigs] || ["sig"]), namespace)
127
+ print Sigmold::Calls.report(found)
128
+ exit(found.empty? ? 0 : 1)
129
+ when "review"
130
+ require "sigmold/review"
131
+ print Sigmold::Review.report(base: rest.fetch(0, "HEAD"), head: rest[1], sig: options[:sigs] || ["sig"],
132
+ tests: options[:tests] || %w[test spec])
133
+ when "deps"
134
+ require "sigmold/deps"
135
+ edges = Sigmold::Deps.edges(Sigmold::Signature.new(options[:sigs] || ["sig"]))
136
+ print Sigmold::Deps.report(edges)
137
+ exit(Sigmold::Deps.cycles(edges).empty? ? 0 : 1)
138
+ when "hide"
139
+ require "sigmold/pour"
140
+ file = rest.fetch(0) { abort "sigmold hide: name the file to hide" }
141
+ into = options[:into] or abort "sigmold hide: --into DIR"
142
+ sig = options[:sig] or abort "sigmold hide: --sig PATH"
143
+ Sigmold::Pour.hide(file, sig, into, files: git_files)
144
+ puts Sigmold::Surface.brief(file, sig, into)
145
+ when "pour"
146
+ require "sigmold/pour"
147
+ file = rest.fetch(0) { abort "sigmold pour: name the file to pour" }
148
+ %i[sig agent into].each { abort "sigmold pour: --#{_1}" unless options[_1] }
149
+ rewrites = Sigmold::Pour.run(file:, sig: options[:sig], agent: options[:agent], out: options[:into],
150
+ files: git_files, times: options[:times], test: options[:test])
151
+ print Sigmold::Pour.report(rewrites)
152
+ written = rewrites.select { _1.written && _1.kept }
153
+ passing = written.reject { _1.tests == false } # a rewrite the tests refuse says nothing new
154
+ ok = written.size == rewrites.size && written.all? { _1.tests != false }
155
+ # A file still made of holes is a mold with no code yet: the rewrites
156
+ # are compared with each other.
157
+ original = File.read(file).include?("Sigmold.hole") ? [] : [["original", file]]
158
+ versions = [*original, *passing.map { [_1.label, _1.path] }]
159
+ if options[:const] && versions.size > 1
160
+ puts
161
+ ok = gaps(options, versions) && ok
162
+ end
163
+ exit(ok ? 0 : 1)
164
+ when "gaps"
165
+ labelled = rest.map do |pair|
166
+ label, path = pair.split("=", 2)
167
+ abort "sigmold gaps: write LABEL=PATH, not #{pair}" unless path
168
+ [label, path]
169
+ end
170
+ exit(gaps(options, labelled) ? 0 : 1)
171
+ else
172
+ warn File.read(__FILE__).lines.take_while { _1.start_with?("#") }.drop(2).join
173
+ exit 2
174
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "tmpdir"
5
+ require_relative "signature"
6
+
7
+ module Sigmold
8
+ # Runs the tests with a recorder and compares what they call with what the
9
+ # signature declares. A test that calls past sig/ pins a method a reader
10
+ # of sig/ cannot see, and a rewrite from sig/ cannot know. A declared
11
+ # method no test calls is shape the tests leave open.
12
+ module Calls
13
+ Gap = Data.define(
14
+ :id, #: String
15
+ :where, #: :outside_sig | :untested
16
+ :at #: String?
17
+ )
18
+
19
+ # Owners mark a declared method that tests need not call with this
20
+ # annotation, such as an `inspect` kept for people.
21
+ ALLOW = "sigmold:untested"
22
+
23
+ # Runs +command+ with the recorder loaded and returns what it called.
24
+ #
25
+ # @rbs namespace: String
26
+ # @rbs command: Array[String]
27
+ # @rbs from: String
28
+ # @rbs out: (String | IO)?
29
+ # @rbs return: [Hash[String, String], Process::Status]
30
+ def self.record(namespace, command, from: "test", out: nil)
31
+ Dir.mktmpdir("sigmold-calls") do |dir|
32
+ recorder = File.expand_path("calls_recorder.rb", File.dirname(__FILE__))
33
+ env = {
34
+ "SIGMOLD_CALLS_NAMESPACE" => namespace, "SIGMOLD_CALLS_OUT" => dir,
35
+ "SIGMOLD_CALLS_FROM" => File.expand_path(from),
36
+ "RUBYOPT" => [ENV["RUBYOPT"], "-r#{recorder}"].compact.join(" ")
37
+ }
38
+ out ? system(env, *command, out:, err: out) : system(env, *command)
39
+ status = $? #: Process::Status
40
+ seen = {} #: Hash[String, String]
41
+ Dir.glob(File.join(dir, "*.tsv")).each do |file|
42
+ File.readlines(file, chomp: true).each { |line| id, at = line.split("\t", 2); seen[id.to_s] ||= at.to_s }
43
+ end
44
+ [seen, status]
45
+ end
46
+ end
47
+
48
+ # @rbs seen: Hash[String, String]
49
+ # @rbs signature: Signature
50
+ # @rbs namespace: String
51
+ # @rbs return: Array[Gap]
52
+ def self.gaps(seen, signature, namespace)
53
+ entries = signature.surface(namespace)
54
+ declared = entries.map(&:id)
55
+ outside = (seen.keys - declared).sort.map { Gap.new(id: _1, where: :outside_sig, at: seen[_1]) }
56
+ # A `new` the signature does not declare is the one every class has:
57
+ # nothing to pin. Ruby 3.5 and later also make it without an event a
58
+ # recorder can see.
59
+ untested = entries.reject { seen.key?(_1.id) || _1.annotations.include?(ALLOW) || (_1.name == :new && !signature.own?(_1)) }
60
+ .map { Gap.new(id: _1.id, where: :untested, at: _1.location) }
61
+ outside + untested.sort_by(&:id)
62
+ end
63
+
64
+ # @rbs gaps: Array[Gap]
65
+ # @rbs return: String
66
+ def self.report(gaps)
67
+ return "calls: the tests call the signature and all of it\n" if gaps.empty?
68
+
69
+ gaps.map do |gap|
70
+ text = gap.where == :outside_sig ? "a test calls it and sig/ does not declare it public" : "sig/ declares it and no test calls it"
71
+ "#{gap.id}: #{text} (#{gap.at})\n"
72
+ end.join
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # Loaded with `-r` into a test process that `sigmold calls` starts. It
5
+ # records each method of one namespace that code under one folder calls,
6
+ # and writes the list when the process ends. It loads nothing else, so it
7
+ # changes no load order in the process it watches.
8
+ module Sigmold
9
+ module CallsRecorder
10
+ # @rbs namespace: String
11
+ # @rbs from: String
12
+ # @rbs out: String
13
+ # @rbs lib: String
14
+ def self.start(namespace, from, out, lib) #: void
15
+ seen = {} #: Hash[String, String]
16
+ owners = {} #: Hash[Module, String | false]
17
+ trace = TracePoint.new(:call, :c_call) do |tp|
18
+ mod = tp.defined_class or next
19
+ # `X.new` runs Class#new, and an `initialize` of X's own only when it
20
+ # has one; the class itself is the receiver.
21
+ made = tp.event == :c_call && tp.method_id == :new && mod == Class ? tp.self : nil
22
+ owner = if made.is_a?(Module) then owner_name(made, namespace)
23
+ else owners.fetch(mod) { owners[mod] = owner_name(mod, namespace) }
24
+ end
25
+ next unless owner
26
+
27
+ # For a Ruby method the first frame is the method itself; a C
28
+ # method has no frame of its own. A call that comes through a
29
+ # library, such as minitest's assert_operator, belongs to the code
30
+ # that called the library, so frames outside the tests and lib/ are
31
+ # passed over.
32
+ where = (caller_locations(tp.event == :call ? 2 : 1) || []).find do |at|
33
+ (at.absolute_path || at.path).then { _1&.start_with?(from) || _1&.start_with?(lib) }
34
+ end
35
+ path = where&.absolute_path || where&.path
36
+ next unless path&.start_with?(from)
37
+
38
+ singleton = made ? true : mod.singleton_class?
39
+ id = tp.method_id == :initialize && !singleton ? "#{owner}.new" : "#{owner}#{singleton ? '.' : '#'}#{tp.method_id}"
40
+ seen[id] ||= "#{path.delete_prefix(Dir.pwd + '/')}:#{where&.lineno}"
41
+ end
42
+ trace.enable
43
+ at_exit do
44
+ trace.disable
45
+ File.write(File.join(out, "#{Process.pid}.tsv"), seen.map { "#{_1}\t#{_2}\n" }.join)
46
+ end
47
+ end
48
+
49
+ # The name of the module a method belongs to, when it is in the namespace.
50
+ #
51
+ # @rbs mod: Module
52
+ # @rbs namespace: String
53
+ # @rbs return: String | false
54
+ def self.owner_name(mod, namespace)
55
+ mod = mod.attached_object if mod.is_a?(Class) && mod.singleton_class?
56
+ name = mod.is_a?(Module) ? mod.name.to_s : ""
57
+ name == namespace || name.start_with?("#{namespace}::") ? name : false
58
+ end
59
+ end
60
+ end
61
+
62
+ if (namespace = ENV["SIGMOLD_CALLS_NAMESPACE"]) && (out = ENV["SIGMOLD_CALLS_OUT"])
63
+ folder = ->(name, default) { File.join(File.expand_path(ENV.fetch(name, default)), "") }
64
+ Sigmold::CallsRecorder.start(namespace, folder.("SIGMOLD_CALLS_FROM", "test"), out, folder.("SIGMOLD_CALLS_LIB", "lib"))
65
+ end