tensaku 0.0.1 → 0.2.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/exe/tensaku ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+ # `tensaku mcp`: the MCP server coding agents start over stdio. See `tensaku help`.
3
+ require_relative "../lib/tensaku/cli"
4
+
5
+ Tensaku::CLI.start(ARGV)
@@ -1,16 +1,24 @@
1
1
  require "rails/generators"
2
2
  require "json"
3
+ require "bundler"
3
4
 
4
5
  module Tensaku
5
6
  module Generators
6
7
  # bin/rails generate tensaku:install
7
8
  #
8
- # Checks the Gemfile group, writes the ReActionView initializer, installs the Claude Code skill,
9
- # adds the MCP endpoint to .mcp.json and makes sure tmp/ is ignored. Prints what it changed.
9
+ # Optional: connects coding agents. Checks the Gemfile group, installs the skill, adds
10
+ # `tensaku mcp` (a stdio MCP server) to each agent's project config and makes sure tmp/ is ignored.
11
+ # Prints what it changed.
12
+ #
13
+ # .mcp.json (Claude Code, Copilot CLI) and the skill in .agents/skills (Codex, Cursor, Gemini CLI,
14
+ # OpenCode, Copilot) are always written. The other agents' files are written for the agents named
15
+ # with --agents, or by default for those whose config is already in the project.
10
16
  class InstallGenerator < Rails::Generators::Base
11
- desc "Set up Tensaku: ReActionView initializer, Claude Code skill, .mcp.json entry, gitignore check."
17
+ desc "Connect coding agents to Tensaku: skill, MCP entries, gitignore check."
18
+
19
+ AGENTS = %w[claude codex cursor gemini opencode copilot].freeze
12
20
 
13
- class_option :port, type: :numeric, default: 3000, desc: "Port of the development server, for .mcp.json"
21
+ class_option :agents, type: :array, desc: "Agents to set up: #{AGENTS.join(", ")} or all. Defaults to Claude Code, Copilot and the agents already configured in the project."
14
22
 
15
23
  SKILL = File.expand_path("../../../skills/tensaku/SKILL.md", __dir__)
16
24
 
@@ -18,85 +26,138 @@ module Tensaku
18
26
  gemfile = File.join(destination_root, "Gemfile")
19
27
  return unless File.exist?(gemfile)
20
28
 
21
- if development_only?(File.read(gemfile))
22
- say_status :ok, "tensaku is in the development group", :green
29
+ groups = tensaku_groups(gemfile)
30
+ if groups.nil?
31
+ say_status :skip, "Couldn't read the Gemfile to check tensaku's group. Keep it in the development group.", :yellow
32
+ elsif (groups & %i[default production]).empty?
33
+ say_status :ok, "tensaku is in the #{groups.join(" and ")} group#{"s" if groups.size > 1}", :green
23
34
  else
24
35
  say_status :warning, "Put tensaku in the development group of your Gemfile, so production keeps " \
25
36
  "rendering with Erubi and never loads it:\n\n group :development do\n gem \"tensaku\"\n end\n", :yellow
26
37
  end
27
38
  end
28
39
 
29
- def reactionview_initializer
30
- path = "config/initializers/reactionview.rb"
31
- if File.exist?(File.join(destination_root, path))
32
- say_status :exist, "#{path} (Tensaku turns on intercept_erb and source attribution itself)", :blue
33
- return
40
+ def skill
41
+ create_file ".claude/skills/tensaku/SKILL.md", File.read(SKILL) if agent?("claude")
42
+ create_file ".agents/skills/tensaku/SKILL.md", File.read(SKILL)
43
+ end
44
+
45
+ COMMAND = %w[bundle exec tensaku mcp].freeze
46
+
47
+ # Claude Code and Copilot CLI read .mcp.json.
48
+ def mcp_json
49
+ json_entry(".mcp.json", %w[mcpServers tensaku], { "command" => COMMAND.first, "args" => COMMAND.drop(1) })
50
+ end
51
+
52
+ # Codex reads .codex/config.toml in projects you trust. The table is appended as bytes, so the
53
+ # rest of the file stays as it is.
54
+ def codex
55
+ return unless agent?("codex")
56
+
57
+ path = File.join(destination_root, ".codex/config.toml")
58
+ table = "[mcp_servers.tensaku]\ncommand = \"#{COMMAND.first}\"\nargs = #{COMMAND.drop(1).to_json}\n"
59
+ if File.exist?(path) && File.read(path).match?(/^\s*\[mcp_servers\.tensaku\]/)
60
+ say_status :skip, ".codex/config.toml already has [mcp_servers.tensaku]. It should read:\n\n#{table}", :blue
61
+ elsif File.exist?(path)
62
+ append_to_file ".codex/config.toml", "\n#{table}"
63
+ else
64
+ create_file ".codex/config.toml", table
34
65
  end
