ruby-anything 0.0.0-stage → 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.
Files changed (45) hide show
  1. package/.claude-plugin/marketplace.json +12 -0
  2. package/.claude-plugin/plugin.json +7 -0
  3. package/.mcp.json +8 -0
  4. package/LICENSE +21 -0
  5. package/README.md +82 -2
  6. package/adapters/node/harness.mjs +324 -0
  7. package/adapters/node/package-lock.json +26 -0
  8. package/adapters/node/package.json +7 -0
  9. package/adapters/polyglot/harness.py +350 -0
  10. package/adapters/polyglot/lang_csharp.py +222 -0
  11. package/adapters/polyglot/lang_go.py +283 -0
  12. package/adapters/polyglot/lang_java.py +510 -0
  13. package/adapters/polyglot/lang_kotlin.py +133 -0
  14. package/adapters/polyglot/lang_php.py +156 -0
  15. package/adapters/polyglot/lang_ruby.py +148 -0
  16. package/adapters/polyglot/lang_rust.py +430 -0
  17. package/adapters/polyglot/lang_swift.py +337 -0
  18. package/adapters/python/harness.py +417 -0
  19. package/bin/ruby-anything.js +10 -0
  20. package/docs/assets/how-it-works-dark.svg +51 -0
  21. package/docs/assets/how-it-works-light.svg +51 -0
  22. package/harness/ruby_replay.rb +144 -0
  23. package/package.json +51 -4
  24. package/skills/ruby-anything/SKILL.md +130 -0
  25. package/skills/ruby-anything/frontend.md +64 -0
  26. package/skills/ruby-anything/languages/csharp.md +43 -0
  27. package/skills/ruby-anything/languages/go.md +36 -0
  28. package/skills/ruby-anything/languages/java.md +54 -0
  29. package/skills/ruby-anything/languages/javascript.md +50 -0
  30. package/skills/ruby-anything/languages/kotlin.md +27 -0
  31. package/skills/ruby-anything/languages/php.md +47 -0
  32. package/skills/ruby-anything/languages/python.md +49 -0
  33. package/skills/ruby-anything/languages/rust.md +31 -0
  34. package/skills/ruby-anything/languages/swift.md +27 -0
  35. package/skills/ruby-anything/whole-app.md +168 -0
  36. package/src/adapters.js +60 -0
  37. package/src/analyze.js +183 -0
  38. package/src/app.js +697 -0
  39. package/src/cli.js +75 -0
  40. package/src/detect.js +266 -0
  41. package/src/go.js +139 -0
  42. package/src/mcp.js +89 -0
  43. package/src/setup.js +106 -0
  44. package/src/units.js +444 -0
  45. package/src/util.js +312 -0
