hamster-web 0.1.0.pre.3 → 0.1.0.pre.5

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 (78) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +42 -0
  3. data/README.md +478 -7
  4. data/lib/hamster/agent_guidance.rb +56 -0
  5. data/lib/hamster/application_graph.rb +336 -0
  6. data/lib/hamster/build/assets.rb +72 -0
  7. data/lib/hamster/build/callbacks.rb +124 -0
  8. data/lib/hamster/build/jobs.rb +78 -0
  9. data/lib/hamster/build/manifest.rb +31 -9
  10. data/lib/hamster/build/query_accessors.rb +18 -0
  11. data/lib/hamster/check.rb +122 -0
  12. data/lib/hamster/cli.rb +92 -12
  13. data/lib/hamster/data/persistence.rb +11 -6
  14. data/lib/hamster/data/read/nodes.rb +2 -0
  15. data/lib/hamster/data/read/schema.rb +28 -16
  16. data/lib/hamster/data/read/validator.rb +3 -0
  17. data/lib/hamster/data/record.rb +15 -1
  18. data/lib/hamster/data/table.rb +22 -3
  19. data/lib/hamster/database/database.rb +2 -25
  20. data/lib/hamster/database/migrator.rb +151 -0
  21. data/lib/hamster/database/pool.rb +7 -3
  22. data/lib/hamster/database/result.rb +3 -3
  23. data/lib/hamster/dev.rb +116 -0
  24. data/lib/hamster/endpoint_generator.rb +7 -0
  25. data/lib/hamster/form.rb +110 -0
  26. data/lib/hamster/generators/plan.rb +96 -0
  27. data/lib/hamster/generators/runner.rb +168 -0
  28. data/lib/hamster/jobs/adapters.rb +106 -0
  29. data/lib/hamster/jobs/postgres_queue.rb +146 -0
  30. data/lib/hamster/jobs/worker.rb +103 -0
  31. data/lib/hamster/jobs.rb +116 -0
  32. data/lib/hamster/migration.rb +36 -0
  33. data/lib/hamster/native_smoke.rb +53 -0
  34. data/lib/hamster/schema_validation.rb +4 -2
  35. data/lib/hamster/storage/disk.rb +89 -0
  36. data/lib/hamster/storage.rb +152 -0
  37. data/lib/hamster/test_database.rb +63 -0
  38. data/lib/hamster/test_runner.rb +29 -0
  39. data/lib/hamster/testing.rb +110 -0
  40. data/lib/hamster/web/action/base.rb +49 -4
  41. data/lib/hamster/web/application.rb +9 -0
  42. data/lib/hamster/web/assets.rb +28 -0
  43. data/lib/hamster/web/context.rb +122 -1
  44. data/lib/hamster/web/files.rb +118 -0
  45. data/lib/hamster/web/http.rb +4 -2
  46. data/lib/hamster/web/json.rb +39 -0
  47. data/lib/hamster/web/multipart.rb +138 -0
  48. data/lib/hamster/web/router.rb +13 -2
  49. data/lib/hamster/web/routing/base.rb +4 -2
  50. data/lib/hamster/web/turbo.rb +24 -0
  51. data/lib/hamster/web/version.rb +1 -1
  52. data/lib/hamster/web/view/form.rb +18 -1
  53. data/lib/hamster/web.rb +9 -0
  54. data/templates/app/.agents/skills/hamster-database/SKILL.md +29 -0
  55. data/templates/app/.agents/skills/hamster-endpoint/SKILL.md +27 -0
  56. data/templates/app/.dockerignore +1 -0
  57. data/templates/app/AGENTS.md +20 -7
  58. data/templates/app/Dockerfile +24 -0
  59. data/templates/app/Gemfile +5 -1
  60. data/templates/app/README.md +303 -3
  61. data/templates/app/app/assets/application.css +2 -0
  62. data/templates/app/app/assets/application.js +2 -0
  63. data/templates/app/app/assets/controllers/hello_controller.js +5 -0
  64. data/templates/app/app/assets/vendor/VERSIONS.md +12 -0
  65. data/templates/app/app/assets/vendor/stimulus.LICENSE.txt +9 -0
  66. data/templates/app/app/assets/vendor/stimulus.js +2563 -0
  67. data/templates/app/app/assets/vendor/turbo.LICENSE.txt +20 -0
  68. data/templates/app/app/assets/vendor/turbo.js +7178 -0
  69. data/templates/app/app/views/layouts/application.html.erb +2 -1
  70. data/templates/app/bin/hamster +8 -0
  71. data/templates/app/bin/server +13 -1
  72. data/templates/app/bin/worker +24 -0
  73. data/templates/app/config/deploy.worker.yml.example +32 -0
  74. data/templates/app/test/home_test.rb +8 -0
  75. data/templates/app/test/native_http.rb +11 -0
  76. data/templates/app/test/native_server.rb +10 -0
  77. data/templates/app/test/test_helper.rb +8 -0
  78. metadata +55 -10