66
+ end
35
67
 
36
- create_file path, <<~RUBY
37
- # ReActionView renders ERB with Herb in development. Tensaku turns on ERB interception and adds
38
- # Herb's source attribution itself; the options here are ReActionView's own.
39
- # It's only loaded in development (it comes with Tensaku, in the development group).
40
- if defined?(ReActionView)
41
- ReActionView.configure do |config|
42
- # Herb's dev tools (outlines, Open in Editor). They wrap ERB output in display: contents spans.
43
- config.debug_mode = true
44
- end
45
- end
46
- RUBY
68
+ def cursor
69
+ json_entry(".cursor/mcp.json", %w[mcpServers tensaku], { "command" => COMMAND.first, "args" => COMMAND.drop(1) }) if agent?("cursor")
47
70
  end
48
71
 
49
- def skill
50
- create_file ".claude/skills/tensaku/SKILL.md", File.read(SKILL)
72
+ def gemini
73
+ json_entry(".gemini/settings.json", %w[mcpServers tensaku], { "command" => COMMAND.first, "args" => COMMAND.drop(1) }) if agent?("gemini")
51
74
  end
52
75
 
53
- def mcp_json
54
- path = File.join(destination_root, ".mcp.json")
55
- config = File.exist?(path) ? JSON.parse(File.read(path)) : {}
56
- servers = (config["mcpServers"] ||= {})
57
- entry = { "type" => "http", "url" => "http://localhost:#{options[:port]}/__tensaku/mcp" }
58
- if servers["tensaku"] == entry
59
- say_status :identical, ".mcp.json", :blue
60
- return
61
- end
76
+ # OpenCode takes the command and its arguments as one list.
77
+ def opencode
78
+ return unless agent?("opencode")
62
79
 
63
- servers["tensaku"] = entry
64
- File.write(path, JSON.pretty_generate(config) + "\n")
65
- say_status :update, ".mcp.json (tensaku: #{entry["url"]})", :green
80
+ if File.exist?(File.join(destination_root, "opencode.jsonc"))
81
+ say_status :skip, "opencode.jsonc has comments Tensaku won't rewrite. Add \"tensaku\": { \"type\": \"local\", \"command\": #{COMMAND.to_json} } under \"mcp\".", :yellow
82
+ else
83
+ json_entry("opencode.json", %w[mcp tensaku], { "type" => "local", "command" => COMMAND }, seed: { "$schema" => "https://opencode.ai/config.json" })
84
+ end
66
85
  end
67
86
 
68
87
  def gitignore
69
88
  path = File.join(destination_root, ".gitignore")
70
89
  ignored = File.exist?(path) && File.readlines(path, chomp: true).any? { it.strip.match?(%r{\A/?tmp(/|/\*|/\*\*)?\z}) }
71
90
  if ignored
72
- say_status :ok, "tmp/ is ignored, so notes stay local", :green
91
+ say_status :ok, "tmp/ is ignored, so tmp/tensaku/ stays out of version control", :green
73
92
  elsif File.exist?(path)
74
- append_to_file ".gitignore", "\n# Tensaku notes\n/tmp/tensaku/\n"
93
+ append_to_file ".gitignore", "\n# Tensaku's token, lock, log and screenshots\n/tmp/tensaku/\n"
75
94
  else
76
- create_file ".gitignore", "# Tensaku notes\n/tmp/tensaku/\n"
95
+ create_file ".gitignore", "# Tensaku's token, lock, log and screenshots\n/tmp/tensaku/\n"
77
96
  end