@@ -0,0 +1,283 @@
1
+ """Go support for the polyglot adapter.
2
+
3
+ Analysis: top-level `func` declarations (methods are listed as kind=method, not recordable).
4
+ Driver: the target package is copied, rewritten to `package main` (a user `main` becomes
5
+ `ppUserMain`), and a generated `pp_driver.go` decodes JSON args into the declared parameter
6
+ types, calls the function, and maps `(T, error)` returns and panics to outcomes.
7
+ Builds offline (GOPROXY=off), so only stdlib / vendored dependencies are supported.
8
+ """
9
+ import os
10
+ import re
11
+ import subprocess
12
+
13
+ from harness import line_of, match_brace, unit_record
14
+
15
+ EXTS = {".go"}
16
+ THROW = r"\bpanic\(|errors\.New\(|fmt\.Errorf\("
17
+ FUNC_RE = re.compile(r"^func\s+(\(\s*\w*\s*\*?(\w+)[^)]*\)\s*)?([A-Za-z_]\w*)\s*(\[[^\]]*\])?\s*\(([^)]*)\)\s*([^{\n]*)\{", re.M)
18
+
19
+
20
+ def runtime():
21
+ return subprocess.run(["go", "version"], capture_output=True, text=True).stdout.strip().replace("go version ", "")
22
+
23
+
24
+ def imports(text):
25
+ block = re.search(r"import\s*\(([^)]*)\)", text)
26
+ single = re.findall(r'^import\s+"([^"]+)"', text, re.M)
27
+ return sorted(set(re.findall(r'"([^"]+)"', block.group(1)) if block else []) | set(single))
28
+
29
+
30
+ def parse_params(raw):
31
+ params, pending = [], []
32
+ for part in [p.strip() for p in raw.split(",") if p.strip()]:
33
+ bits = part.split(None, 1)
34
+ if len(bits) == 1: # name without type yet (`a, b int`) or an unnamed type
35
+ pending.append(bits[0])
36
+ continue
37
+ name, typ = bits
38
+ for p in pending:
39
+ params.append({"name": p, "annotation": typ.strip(), "default": None, "kind": "positional"})
40
+ pending = []
41
+ params.append({"name": name, "annotation": typ.strip(), "default": None,
42
+ "kind": "varargs" if typ.strip().startswith("...") else "positional"})
43
+ return params
44
+
45
+
46
+ def analyze_file(rel, text):
47
+ if rel.endswith("_test.go"):
48
+ return []
49
+ pkg = (re.search(r"^package\s+(\w+)", text, re.M) or [None, "main"])[1]
50
+ units = []
51
+ for m in FUNC_RE.finditer(text):
52
+ name = m.group(3)
53
+ if name in ("main", "init") or m.group(4): # entrypoints and generic functions are not recordable
54
+ continue
55
+ end = match_brace(text, m.end() - 1)
56
+ units.append(unit_record(rel, pkg, name, m.start(), end, text, parse_params(m.group(5)),
57
+ m.group(6).strip() or None, THROW, owner=m.group(2)))
58
+ return units
59
+
60
+
61
+ def returns_of(ret):
62
+ ret = (ret or "").strip()
63
+ if not ret:
64
+ return []
65
+ if ret.startswith("("):
66
+ inner = ret[1:-1]
67
+ return [p.split()[-1] for p in inner.split(",") if p.strip()]
68
+ return [ret]
69
+
70
+
71
+ DRIVER = r'''package main
72
+
73
+ import (
74
+ "encoding/json"
75
+ "fmt"
76
+ "math"
77
+ "os"
78
+ "reflect"
79
+ "regexp"
80
+ "runtime/debug"
81
+ "strconv"
82
+ "time"
83
+ )
84
+
85
+ func ppSpecial(s string) float64 {
86
+ switch s {
87
+ case "nan":
88
+ return math.NaN()
89
+ case "inf":
90
+ return math.Inf(1)
91
+ case "-inf":
92
+ return math.Inf(-1)
93
+ case "-0.0":
94
+ return math.Copysign(0, -1)
95
+ }
96
+ f, _ := strconv.ParseFloat(s, 64)
97
+ return f
98
+ }
99
+
100
+ func ppDecode(raw json.RawMessage, target interface{}) error {
101
+ var tag map[string]interface{}
102
+ if json.Unmarshal(raw, &tag) == nil {
103
+ if s, ok := tag["$float"].(string); ok {
104
+ el := reflect.ValueOf(target).Elem()
105
+ if el.Kind() == reflect.Float64 || el.Kind() == reflect.Float32 {
106
+ el.SetFloat(ppSpecial(s))
107
+ return nil
108
+ }
109
+ return fmt.Errorf("cannot use float %s as %s", s, el.Type())
110
+ }
111
+ }
112
+ return json.Unmarshal(raw, target)
113
+ }
114
+
115
+ func ppEnc(v interface{}) interface{} {
116
+ if v == nil {
117
+ return nil
118
+ }
119
+ rv := reflect.ValueOf(v)
120
+ switch rv.Kind() {
121
+ case reflect.Float32, reflect.Float64:
122
+ f := rv.Float()
123
+ switch {
124
+ case math.IsNaN(f):
125
+ return map[string]string{"$float": "nan"}
126
+ case math.IsInf(f, 1):
127
+ return map[string]string{"$float": "inf"}
128
+ case math.IsInf(f, -1):
129
+ return map[string]string{"$float": "-inf"}
130
+ case f == 0 && math.Signbit(f):
131
+ return map[string]string{"$float": "-0.0"}
132
+ case f == math.Trunc(f) && math.Abs(f) > 9007199254740992:
133
+ return map[string]string{"$float": strconv.FormatFloat(f, 'g', -1, 64)}
134
+ case f == math.Trunc(f):
135
+ return json.Number(strconv.FormatFloat(f, 'f', 1, 64)) // keep 2.0 a float in JSON
136
+ }
137
+ return f
138
+ case reflect.Slice, reflect.Array:
139
+ if rv.Kind() == reflect.Slice && rv.IsNil() {
140
+ return []interface{}{}
141
+ }
142
+ out := make([]interface{}, rv.Len())
143
+ for i := range out {
144
+ out[i] = ppEnc(rv.Index(i).Interface())
145
+ }
146
+ return out
147
+ case reflect.Map:
148
+ out := map[string]interface{}{}
149
+ for _, k := range rv.MapKeys() {
150
+ out[fmt.Sprint(k.Interface())] = ppEnc(rv.MapIndex(k).Interface())
151
+ }
152
+ return out
153
+ }
154
+ return v
155
+ }
156
+
157
+ var ppFile = regexp.MustCompile(`/__FILE__:(\d+)`)
158
+
159
+ func ppRaise(typ, msg string, line int) map[string]interface{} {
160
+ o := map[string]interface{}{"kind": "raise", "type": typ, "message": msg}
161
+ if line > 0 {
162
+ o["raise_line"] = line
163
+ }
164
+ return o
165
+ }
166
+
167
+ func ppErrType(err error) string {
168
+ t := fmt.Sprintf("%T", err)
169
+ if t == "*errors.errorString" || t == "*fmt.wrapError" || t == "*fmt.wrapErrors" {
170
+ return "error"
171
+ }
172
+ return t
173
+ }
174
+
175
+ func ppCall(call func() (interface{}, error)) (o map[string]interface{}) {
176
+ defer func() {
177
+ if r := recover(); r != nil {
178
+ line := 0
179
+ if m := ppFile.FindAllStringSubmatch(string(debug.Stack()), -1); len(m) > 0 {
180
+ line, _ = strconv.Atoi(m[0][1])
181
+ }
182
+ o = ppRaise("panic", fmt.Sprint(r), line)
183
+ }
184
+ }()
185
+ v, err := call()
186
+ if err != nil {
187
+ return ppRaise(ppErrType(err), err.Error(), 0)
188
+ }
189
+ return map[string]interface{}{"kind": "return", "value": ppEnc(v)}
190
+ }
191
+
192
+ func ppWrite(v interface{}) {
193
+ b, _ := json.Marshal(v)
194
+ _ = os.WriteFile(os.Getenv("PP_RESULT"), b, 0o600)
195
+ }
196
+
197
+ func main() {
198
+ var req struct {
199
+ Mode string `json:"mode"`
200
+ Args []json.RawMessage `json:"args"`
201
+ Iterations int `json:"iterations"`
202
+ }
203
+ _ = json.NewDecoder(os.Stdin).Decode(&req)
204
+ __DECODE__
205
+ call := func() (interface{}, error) {
206
+ __CALL__
207
+ }
208
+ if req.Mode == "bench" {
209
+ samples := make([]int64, 0, req.Iterations)
210
+ for i := 0; i < req.Iterations; i++ {
211
+ t0 := time.Now()
212
+ ppCall(call)
213
+ samples = append(samples, time.Since(t0).Nanoseconds())
214
+ }
215
+ ppWrite(map[string]interface{}{"samples_ns": samples})
216
+ return
217
+ }
218
+ ppWrite(map[string]interface{}{"outcome": ppCall(call)})
219
+ }
220
+ '''
221
+
222
+
223
+ def prepare(src, rel, unit, work):
224
+ if unit["kind"] != "function":
225
+ raise SystemExit("only top-level Go functions can be recorded")
226
+ pkg_dir = os.path.join(src, os.path.dirname(rel))
227
+ if not any(os.path.exists(os.path.join(d, "go.mod")) for d in _parents(pkg_dir, src)):
228
+ with open(os.path.join(src, "go.mod"), "w") as fh:
229
+ fh.write("module ppsrc\n\ngo 1.21\n")
230
+ for name in os.listdir(pkg_dir): # the package becomes `main` so unexported functions are callable
231
+ if name.endswith(".go") and not name.endswith("_test.go"):
232
+ p = os.path.join(pkg_dir, name)
233
+ code = open(p, encoding="utf-8").read()
234
+ code = re.sub(r"^package\s+\w+", "package main", code, count=1, flags=re.M)
235
+ code = re.sub(r"^func\s+main\s*\(", "func ppUserMain(", code, flags=re.M)
236
+ open(p, "w", encoding="utf-8").write(code)
237
+
238
+ decode, args = [], []
239
+ for i, p in enumerate(unit["params"]):
240
+ typ = p["annotation"]
241
+ if typ.startswith("..."):
242
+ typ = "[]" + typ[3:]
243
+ args.append(f"a{i}...")
244
+ else:
245
+ args.append(f"a{i}")
246
+ decode.append(f"\tvar a{i} {typ}\n\tif len(req.Args) > {i} {{\n\t\tif err := ppDecode(req.Args[{i}], &a{i}); err != nil {{\n"
247
+ f"\t\t\tppWrite(map[string]interface{{}}{{\"outcome\": ppRaise(\"TypeError\", err.Error(), 0)}})\n\t\t\treturn\n\t\t}}\n\t}}")
248
+ call = f"{unit['name']}({', '.join(args)})"
249
+ rets = returns_of(unit["returns"])
250
+ if not rets:
251
+ body = f"\t\t{call}\n\t\treturn nil, nil"
252
+ elif rets == ["error"]:
253
+ body = f"\t\treturn nil, {call}"
254
+ elif len(rets) == 2 and rets[1] == "error":
255
+ body = f"\t\tr0, err := {call}\n\t\treturn r0, err"
256
+ elif len(rets) == 1:
257
+ body = f"\t\treturn {call}, nil"
258
+ else:
259
+ names = [f"r{i}" for i in range(len(rets))]
260
+ tail_err = rets[-1] == "error"
261
+ body = f"\t\t{', '.join(names)} := {call}\n"
262
+ if tail_err:
263
+ body += f"\t\tif {names[-1]} != nil {{\n\t\t\treturn nil, {names[-1]}\n\t\t}}\n\t\treturn []interface{{}}{{{', '.join(names[:-1])}}}, nil"
264
+ else:
265
+ body += f"\t\treturn []interface{{}}{{{', '.join(names)}}}, nil"
266
+ driver = DRIVER.replace("__DECODE__", "\n".join(decode)).replace("__CALL__", body) \
267
+ .replace("__FILE__", re.escape(os.path.basename(rel)))
268
+ open(os.path.join(pkg_dir, "pp_driver.go"), "w", encoding="utf-8").write(driver)
269
+ out = os.path.join(work, "ppdrv")
270
+ env = dict(os.environ, GOCACHE=os.path.join(work, "gocache"), GOPATH=os.path.join(work, "gopath"),
271
+ GOFLAGS="-mod=mod", GOPROXY="off", GOTOOLCHAIN="local", CGO_ENABLED="0", HOME=work)
272
+ subprocess.run(["go", "build", "-o", out, "."], cwd=pkg_dir, env=env, check=True, capture_output=True)
273
+ return [out]
274
+
275
+
276
+ def _parents(path, stop):
277
+ path = os.path.abspath(path)
278
+ stop = os.path.abspath(stop)
279
+ while True:
280
+ yield path
281
+ if path == stop or len(path) <= len(stop):
282
+ return
283
+ path = os.path.dirname(path)