@@ -1,9 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "ripper"
4
+ require "fileutils"
4
5
  require_relative "../web"
5
6
  require_relative "view_compiler"
6
7
  require_relative "query_accessors"
8
+ require_relative "callbacks"
9
+ require_relative "assets"
10
+ require_relative "jobs"
7
11
 
8
12
  module Hamster
9
13
  module Build
@@ -11,11 +15,14 @@ module Hamster
11
15
  module_function
12
16
 
13
17
  def outputs(root)
14
- paths = Dir.glob("{app,db}/**/*.rb", base: root).sort_by do |path|
18
+ paths = Dir.glob("{app,db}/**/*.rb", base: root).reject { |path| path.start_with?("db/migrations/") }.sort_by do |path|
15
19
  priority = path.start_with?("db/") ? 0 : path.start_with?("app/models/") ? 1 : 2
16
- priority = 3 if path == "app/routes/mappings.rb"
20
+ priority = 2 if path.start_with?("app/concerns/")
21
+ priority = 3 if path.start_with?("app/routes/")
22
+ priority = 4 if path == "app/routes/mappings.rb"
17
23
  [priority, path]
18
24
  end
25
+ paths = Callbacks.order(paths.to_h { |path| [path, File.read(File.join(root, path))] })
19
26
  sources = {}
20
27
  Dir.glob("{app/routes,app/views}/**/*.html.erb", base: root).sort.each do |path|
21
28
  name = path.sub(%r{\Aapp/(?:routes|views)/}, "").sub(%r{/view\.html\.erb\z}, "").delete_suffix(".html.erb")
@@ -25,21 +32,36 @@ module Hamster
25
32
  lines = paths.map { |path| %(require_relative "../#{path.delete_suffix('.rb')}") }
26
33
  paths.each { |path| lines.concat(QueryAccessors.lines(File.read(File.join(root, path)))) }
27
34
  paths.each { |path| lines.concat(QueryAccessors.lines(File.read(File.join(root, path)), declaration: "column", writers: true)) }
35
+ lines.concat(QueryAccessors.schema_guards(paths.map { |path| File.read(File.join(root, path)) }))
36
+ lines << 'require_relative "callback_registry"'
28
37
  lines << 'require_relative "view_registry"'
38
+ lines << 'require_relative "asset_registry"'
39
+ lines << 'require_relative "job_registry"'
40
+ assets = Assets.outputs(root)
41
+ sources.each_value do |template|
42
+ template[:source].scan(/Hamster::Assets.path\(["']([^"']+)["']\)/).flatten.each do |name|
43
+ raise View::Error, "#{template[:path]}:1: missing asset #{name}" unless assets["public/assets/manifest.json"].include?(name.to_json)
44
+ end
45
+ end
29
46
  {
30
47
  "config/manifest.rb" => "# frozen_string_literal: true\n# Generated by hamster manifest.\n" + lines.join("\n") + "\n",
31
- "config/view_registry.rb" => ViewCompiler.compile(sources)
32
- }
48
+ "config/view_registry.rb" => ViewCompiler.compile(sources),
49
+ "config/job_registry.rb" => Jobs.compile(paths.map { |path| File.read(File.join(root, path)) }),
50
+ "config/callback_registry.rb" => Callbacks.compile(paths.map { |path| File.read(File.join(root, path)) })
51
+ }.merge(assets)
33
52
  end
34
53
 
35
54
  def generate(root)
36
- outputs(root).each { |path, content| File.write(File.join(root, path), content) }
55
+ outputs(root).each do |path, content|
56
+ FileUtils.mkdir_p(File.dirname(File.join(root, path)))
57
+ File.binwrite(File.join(root, path), content)
58
+ end
37
59
  end
38
60
 
39
- def check(root)
40
- issues = outputs(root).filter_map do |path, expected|
41
- actual = File.file?(File.join(root, path)) ? File.read(File.join(root, path)) : nil
42
- "#{path} is missing or stale; run bin/hamster manifest" unless actual == expected
61
+ def check(root, expected: nil)
62
+ issues = (expected || outputs(root)).filter_map do |path, expected|
63
+ actual = File.file?(File.join(root, path)) ? File.binread(File.join(root, path)) : nil
64
+ "#{path} is missing or stale; run bin/hamster manifest" unless actual == expected.b
43
65
  end
44
66
  Dir.glob("{app,db}/**/*.rb", base: root).each do |path|
45
67
  Ripper.lex(File.read(File.join(root, path))).each do |position, type, token, _|
@@ -18,6 +18,24 @@ module Hamster
18
18
  end
19
19
  end
20
20
 