78
97
  end
79
98
 
80
99
  def done
81
100
  say "\nTensaku is ready. Start the server with bin/dev or bin/rails server, open a page, and press " \
82
101
  "Alt+Shift+T (or click the corner button)."
102
+ say "Restart your agent so it starts tensaku mcp. Ask it to do your Tensaku notes, or to watch them " \
103
+ "so the notes you save reach it as you write them."
104
+ say "Codex reads .codex/config.toml once you trust the project." if agent?("codex")
83
105
  end
84
106
 
85
107
  private
86
108
 
87
- def development_only?(gemfile)
88
- lines = gemfile.lines
89
- index = lines.index { it.match?(/^\s*gem\s+["']tensaku["']/) }
90
- return false unless index
91
- return true if lines[index].match?(/group:\s*(:development|\[\s*:development\s*\])/)
92
-
93
- inside = false
94
- lines.each_with_index do |current, number|
95
- inside = true if current.match?(/^\s*group\s+:development\s+do/)
96
- return true if inside && number == index
97
- inside = false if inside && current.match?(/^\s*end\b/)
109
+ def agents
110
+ @agents ||= begin
111
+ named = Array(options[:agents]).flat_map { it.split(",") }.map(&:strip).map(&:downcase)
112
+ if named.include?("all")
113
+ AGENTS
114
+ elsif named.any?
115
+ unknown = named - AGENTS
116
+ say_status :skip, "Unknown agents: #{unknown.join(", ")}. Known: #{AGENTS.join(", ")}", :yellow if unknown.any?
117
+ named & AGENTS
118
+ else
119
+ found = { "codex" => ".codex", "cursor" => ".cursor", "gemini" => ".gemini", "opencode" => "opencode.json" }
120
+ %w[claude copilot] + found.select { |_, path| File.exist?(File.join(destination_root, path)) }.keys
121
+ end
98
122
  end
99
- false
123
+ end
124
+
125
+ def agent?(name)
126
+ agents.include?(name)
127
+ end
128
+
129
+ # Sets the entry at keys in a JSON file, keeping everything else. Rewriting the file is fine here:
130
+ # these are small config files, not templates or translations.
131
+ def json_entry(file, keys, entry, seed: {})
132
+ path = File.join(destination_root, file)
133
+ raw = File.exist?(path) ? File.read(path) : ""
134
+ config = raw.strip.empty? ? seed.dup : JSON.parse(raw)
135
+ unless config.is_a?(Hash) && (config[keys.first].nil? || config[keys.first].is_a?(Hash))
136
+ say_status :error, "#{file} isn't a JSON object with an object at #{keys.first}. Add the tensaku server to it by hand.", :red
137
+ return
138
+ end
139
+
140
+ parent = (config[keys.first] ||= {})
141
+ if parent[keys.last] == entry
142
+ say_status :identical, file, :blue
143
+ return
144
+ end
145
+
146
+ parent[keys.last] = entry
147
+ create_file file, JSON.pretty_generate(config) + "\n", force: true, verbose: false
148
+ say_status :update, "#{file} (tensaku: #{COMMAND.join(" ")})", :green
149
+ rescue JSON::ParserError => error
150
+ say_status :error, "#{file} isn't valid JSON (#{error.message.lines.first.strip}). Fix it, or add the tensaku server by hand.", :red
151
+ end
152
+
153
+ # The groups tensaku is listed in, read the way Bundler reads the Gemfile, or nil when it isn't
154
+ # listed or the Gemfile can't be evaluated here.
155
+ def tensaku_groups(gemfile)
156
+ dsl = Bundler::Dsl.new
157
+ Dir.chdir(destination_root) { dsl.eval_gemfile(gemfile) }
158
+ dsl.dependencies.find { it.name == "tensaku" }&.groups&.map(&:to_sym)
159
+ rescue StandardError, ScriptError
160
+ nil
100
161
  end
101
162
  end
102
163
  end
@@ -0,0 +1,143 @@
1
+ require "json"
2
+
3
+ module Tensaku
4
+ # The agent sessions connected to the app at Tensaku.root. Each `tensaku mcp` process (Session)
5
+ # checks in every few seconds while it runs, and the page reads the rows to say who is connected and
6
+ # what each is doing. A session owns the notes it was handed or started while its process runs
7
+ # (Presence), so two sessions never change the same thing.
8
+ module Agents
9
+ # An agent counts as connected for this long after its process last checked in.
10
+ WINDOW = 20
11
+ SESSION = /\A[a-f0-9]{32}\z/
12
+ COLUMNS = %w[name handle listening cwd pid started_at last version channel].freeze
13
+
14
+ HANDLE_WORDS = [
15
+ %w[amber brisk calm dusky eager fern gilded hazy ivory jolly keen lucid misty noble olive plum quiet rosy sandy tidy umber vivid wary young zesty bold coral dewy frosty grassy lemon mossy],
16
+ %w[fox heron otter lynx wren badger crane finch gecko hare ibis koala lark mole newt owl panda quail raven seal tern vole wolf yak bison camel dingo egret ferret moth stoat toad]
17
+ ].freeze
18
+
19
+ module_function
20
+
21
+ # A check-in: the client's name, its handle, the directory it runs in, when it started, whether a
22
+ # watch_notes call is waiting, whether notes are pushed over a Claude Code channel, its last tool
23
+ # call ({ "tool", "note", "at" }), and the fingerprint of the code it runs (Build). A check-in with
24
+ # nothing new isn't a change.
25
+ def seen!(session, name:, handle: nil, listening: false, channel: false, cwd: nil, started_at: nil, last: nil, version: Build.started)
26
+ Presence.hold(session)
27
+ row = [ name.to_s, (handle || self.handle(session)).to_s, listening ? 1 : 0, cwd, Process.pid, started_at, last && JSON.generate(last), version, channel ? 1 : 0 ]
28
+ Project.write do |db, app|
29
+ before = db.get_first_row("SELECT #{COLUMNS.join(", ")}, seen_at FROM agents WHERE session = ? AND project = ?", [ session, app ])
30
+ db.execute(<<~SQL, [ session, app, *row, Time.now.to_f ])
31
+ INSERT INTO agents (session, project, #{COLUMNS.join(", ")}, seen_at) VALUES (?, ?, #{(%w[?] * COLUMNS.size).join(", ")}, ?)
32
+ ON CONFLICT (session, project) DO UPDATE SET #{(COLUMNS + %w[seen_at]).map { "#{it} = excluded.#{it}" }.join(", ")}
33
+ SQL
34
+ reconnected = before && before["seen_at"] < Time.now.to_f - WINDOW
35
+ Project.changed!(db, app, "agent") if before.nil? || reconnected || before.values_at(*COLUMNS) != row
36
+ end
37
+ end
38
+
39
+ def gone!(session)
40
+ Project.write do |db, app|
41
+ Presence.release(session)
42
+ db.execute("DELETE FROM agents WHERE session = ? AND project = ?", [ session.to_s, app ])
43
+ Project.changed!(db, app, "agent") if db.changes.positive?
44
+ end
45
+ end
46
+
47
+ # Whether session still owns its notes: its process is running. A late check-in (a database busy for
48
+ # a while, a suspended laptop) doesn't free a note an agent is working on; a crashed or closed agent
49
+ # frees it at once.
50
+ def connected?(session)
51
+ return false unless session.to_s.match?(SESSION)
52
+
53
+ Project.read do |db, app|
54
+ db.get_first_value("SELECT 1 FROM agents WHERE session = ? AND project = ?", [ session.to_s, app ]) && Presence.alive?(session)
55
+ end
56
+ end
57
+
58
+ # The sessions that checked in lately and whose process still runs.
59
+ def connected_sessions(db, app, now: Time.now)
60
+ db.execute("SELECT session FROM agents WHERE project = ? AND seen_at > ?", [ app, now.to_f - WINDOW ])
61
+ .map { it["session"] }.select { Presence.alive?(it) }
62
+ end
63
+
64
+ # The agents connected to this app, oldest first, as the page shows them: name, handle, the
65
+ # directory it runs in, when it started, whether it is listening, its last tool call, and the notes
66
+ # it is working on.
67
+ def list(now: Time.now)
68
+ working = Notes.list(status: "working").group_by { it["session"] }
69
+ rows = Project.read { |db, app| db.execute("SELECT * FROM agents WHERE project = ? AND seen_at > ?", [ app, now.to_f - WINDOW ]) }
70
+ rows.select { Presence.alive?(it["session"]) }.map do |row|
71
+ last = row["last"] && JSON.parse(row["last"])
72
+ {
73
+ "name" => row["name"].presence || "MCP agent",
74
+ "handle" => row["handle"],
75
+ "folder" => folder(row["cwd"]),
76
+ "started_at" => row["started_at"],
77
+ "listening" => row["listening"] == 1,
78
+ # Notes are pushed into the session over a Claude Code channel (see Session).
79
+ "channel" => row["channel"] == 1,
80
+ "last" => last.is_a?(Hash) ? last.slice("tool", "note", "at") : nil,
81
+ # Started before Tensaku's code last changed: it should reconnect to run the new code.
82
+ "outdated" => row["version"] != Build.current,
83
+ "working" => Array(working[row["session"]]).map { { "id" => it["id"], "url" => it["url"], "comment" => it["comment"].to_s.squish.truncate(80) } }
84
+ }.compact
85
+ end.sort_by { [ it["started_at"].to_s, it["name"] ] }
86
+ end
87
+
88
+ # The owner fields of a note for the connected session whose handle is handle: that session alone
89
+ # gets it, as if it had claimed it. Blank means any agent.
90
+ def owner(db, app, handle)
91
+ return {} if handle.blank?
92
+
93
+ row = db.execute("SELECT session, name, handle FROM agents WHERE project = ? AND handle = ? AND seen_at > ?", [ app, handle.to_s, Time.now.to_f - WINDOW ])
94
+ .find { Presence.alive?(it["session"]) }
95
+ raise Error, "#{handle} isn't connected any more. Assign the note to another session." unless row
96
+
97
+ { "session" => row["session"], "agent" => "#{row["name"].presence || "MCP agent"} · #{row["handle"]}" }
98
+ end
99
+
100
+ def busy?(db, app, session)
101
+ db.get_first_value("SELECT COUNT(*) FROM notes WHERE project = ? AND session = ? AND status = 'working' AND archived_at IS NULL", [ app, session ]).to_i.positive?
102
+ end
103
+
104
+ # Another connected session that is waiting in watch_notes and working on no note.
105
+ def idle_listener?(db, app, except:)
106
+ db.execute("SELECT session FROM agents WHERE project = ? AND session != ? AND listening = 1 AND seen_at > ?", [ app, except.to_s, Time.now.to_f - WINDOW ])
107
+ .any? { Presence.alive?(it["session"]) && !busy?(db, app, it["session"]) }
108
+ end
109
+
110
+ # Two words from the session id, such as amber-fox, so the person can tell sessions apart on the
111
+ # page and match one to a terminal. offset picks the next pair, for a session whose first pair is
112
+ # taken (free_handle).
113
+ def handle(session, offset = 0)
114
+ hex = session.to_s
115
+ return nil unless hex.match?(SESSION)
116
+
117
+ first, second = HANDLE_WORDS
118
+ n = hex[0, 2].to_i(16) * second.size + hex[2, 2].to_i(16) + offset
119
+ "#{first[(n / second.size) % first.size]}-#{second[n % second.size]}"
120
+ end
121
+
122
+ # The first handle for session that no other connected session of this app has.
123
+ def free_handle(session)
124
+ taken = Project.read do |db, app|
125
+ db.execute("SELECT session, handle FROM agents WHERE project = ? AND session != ? AND seen_at > ?", [ app, session.to_s, Time.now.to_f - WINDOW ])
126
+ .select { Presence.alive?(it["session"]) }.map { it["handle"] }
127
+ end
128
+ (0...(HANDLE_WORDS.first.size * HANDLE_WORDS.last.size)).lazy.map { handle(session, it) }.find { !taken.include?(it) } || handle(session)
129
+ end
130
+
131
+ # A directory as the page shows it: relative to the app root when inside it, else its name.
132
+ def folder(cwd)
133
+ return nil if cwd.blank?
134
+
135
+ path = Pathname(cwd)
136
+ root = Tensaku.root.expand_path
137
+ return "#{root.basename}/" if path == root
138
+ return "#{path.relative_path_from(root)}/" if path.to_s.start_with?("#{root}/")
139
+
140
+ "#{path.basename}/"
141
+ end
142
+ end
143
+ end
@@ -0,0 +1,32 @@
1
+ require "digest"
2
+
3
+ module Tensaku
4
+ # A fingerprint of Tensaku's Ruby code. Each process takes it when it starts (Build.started); comparing
5
+ # it with the code on disk now (Build.current) tells a dev server or an agent's `tensaku mcp` that
6
+ # runs older code than the overlay script, which the page loads fresh on every request. A released
7
+ # gem's files don't change, so there the two differ only after an upgrade.
8
+ module Build
9
+ FILES = File.expand_path("../**/*.rb", __dir__)
10
+ LOCK = Mutex.new
11
+
12
+ module_function
13
+
14
+ def started
15
+ @started ||= current
16
+ end
17
+
18
+ # Hashes the files again only when one of them changed since the last call.
19
+ def current
20
+ LOCK.synchronize do
21
+ stamp = Dir[FILES].sort.map { [ it, File.mtime(it).to_f, File.size(it) ] }
22
+ @current = nil unless @stamp == stamp
23
+ @stamp = stamp
24
+ @current ||= Digest::SHA256.hexdigest(stamp.map { |path, *| File.binread(path) }.join("\0"))[0, 12]
25
+ end
26
+ end
27
+
28
+ def stale?
29
+ started != current
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,155 @@
1
+ require "pathname"
2
+
3
+ module Tensaku
4
+ # The `tensaku` command. `tensaku mcp` is the MCP server an agent starts over stdio. It loads Tensaku
5
+ # and Active Support but not the Rails app, so the dev server doesn't need to be running.
6
+ module CLI
7
+ USAGE = <<~TEXT
8
+ Usage: bundle exec tensaku mcp [--app PATH]...
9
+ bundle exec tensaku notes [COMMAND] [--app PATH]... [--as NAME]
10
+
11
+ tensaku mcp runs Tensaku's MCP server over stdin and stdout. Coding agents start it from their
12
+ project config, such as .mcp.json; `bin/rails generate tensaku:install` writes those entries.
13
+
14
+ tensaku notes does what the MCP tools do, for an agent without MCP:
15
+
16
+ tensaku notes [--status STATUS] [--url PATH] list notes (open, working and question by default;
17
+ STATUS is one of those, resolved, declined,
18
+ active, archived or all)
19
+ tensaku notes show ID one note with its whole thread
20
+ tensaku notes screenshot ID [FILE] save the note's screenshot as a PNG (default:
21
+ tmp/tensaku/screenshots/ID.png in its app)
22
+ tensaku notes start ID mark it as being worked on
23
+ tensaku notes resolve ID REPLY mark a started note resolved, with a one-line reply
24
+ tensaku notes decline ID REASON close it without a change
25
+ tensaku notes ask ID QUESTION ask the person something
26
+ tensaku notes reply ID MESSAGE add a message to its thread
27
+ tensaku notes watch [--since TIME] [--timeout SECONDS]
28
+ wait for notes the person sends (60 seconds by
29
+ default, up to 300)
30
+
31
+ --as NAME is the name the page shows for you (default: tensaku CLI).
32
+
33
+ Both serve the notes of the Rails app that contains the current directory. Run from a directory
34
+ that isn't inside an app, they serve the apps up to two levels below that list tensaku in their
35
+ Gemfile.lock. --app PATH picks an app, and can be given more than once.
36
+ TEXT
37
+
38
+ NOTE_COMMANDS = {
39
+ "show" => [ "get_note", %w[id] ],
40
+ "start" => [ "start_note", %w[id] ],
41
+ "resolve" => [ "resolve_note", %w[id reply] ],
42
+ "decline" => [ "decline_note", %w[id reason] ],
43
+ "ask" => [ "ask_question", %w[id question] ],
44
+ "reply" => [ "reply_to_note", %w[id message] ]
45
+ }.freeze
46
+
47
+ # Directories skipped when looking for apps below the current directory.
48
+ SKIP = %w[node_modules vendor tmp log test spec].freeze
49
+
50
+ module_function
51
+
52
+ def start(argv, input: $stdin, output: $stdout)
53
+ command, *rest = argv
54
+ return output.puts(USAGE) unless %w[mcp notes].include?(command)
55
+
56
+ apps = apps(rest)
57
+ return abort("tensaku: no Rails app with tensaku found from #{Dir.pwd}. Pass --app PATH.") if apps.empty?
58
+
59
+ load_mcp
60
+ return notes(rest, apps, output:) if command == "notes"
61
+
62
+ output.sync = true
63
+ Mcp.new(apps, output:).run(input)
64
+ end
65
+
66
+ # One `tensaku notes` command, run as a session of its own that leaves when it's done. Prints the
67
+ # same text as the MCP tool, and exits 1 when the tool failed.
68
+ def notes(args, apps, output: $stdout)
69
+ options, words = options(args)
70
+ return screenshot(words[1], words[2], apps, output:) if words.first == "screenshot" && words[1]
71
+
72
+ name, arguments = note_call(words, options)
73
+ return output.puts(USAGE) unless name
74
+
75
+ session = Session.new(apps, name: options["as"] || "tensaku CLI")
76
+ result = session.call(name, arguments)
77
+ output.puts(result[:content].map { it[:text] }.join("\n\n"))
78
+ exit(1) if result[:isError]
79
+ ensure
80
+ session&.close
81
+ end
82
+
83
+ # Writes a note's screenshot to file, for an agent that reads images from disk, and prints where.
84
+ def screenshot(id, file, apps, output:)
85
+ app, = Notes.locate(apps, id)
86
+ shot = Tensaku.with_root(app) { Notes.screenshot(id) } or abort "Note #{id} has no screenshot."
87
+ path = Pathname(file || app.join("tmp/tensaku/screenshots/#{id}.png")).expand_path
88
+ path.dirname.mkpath
89
+ path.binwrite(shot["png"])
90
+ output.puts("#{path} (#{shot["width"]}x#{shot["height"]})")
91
+ rescue Notes::NotFound => error
92
+ abort error.message
93
+ end
94
+
95
+ def note_call(words, options)
96
+ subcommand, *values = words
97
+ return [ "list_notes", options.slice("status", "url") ] if subcommand.nil?
98
+ return [ "watch_notes", { "since" => options["since"], "timeout_seconds" => options["timeout"]&.to_i }.compact ] if subcommand == "watch"
99
+
100
+ tool, params = NOTE_COMMANDS[subcommand]
101
+ return nil unless tool && values.size >= params.size
102
+
103
+ [ tool, params.each_with_index.to_h { |param, i| [ param, i == params.size - 1 ? values[i..].join(" ") : values[i] ] } ]
104
+ end
105
+
106
+ # Splits --flag VALUE pairs from the other words. --app is read by apps.
107
+ def options(args)
108
+ options = {}
109
+ words = []
110
+ args = args.dup
111
+ while (arg = args.shift)
112
+ if arg.start_with?("--")
113
+ options[arg.delete_prefix("--")] = args.shift
114
+ else
115
+ words << arg
116
+ end
117
+ end
118
+ [ options.except("app"), words ]
119
+ end
120
+
121
+ # The app roots to serve: those passed with --app, else the app containing pwd, else apps below it.
122
+ def apps(args, pwd: Pathname(Dir.pwd))
123
+ pwd = pwd.expand_path
124
+ named = args.each_cons(2).select { |flag, _| flag == "--app" }.map { |_, path| pwd.join(path).expand_path }
125
+ return named if named.any?
126
+
127
+ inside = pwd.ascend.find { app?(it) }
128
+ return [ inside ] if inside
129
+
130
+ [ "*", "*/*" ].flat_map { pwd.glob("#{it}/config/application.rb") }
131
+ .map { it.dirname.dirname }
132
+ .reject { |root| root.relative_path_from(pwd).each_filename.any? { SKIP.include?(it) || it.start_with?(".") } }
133
+ .select { uses_tensaku?(it) }
134
+ .sort
135
+ end
136
+
137
+ def app?(dir)
138
+ dir.join("config/application.rb").file?
139
+ end
140
+
141
+ def uses_tensaku?(root)
142
+ lock = root.join("Gemfile.lock")
143
+ lock.file? && lock.read.match?(/^ tensaku \(/)
144
+ end
145
+
146
+ def load_mcp
147
+ require "active_support"
148
+ require "active_support/core_ext/object/blank"
149
+ require "active_support/core_ext/string/filters"
150
+ require "active_support/core_ext/hash/keys"
151
+ require "active_support/core_ext/enumerable"
152
+ require "tensaku"
153
+ end
154
+ end
155
+ end
@@ -0,0 +1,91 @@
1
+ require "socket"
2
+ require "digest"
3
+ require "tmpdir"
4
+ require "securerandom"
5
+
6
+ module Tensaku
7
+ # Wakes the processes waiting for an app's notes to change, so none of them polls. A waiting reader
8
+ # (a page's event stream in the dev server, a watch_notes call) listens on a Unix socket of its own
9
+ # in the app's folder; a writer, once its change is committed, connects to each socket there and
10
+ # sends a byte. A socket that refuses the connection belongs to a process that is gone, and is
11
+ # deleted.
12
+ #
13
+ # The sockets live under /tmp (Dir.tmpdir on Windows), in a folder only this user can open, because
14
+ # a socket path is limited to about 100 bytes. Where Unix sockets aren't available, a reader checks
15
+ # once a second instead.
16
+ module Doorbell
17
+ # How long a reader without a socket sleeps between checks.
18
+ FALLBACK = 1.0
19
+
20
+ module_function
21
+
22
+ def dir(root)
23
+ base = Gem.win_platform? ? Dir.tmpdir : "/tmp"
24
+ Pathname(base).join("tensaku-#{Process.uid}", Digest::SHA256.hexdigest(Pathname(root).expand_path.to_s)[0, 12])
25
+ end
26
+
27
+ def ring(root)
28
+ folder = dir(root)
29
+ return unless folder.directory?
30
+
31
+ folder.glob("*.sock").each do |path|
32
+ UNIXSocket.open(path.to_s) { it.write_nonblock("!", exception: false) }
33
+ rescue Errno::ECONNREFUSED, Errno::ENOENT, Errno::ENOTSOCK
34
+ path.delete rescue nil
35
+ rescue SystemCallError, IOError
36
+ nil
37
+ end
38
+ rescue NotImplementedError, SystemCallError
39
+ nil
40
+ end
41
+
42
+ # A reader's socket, for one or more apps.
43
+ class Listener
44
+ def initialize(roots)
45
+ @servers = Array(roots).filter_map do |root|
46
+ folder = Doorbell.dir(root)
47
+ folder.mkpath
48
+ folder.parent.chmod(0o700)
49
+ path = folder.join("#{Process.pid}-#{SecureRandom.hex(3)}.sock")
50
+ [ UNIXServer.new(path.to_s), path ]
51
+ rescue NotImplementedError, SystemCallError, NameError
52
+ nil
53
+ end
54
+ end
55
+
56
+ # Waits until a writer rings or timeout seconds pass. True when rung.
57
+ def wait(timeout)
58
+ if @servers.empty?
59
+ sleep [ timeout, FALLBACK ].min
60
+ return true
61
+ end
62
+ ready, = IO.select(@servers.map(&:first), nil, nil, timeout)
63
+ return false unless ready
64
+
65
+ ready.each do |server|
66
+ while (client = server.accept_nonblock(exception: false)).is_a?(UNIXSocket)
67
+ client.close
68
+ end
69
+ end
70
+ true
71
+ end
72
+
73
+ def close
74
+ @servers.each do |server, path|
75
+ server.close
76
+ path.delete if path.exist?
77
+ rescue SystemCallError, IOError
78
+ nil
79
+ end
80
+ @servers = []
81
+ end
82
+ end
83
+
84
+ def listen(roots)
85
+ listener = Listener.new(roots)
86
+ yield listener
87
+ ensure
88
+ listener&.close
89
+ end
90
+ end
91
+ end