21
+ def schema_guards(sources)
22
+ definitions = {}
23
+ sources.each { |source| Build::Callbacks.scan(Ripper.sexp(source), "", definitions) }
24
+ tables = []
25
+ loop do
26
+ found = definitions.keys.reject { |name| tables.include?(name) }.select do |name|
27
+ parent = definitions[name][:parent]
28
+ scopes = name.split("::")[0...-1]
29
+ parent == "Hamster::Table" || scopes.length.downto(0).any? { |n| tables.include?((scopes.take(n) + [parent]).compact.join("::")) }
30
+ end
31
+ break if found.empty?
32
+ tables.concat(found)
33
+ end
34
+ tables.sort.flat_map do |path|
35
+ ["class #{path}", " def assert_compiled_record_column_enabled!(name)", " #{path}.assert_column_enabled!(name)", " raise Hamster::MissingAttributeError, \"Undeclared attribute #{'#{name}'}\" unless #{path}.columns.key?(name.to_sym)", " end", "end"]
36
+ end
37
+ end
38
+
21
39
  def constant(node)
22
40
  return nil unless node.is_a?(Array)
23
41
  case node[0]
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+ require "ripper"
3
+ require "json"
4
+ require "open3"
5
+ require "rbconfig"
6
+ require "fileutils"
7
+ require_relative "build/manifest"
8
+
9
+ module Hamster
10
+ module Check
11
+ module_function
12
+ class Parser < Ripper::SexpBuilderPP
13
+ attr_reader :errors
14
+ def initialize(source)
15
+ super(source)
16
+ @errors = []
17
+ end
18
+ def on_parse_error(message)
19
+ @errors << [lineno, message]
20
+ end
21
+ end
22
+ def diagnostic(code, message, path = nil, line = nil)
23
+ {"code" => code, "message" => message, "path" => path, "line" => line}
24
+ end
25
+ def run(root, full: false)
26
+ issues = []
27
+ paths = Dir.glob("{app,db,config,test}/**/*.rb", base: root).sort
28
+ paths.each do |path|
29
+ source = File.read(File.join(root, path))
30
+ parser = Parser.new(source)
31
+ parser.parse
32
+ parser.errors.each { |line, message| issues << diagnostic("ruby.syntax", message, path, line) }
33
+ end
34
+ if issues.empty?
35
+ begin
36
+ Build::Manifest.check(root).each do |message|
37
+ path, line = location(message)
38
+ issues << diagnostic("manifest.stale", message, path, line)
39
+ end
40
+ rescue StandardError => error
41
+ path, line = location(error.message)
42
+ issues << diagnostic("manifest.invalid", error.message, path, line)
43
+ end
44
+ paths.grep(%r{\Aapp/}).each do |path|
45
+ source = File.read(File.join(root, path))
46
+ source.lines.each_with_index do |line, index|
47
+ line.scan(/\brespond\s*\(\s*view:\s*["']([^"']+)["']/).flatten.each do |view|
48
+ present = ["app/routes/#{view}/view.html.erb", "app/views/#{view}.html.erb"].any? { |p| File.file?(File.join(root, p)) }
49
+ issues << diagnostic("view.missing", "Missing view #{view}", path, index + 1) unless present
50
+ end
51
+ end
52
+ end
53
+ end
54
+ if issues.empty?
55
+ require_relative "application_graph"
56
+ graph = ApplicationGraph.new(root).build.report
57
+ graph["diagnostics"].select { |d| d["severity"] == "error" }.each do |d|
58
+ issues << diagnostic(d["code"], d["message"], d["path"], d["line"])
59
+ end
60
+ end
61
+ completed = ["syntax", "manifest", "conventions"]
62
+ if full && issues.empty?
63
+ test_files = Dir.glob("test/**/*_test.rb", base: root).sort
64
+ unless test_files.empty?
65
+ output, status = Open3.capture2e({"HAMSTER_ENV" => "test"}, RbConfig.ruby, "-I", File.expand_path("..", __dir__), "-Itest", "-e", 'ARGV.each { |path| require File.expand_path(path) }', *test_files, chdir: root)
66
+ issues << diagnostic("test.failed", output, "test") unless status.success?
67
+ end
68
+ completed << "tests"
69
+ begin
70
+ require_relative "native_smoke"
71
+ NativeSmoke.run(root)
72
+ rescue StandardError => error
73
+ issues << diagnostic("native.failed", error.message, "test/native_server.rb")
74
+ end
75
+ completed << "native"
76
+ end
77
+ {"format_version" => 1, "mode" => full ? "full" : "quick", "valid" => issues.empty?, "checks" => completed, "diagnostics" => issues}
78
+ rescue StandardError => error
79
+ {"format_version" => 1, "mode" => full ? "full" : "quick", "valid" => false, "checks" => [], "diagnostics" => [diagnostic("check.failed", error.message)]}
80
+ end
81
+ def location(message)
82
+ match = message.match(/\A([^\s:]+)(?::(\d+))?/)
83
+ path = match && match[1].include?("/") ? match[1] : nil
84
+ [path, match && match[2] ? match[2].to_i : nil]
85
+ end
86
+ def cli(root, args)
87
+ raise ArgumentError, "Usage: check [--quick | --full] [--json]" unless (args - %w[--quick --full --json]).empty? && !(args.include?("--quick") && args.include?("--full"))
88
+ report = run(root, full: args.include?("--full"))
89
+ if args.include?("--json")
90
+ puts JSON.generate(report)
91
+ else
92
+ report["diagnostics"].each { |d| puts "#{d['code']} #{[d['path'], d['line']].compact.join(':')}: #{d['message']}" }
93
+ puts "#{report['mode']} checks #{report['valid'] ? 'passed' : 'failed'}"
94
+ end
95
+ report["valid"] ? 0 : 1
96
+ end
97
+
98
+ def install_hooks(root, args)
99
+ raise ArgumentError, "Usage: hooks:install [--pre-push]" unless (args - ["--pre-push"]).empty?
100
+ output, status = Open3.capture2e("git", "rev-parse", "--show-toplevel", chdir: root)
101
+ raise "Application must be a Git repository root" unless status.success? && File.realpath(output.strip) == File.realpath(root)
102
+ files = {"pre-commit" => "--quick"}
103
+ files["pre-push"] = "--full" if args.include?("--pre-push")
104
+ directory = File.join(root, ".githooks")
105
+ raise "Symlink hook directory" if File.symlink?(directory)
106
+ files.each do |name, mode|
107
+ path = File.join(directory, name)
108
+ source = "#!/bin/sh\n# Managed Hamster hook\nexec bin/hamster check #{mode}\n"
109
+ raise "Customized hook exists: #{path}" if File.exist?(path) && File.read(path) != source || File.symlink?(path)
110
+ end
111
+ FileUtils.mkdir_p(directory)
112
+ files.each do |name, mode|
113
+ path = File.join(directory, name)
114
+ File.write(path, "#!/bin/sh\n# Managed Hamster hook\nexec bin/hamster check #{mode}\n")
115
+ File.chmod(0755, path)
116
+ end
117
+ raise "Cannot configure Git hooks" unless system("git", "config", "--local", "core.hooksPath", ".githooks", chdir: root)
118
+ puts "Installed explicit project hooks in .githooks"
119
+ 0
120
+ end
121
+ end
122
+ end
data/lib/hamster/cli.rb CHANGED
@@ -18,14 +18,37 @@ module Hamster
18
18
  when "--version"
19
19
  puts Web::VERSION
20
20
  0
21
+ when "generate"
22
+ require_relative "endpoint_generator"
23
+ EndpointGenerator.run(root, args)
24
+ 0
25
+ when "inspect"
26
+ require_relative "application_graph"
27
+ ApplicationGraph.cli(root, args)
28
+ when "dev"
29
+ require_relative "dev"
30
+ Dev.run(root, args)
31
+ when "test"
32
+ require_relative "test_runner"
33
+ TestRunner.run(root, args)
34
+ when "check", "hooks:install"
35
+ require_relative "check"
36
+ command == "check" ? Check.cli(root, args) : Check.install_hooks(root, args)
37
+ when "agents:install"
38
+ raise ArgumentError, "Usage: agents:install [--dry-run]" unless args.empty? || args == ["--dry-run"]
39
+ require_relative "agent_guidance"
40
+ AgentGuidance.install(root, dry_run: args == ["--dry-run"]) ? 0 : 1
21
41
  when "new"
22
42
  raise ArgumentError, "Usage: hamster new AppName" unless args.length == 1
23
43
  Generator.create(args.first)
24
44
  0
25
45
  when nil, "help", "--help", "-h"
26
- puts "Usage: hamster new AppName | setup | manifest | manifest:check | build | serve | routes | console | db:create | db:migrate | db:validate"
46
+ puts "Usage: hamster new AppName | generate --help | check [--quick|--full] [--json] | test [path] [--json] | hooks:install [--pre-push] | agents:install [--dry-run] | inspect [--json] | dev | setup | manifest | manifest:check | build | build:worker | jobs:work [--once] | jobs:status [--json] | serve | routes | console | db:create | db:migrate | db:rollback [STEP=n] | db:migrate:status | db:migrate:history --json | db:structure:dump | db:validate"
27
47
  0
28
48
  else
49
+ if %w[db:rollback db:migrate:history db:validate jobs:status jobs:work].include?(command)
50
+ return dispatch(command, args)
51
+ end
29
52
  raise ArgumentError, "Unexpected arguments: #{args.join(' ')}" unless args.empty?
30
53
  dispatch(command)
31
54
  end
@@ -51,20 +74,50 @@ module Hamster
51
74
  raise "Required executable #{executable.inspect} was not found; #{instruction}"
52
75
  end
53
76
 
54
- def self.dispatch(command)
77
+ def self.dispatch(command, args = [])
55
78
  app_root = root
56
79
  metadata = JSON.parse(File.read(File.join(app_root, "config/hamster.json")))
57
- binary = ENV.fetch("HAMSTER_SERVER_BINARY", File.join(app_root, "bin", "#{metadata.fetch('name')}-server"))
80
+ worker_command = %w[build:worker jobs:work].include?(command)
81
+ binary = ENV.fetch(worker_command ? "HAMSTER_WORKER_BINARY" : "HAMSTER_SERVER_BINARY", File.join(app_root, "bin", "#{metadata.fetch('name')}-#{worker_command ? 'worker' : 'server'}"))
58
82
  case command
83
+ when "jobs:status"
84
+ raise ArgumentError, "Usage: jobs:status [--json]" unless args.empty? || args == ["--json"]
85
+ require File.join(app_root, "config/commands.rb")
86
+ require_relative "jobs/postgres_queue"
87
+ database = ApplicationCommands.database
88
+ begin
89
+ queue = Jobs::PostgresQueue.new(database: database)
90
+ queue.verify!
91
+ report = queue.status
92
+ args == ["--json"] ? puts(JSON.generate(report)) : report["counts"].each { |state, count| puts "#{state}: #{count}" }
93
+ ensure
94
+ database.shutdown
95
+ end
96
+ when "jobs:work"
97
+ raise ArgumentError, "Usage: jobs:work [--once]" unless args.empty? || args == ["--once"]
98
+ raise "Worker binary missing; run bin/hamster build:worker" unless File.executable?(binary)
99
+ Dir.chdir(app_root) { exec(binary, *args) }
59
100
  when "console", "c", "db:validate"
60
101
  adapter = File.join(app_root, "config/commands.rb")
61
102
  raise "Missing config/commands.rb; add the command adapter from the current app template" unless File.file?(adapter)
62
103
  require adapter
63
104
  if command == "db:validate"
64
105
  require_relative "schema_validation"
65
- issues = SchemaValidation.run(ApplicationCommands.database)
66
- raise issues.join("\n") unless issues.empty?
67
- puts "Database declarations validated (#{Table.registry.length} tables); no migrations were run."
106
+ raise ArgumentError, "Usage: db:validate [--json | --detailed]" unless args.empty? || args == ["--json"] || args == ["--detailed"]
107
+ report = SchemaValidation.run(ApplicationCommands.database, detailed: true)
108
+ if args == ["--json"]
109
+ puts JSON.generate(report)
110
+ elsif args == ["--detailed"]
111
+ report["tables"].each do |table|
112
+ puts "#{table['schema']}.#{table['table']}: enabled=#{table['enabled']} exists=#{table['exists']}"
113
+ table["columns"].each { |column| puts " #{column['name']}: enabled=#{column['enabled']} exists=#{column['exists']} checked=#{column['checked']}" }
114
+ end
115
+ report["errors"].each { |error| warn error }
116
+ else
117
+ raise report["errors"].join("\n") unless report["valid"]
118
+ puts "Database declarations validated (#{Table.registry.length} tables); no migrations were run."
119
+ end
120
+ return report["valid"] ? 0 : 1
68
121
  else
69
122
  require_relative "console"
70
123
  Console.run(ApplicationCommands.build)
@@ -72,10 +125,19 @@ module Hamster
72
125
  when "setup"
73
126
  require_tool!("bundle", "install Bundler with gem install bundler")
74
127
  require_tool!("spin", "install the supported Spinel toolchain (including spin); see the Hamster README") if File.file?(File.join(app_root, "spin.toml"))
75
- Dir.chdir(app_root) { raise "Dependency installation failed" unless system("bundle", "install") }
128
+ Dir.chdir(app_root) do
129
+ ready = system("bundle", "check", out: File::NULL, err: File::NULL) || system("bundle", "install")
130
+ raise "Dependency installation failed" unless ready
131
+ end
76
132
  Dir.chdir(app_root) { raise "Spin dependency vendoring failed" unless system("spin", "vendor") } if File.file?(File.join(app_root, "spin.toml"))
77
133
  Build::PostgresCompatibility.apply(app_root) if File.file?(File.join(app_root, "spin.toml"))
78
- when "db:create", "db:migrate"
134
+ when "db:create", "db:migrate", "db:rollback", "db:migrate:status", "db:migrate:history", "db:structure:dump"
135
+ require_relative "database/migrator"
136
+ if command == "db:rollback"
137
+ raise ArgumentError, "Usage: db:rollback [STEP=n]" unless args.empty? || (args.length == 1 && args.first.match?(/\ASTEP=[1-9][0-9]*\z/))
138
+ elsif command == "db:migrate:history"
139
+ raise ArgumentError, "Usage: db:migrate:history --json" unless args == ["--json"]
140
+ end
79
141
  require_tool!("spin", "install the supported Spinel toolchain and run bin/hamster setup")
80
142
  output, status = Open3.capture2e("spin", "list", "--json", chdir: app_root)
81
143
  raise "Cannot resolve PostgreSQL dependency: #{output}" unless status.success?
@@ -92,8 +154,24 @@ module Hamster
92
154
  else
93
155
  database = Hamster::Database.new(configuration, migrations_path: File.join(app_root, "db/migrations"))
94
156
  begin
95
- database.migrate!
96
- puts "Database migrated: #{configuration.database}"
157
+ case command
158
+ when "db:migrate"
159
+ database.migrate!
160
+ puts "Database migrated: #{configuration.database}"
161
+ when "db:rollback"
162
+ database.rollback!(args.empty? ? 1 : args.first.split("=").last.to_i)
163
+ puts "Database rolled back: #{configuration.database}"
164
+ when "db:migrate:status"
165
+ database.migration_status.each { |row| puts [row["version"], row["status"], row["file"]].join("\t") }
166
+ when "db:migrate:history"
167
+ puts JSON.generate(database.migration_history)
168
+ when "db:structure:dump"
169
+ require_tool!("pg_dump", "install PostgreSQL client tools")
170
+ output, error, status = Open3.capture3({"PGPASSWORD" => configuration.password.to_s}, "pg_dump", "--schema-only", "--no-owner", "--no-privileges", "-h", configuration.host, "-p", configuration.port.to_s, "-U", configuration.username, configuration.database)
171
+ raise "Schema dump failed: #{error}" unless status.success?
172
+ FileUtils.mkdir_p(File.join(app_root, "db"))
173
+ File.write(File.join(app_root, "db/structure.sql"), output)
174
+ end
97
175
  ensure
98
176
  database.shutdown
99
177
  end
@@ -104,7 +182,7 @@ module Hamster
104
182
  issues = Build::Manifest.check(app_root)
105
183
  raise issues.join("\n") unless issues.empty?
106
184
  puts "Manifest check passed"
107
- when "build"
185
+ when "build", "build:worker"
108
186
  compiler = ENV.fetch("SPINEL", "spinel")
109
187
  require_tool!(compiler, "install the supported Spinel toolchain or set SPINEL to its compiler path; see the Hamster README")
110
188
  require_tool!("spin", "install the supported Spinel toolchain (including spin)") if File.file?(File.join(app_root, "spin.toml"))
@@ -122,7 +200,7 @@ module Hamster
122
200
  raise "Spin dependency resolution failed: #{diagnostic}" unless status.success?
123
201
  flags.concat(Shellwords.split(output))
124
202
  end
125
- raise "Spinel compilation failed" unless system(compiler, "bin/server", *flags, "-o", temporary)
203
+ raise "Spinel compilation failed" unless system(compiler, worker_command ? "bin/worker" : "bin/server", *flags, "-o", temporary)
126
204
  end
127
205
  File.rename(temporary, binary)
128
206
  ensure
@@ -169,6 +247,8 @@ module Hamster
169
247
  end
170
248
  end
171
249
  Build::Manifest.generate(staging)
250
+ require_relative "agent_guidance"
251
+ AgentGuidance.install(staging)
172
252
  File.chmod(0755, File.join(staging, "bin/hamster"))
173
253
  raise "Destination appeared during generation" if File.exist?(destination)
174
254
  File.rename(staging, destination)
@@ -20,11 +20,11 @@ module Hamster
20
20
  end
21
21
 
22
22
  def create_fields
23
- columns.select { |_name, definition| [:create, :both].include?(definition[:write]) }.keys.map(&:to_s)
23
+ columns.select { |_name, definition| definition[:enabled] && [:create, :both].include?(definition[:write]) }.keys.map(&:to_s)
24
24
  end
25
25
 
26
26
  def update_fields
27
- columns.select { |_name, definition| [:update, :both].include?(definition[:write]) }.keys.map(&:to_s)
27
+ columns.select { |_name, definition| definition[:enabled] && [:update, :both].include?(definition[:write]) }.keys.map(&:to_s)
28
28
  end
29
29
 
30
30
  def create(**attributes)
@@ -33,13 +33,14 @@ module Hamster
33
33
 
34
34
  # Shared persistence path; the caller owns the record boundary.
35
35
  def persist_create(**attributes)
36
+ assert_column_enabled!(:id)
36
37
  check_fields!(attributes, create_fields)
37
38
  record = new(**attributes)
38
39
  errors = validate_create(attributes)
39
40
  return Result.new(record: record, code: :invalid, errors: errors) unless errors.empty?
40
41
 
41
42
  now = Time.now.utc.iso8601
42
- timestamps = %w[created_at updated_at].select { |name| self.columns.key?(name.to_sym) }
43
+ timestamps = %w[created_at updated_at].select { |name| self.columns[name.to_sym] && self.columns[name.to_sym][:enabled] }
43
44
  columns = create_fields + timestamps
44
45
  values = create_fields.map { |name| attributes[name.to_sym] } + timestamps.map { now }
45
46
  placeholders = (1..columns.length).map { |number| "$#{number}" }.join(", ")
@@ -49,8 +50,8 @@ module Hamster
49
50
  return Result.new(record: record, code: :database_error, errors: ["Could not save record."]) unless row
50
51
 
51
52
  record.id = row["id"]
52
- record.write_attribute(:created_at, row["created_at"]) if self.columns.key?(:created_at)
53
- record.write_attribute(:updated_at, row["updated_at"]) if self.columns.key?(:updated_at)
53
+ record.write_attribute(:created_at, row["created_at"]) if timestamps.include?("created_at")
54
+ record.write_attribute(:updated_at, row["updated_at"]) if timestamps.include?("updated_at")
54
55
  Result.new(record: record)
55
56
  rescue Hamster::Database::Error => error
56
57
  database_failure(record, error)
@@ -66,6 +67,8 @@ module Hamster
66
67
  end
67
68
 
68
69
  def check_fields!(attributes, allowed)
70
+ assert_enabled!
71
+ attributes.each_key { |name| assert_column_enabled!(name) }
69
72
  unknown = attributes.keys.map(&:to_s) - allowed
70
73
  raise ArgumentError, "Undeclared record fields: #{unknown.join(', ')}" unless unknown.empty?
71
74
  end
@@ -81,6 +84,7 @@ module Hamster
81
84
 
82
85
  def update(**changes)
83
86
  Instrumentation.record(self.class.name, "update") do
87
+ self.class.assert_column_enabled!(:id)
84
88
  self.class.check_fields!(changes, self.class.update_fields)
85
89
  next missing_result if id.nil? || destroyed?
86
90
  next Result.new(record: self, code: :invalid, errors: ["No changes supplied."]) if changes.empty?
@@ -91,7 +95,7 @@ module Hamster
91
95
  now = Time.now.utc.iso8601
92
96
  columns = self.class.update_fields.select { |name| changes.key?(name.to_sym) }
93
97
  values = columns.map { |name| changes[name.to_sym] }
94
- timestamps = self.class.columns.key?(:updated_at)
98
+ timestamps = self.class.columns[:updated_at] && self.class.columns[:updated_at][:enabled]
95
99
  columns << "updated_at" if timestamps
96
100
  values << now if timestamps
97
101
  assignments = columns.each_with_index.map { |name, index| "#{name} = $#{index + 1}" }.join(", ")
@@ -114,6 +118,7 @@ module Hamster
114
118
 
115
119
  def destroy
116
120
  Instrumentation.record(self.class.name, "destroy") do
121
+ self.class.assert_column_enabled!(:id)
117
122
  next missing_result if id.nil? || destroyed?
118
123
 
119
124
  sql = "DELETE FROM #{self.class.write_table_name} WHERE id = $1 RETURNING id"
@@ -5,6 +5,8 @@ module Hamster
5
5
  class Error < StandardError; end
6
6
  class ValidationError < Error; end
7
7
  class DecodeError < Error; end
8
+ class DisabledTableError < ValidationError; end
9
+ class DisabledColumnError < ValidationError; end
8
10
 
9
11
  TYPES = { integer: 23, bigint: 20, text: 25, boolean: 16, timestamptz: 1184 }.freeze
10
12
 
@@ -4,36 +4,48 @@ module Hamster
4
4
  module Read
5
5
  class Schema
6
6
  def self.validate(connection, tables = Table.registry)
7
+ report(connection, tables)["errors"]
8
+ end
9
+
10
+ # A LEFT JOIN preserves physical existence even for zero-column relations.
11
+ # Disabled declarations are informational; they never trigger migrations.
12
+ def self.report(connection, tables = Table.registry)
7
13
  errors = []
8
- tables.each do |table|
14
+ declarations = tables.map do |table|
9
15
  catalog = connection.execute(<<~SQL, [table.schema_name, table.table_name]).hashes
10
16
  SELECT a.attname AS name, a.atttypid::text AS type_id,
11
17
  a.attnotnull::text AS not_null
12
- FROM pg_catalog.pg_attribute a
13
- JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
18
+ FROM pg_catalog.pg_class c
14
19
  JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
20
+ LEFT JOIN pg_catalog.pg_attribute a ON c.oid = a.attrelid
21
+ AND a.attnum > 0 AND NOT a.attisdropped
15
22
  WHERE n.nspname = $1 AND c.relname = $2
16
23
  AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
17
- AND a.attnum > 0 AND NOT a.attisdropped
18
24
  SQL
25
+ exists = !catalog.empty?
19
26
  prefix = "#{table.schema_name}.#{table.table_name}"
20
- errors << "#{prefix}: table is missing" if catalog.empty?
21
- table.columns.each do |name, definition|
22
- next unless definition[:enabled]
27
+ errors << "#{prefix}: table is missing" if table.enabled? && !exists
28
+ columns = table.columns.map do |name, definition|
23
29
  actual = catalog.find { |row| row["name"] == name.to_s }
24
- if actual.nil?
25
- errors << "#{prefix}.#{name}: column is missing"
26
- else
27
- unless actual["type_id"] == TYPES[definition[:type]].to_s
28
- errors << "#{prefix}.#{name}: incompatible type (expected #{definition[:type]})"
29
- end
30
- if !definition[:nullable] && actual["not_null"] != "true"
31
- errors << "#{prefix}.#{name}: database permits NULL"
30
+ checked = table.enabled? && definition[:enabled] && exists
31
+ if checked
32
+ if actual.nil?
33
+ errors << "#{prefix}.#{name}: column is missing"
34
+ else
35
+ unless actual["type_id"] == TYPES[definition[:type]].to_s
36
+ errors << "#{prefix}.#{name}: incompatible type (expected #{definition[:type]})"
37
+ end
38
+ if !definition[:nullable] && actual["not_null"] != "true"
39
+ errors << "#{prefix}.#{name}: database permits NULL"
40
+ end
32
41
  end
33
42
  end
43
+ {"name" => name.to_s, "enabled" => definition[:enabled], "exists" => !actual.nil?, "checked" => checked}
34
44
  end
45
+ {"schema" => table.schema_name, "table" => table.table_name, "enabled" => table.enabled?,
46
+ "exists" => exists, "columns" => columns}
35
47
  end
36
- errors
48
+ {"format_version" => 1, "valid" => errors.empty?, "tables" => declarations, "errors" => errors}
37
49
  end
38
50
  end
39
51
  end
@@ -22,8 +22,10 @@ module Hamster
22
22
  end
23
23
 
24
24
  def validate
25
+ source.row_class.assert_enabled!
25
26
  state[:joins].each do |join|
26
27
  other = join.args[0]
28
+ other.row_class.assert_enabled!
27
29
  fail!("duplicate source alias #{other.label}", "JOIN") if @sources.any? { |s| s.label == other.label }
28
30
  @sources << other
29
31
  @left_sources << other.key if join.options[:kind] == :left
@@ -159,6 +161,7 @@ module Hamster
159
161
  when :column
160
162
  table, name = node.args
161
163
  fail!("source #{table.label} is not visible", clause) unless visible.any? { |s| s.key == table.key }
164
+ table.row_class.assert_column_enabled!(name)
162
165
  definition = table.columns[name]
163
166
  fail!("#{table.schema}.#{table.name}.#{name} is undeclared", clause) unless definition
164
167
  fail!("#{table.schema}.#{table.name}.#{name} is disabled", clause) unless definition[:enabled]
@@ -67,12 +67,26 @@ module Hamster
67
67
 
68
68
  def [](name)
69
69
  key = name.to_sym
70
+ assert_record_column_enabled!(key)
70
71
  raise MissingAttributeError, "Unloaded attribute #{key}" if @partial && !@attributes.key?(key)
71
- raise MissingAttributeError, "Undeclared attribute #{key}" unless self.class.columns.key?(key)
72
72
  @attributes[key]
73
73
  end
74
74
 
75
+ def assert_record_column_enabled!(name)
76
+ if RUBY_ENGINE == "ruby"
77
+ self.class.assert_column_enabled!(name)
78
+ raise MissingAttributeError, "Undeclared attribute #{name}" unless self.class.columns.key?(name.to_sym)
79
+ else
80
+ assert_compiled_record_column_enabled!(name)
81
+ end
82
+ end
83
+
84
+ def assert_compiled_record_column_enabled!(name)
85
+ raise MissingAttributeError, "Run hamster manifest to generate record schema guards"
86
+ end
87
+
75
88
  def write_attribute(name, value)
89
+ assert_record_column_enabled!(name)
76
90
  @attributes[name.to_sym] = value
77
91
  end
78
92
  end
@@ -9,25 +9,44 @@ module Hamster
9
9
  REGISTRY = []
10
10
 
11
11
  def self.inherited(child)
12
- child.set_metadata(table_name, schema_name, columns) unless self == Table
12
+ child.set_metadata(table_name, schema_name, columns, enabled?) unless self == Table
13
13
  REGISTRY << child
14
14
  end
15
15
 
16
- def self.set_metadata(name, schema, definitions)
16
+ def self.set_metadata(name, schema, definitions, enabled = true)
17
17
  @table_name = name
18
18
  @schema_name = schema
19
19
  @columns = definitions.dup
20
+ @enabled = enabled
20
21
  end
21
22
 
22
23
  def self.registry
23
24
  REGISTRY.dup.freeze
24
25
  end
25
26
 
26
- def self.table(name, schema: "public")
27
+ def self.table(name, schema: "public", enabled: true)
28
+ raise Read::ValidationError, "Table enabled must be boolean" unless [true, false].include?(enabled)
29
+ @enabled = enabled
27
30
  @table_name = Read.identifier(name)
28
31
  @schema_name = Read.identifier(schema)
29
32
  end
30
33
 
34
+ def self.enabled?
35
+ @enabled != false
36
+ end
37
+
38
+ def self.assert_enabled!
39
+ raise Read::DisabledTableError, "#{schema_name}.#{table_name}: table is disabled" unless enabled?
40
+ end
41
+
42
+ def self.assert_column_enabled!(name)
43
+ assert_enabled!
44
+ definition = columns[name.to_sym]
45
+ if definition && !definition[:enabled]
46
+ raise Read::DisabledColumnError, "#{schema_name}.#{table_name}.#{name}: column is disabled"
47
+ end
48
+ end
49
+
31
50
  def self.table_name
32
51
  @table_name || name.split("::").last.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').gsub(/([a-z0-9])([A-Z])/, '\1_\2').downcase + "s"
33
52
  end