hamster-web 0.1.0.pre.2 → 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 (83) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +42 -0
  3. data/README.md +576 -5
  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 +105 -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 +19 -0
  57. data/templates/app/AGENTS.md +20 -7
  58. data/templates/app/Dockerfile +77 -0
  59. data/templates/app/Gemfile +5 -1
  60. data/templates/app/README.md +365 -2
  61. data/templates/app/app/application.rb +15 -0
  62. data/templates/app/app/assets/application.css +2 -0
  63. data/templates/app/app/assets/application.js +2 -0
  64. data/templates/app/app/assets/controllers/hello_controller.js +5 -0
  65. data/templates/app/app/assets/vendor/VERSIONS.md +12 -0
  66. data/templates/app/app/assets/vendor/stimulus.LICENSE.txt +9 -0
  67. data/templates/app/app/assets/vendor/stimulus.js +2563 -0
  68. data/templates/app/app/assets/vendor/turbo.LICENSE.txt +20 -0
  69. data/templates/app/app/assets/vendor/turbo.js +7178 -0
  70. data/templates/app/app/routes/mappings.rb +1 -0
  71. data/templates/app/app/routes/up/index/action.rb +14 -0
  72. data/templates/app/app/views/layouts/application.html.erb +2 -1
  73. data/templates/app/bin/hamster +8 -0
  74. data/templates/app/bin/server +13 -1
  75. data/templates/app/bin/worker +24 -0
  76. data/templates/app/config/application.rb +1 -1
  77. data/templates/app/config/deploy.worker.yml.example +32 -0
  78. data/templates/app/public/.keep +0 -0
  79. data/templates/app/test/home_test.rb +8 -0
  80. data/templates/app/test/native_http.rb +11 -0
  81. data/templates/app/test/native_server.rb +10 -0
  82. data/templates/app/test/test_helper.rb +8 -0
  83. metadata +58 -4
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+ require "ripper"
3
+ require_relative "callbacks"
4
+ module Hamster
5
+ module Build
6
+ module Jobs
7
+ module_function
8
+ def literal(node)
9
+ return node[1][1][1] if node && node[0] == :string_literal && node[1].length == 2 && node[1][1][0] == :@tstring_content
10
+ return node[1].to_i if node && node[0] == :@int
11
+ if node && node[0] == :array
12
+ return (node[1] || []).map { |n| literal(n) }
13
+ end
14
+ raise ArgumentError, "Job names and versions must be literal"
15
+ end
16
+ def declarations(node, owner = "", result = [])
17
+ return result unless node.is_a?(Array)
18
+ if [:class, :module].include?(node[0])
19
+ local = Callbacks.constant(node[1])
20
+ raise ArgumentError, "dynamic job declaration" unless local
21
+ owner = local.include?("::") ? local : [owner, local].reject(&:empty?).join("::")
22
+ declarations(node[node[0] == :class ? 3 : 2], owner, result)
23
+ elsif [:def, :defs].include?(node[0])
24
+ return result
25
+ elsif node[0] == :method_add_arg && node.dig(1, 0) == :fcall && node.dig(1, 1, 1) == "job"
26
+ arguments = node[2][0] == :arg_paren ? node[2][1] : node[2]
27
+ declarations([:command, node[1][1], arguments], owner, result)
28
+ elsif node[0] == :command && node.dig(1, 1) == "job"
29
+ args = node[2][1]
30
+ name = literal(args.first)
31
+ options = args.find { |arg| arg[0] == :bare_assoc_hash }
32
+ values = options ? options[1].to_h { |pair| [pair[1][1].delete_suffix(":"), literal(pair[2])] } : {}
33
+ version = values.fetch("version", 1)
34
+ accepts = (values.fetch("accepts", []) + [version]).uniq
35
+ raise ArgumentError, "Invalid job name/version" unless name.is_a?(String) && name.match?(/\A[a-z][a-z0-9_.-]*\z/) && accepts.all? { |v| v.is_a?(Integer) && v > 0 }
36
+ result << [owner, name, accepts]
37
+ else
38
+ node.each { |child| declarations(child, owner, result) if child.is_a?(Array) }
39
+ end
40
+ result
41
+ end
42
+ def compile(sources)
43
+ definitions = {}
44
+ sources.each { |source| Callbacks.scan(Ripper.sexp(source), "", definitions) }
45
+ jobs = sources.flat_map { |source| declarations(Ripper.sexp(source)) }.sort_by { |job| job[1] }
46
+ raise ArgumentError, "Duplicate job name" unless jobs.map { |job| job[1] }.uniq.length == jobs.length
47
+ jobs.each do |owner, _, _|
48
+ current, seen = owner, []
49
+ until current == "Hamster::Job"
50
+ raise ArgumentError, "#{owner}: job declaration must inherit Hamster::Job" if seen.include?(current) || !definitions[current]
51
+ seen << current
52
+ parent = definitions[current][:parent]
53
+ scopes = current.split("::")[0...-1]
54
+ current = scopes.length.downto(0).map { |n| (scopes.take(n) + [parent]).compact.join("::") }.find { |name| definitions.key?(name) } || parent
55
+ end
56
+ end
57
+ lines = ["# Generated by hamster manifest.", "module Hamster", " module CompiledJobs", " def self.accepts?(name, version)"]
58
+ if jobs.empty?
59
+ lines << " false"
60
+ else
61
+ lines << " case name"
62
+ jobs.each { |_, name, versions| lines << " when #{name.inspect} then #{versions.inspect}.include?(version)" }
63
+ lines += [" else false", " end"]
64
+ end
65
+ lines += [" end", " def self.execute_registered_job(name, version, arguments)"]
66
+ unless jobs.empty?
67
+ lines << " case name"
68
+ jobs.each do |owner, name, versions|
69
+ lines += [" when #{name.inspect}", " raise Hamster::Jobs::UnknownJob, 'Unsupported job version' unless #{versions.inspect}.include?(version)", " return #{owner}.new.perform(arguments, version: version)"]
70
+ end
71
+ lines << " end"
72
+ end
73
+ lines += [" raise Hamster::Jobs::UnknownJob, 'Unknown job'", " end", " end", "end"]
74
+ lines.join("\n") + "\n"
75
+ end
76
+ end
77
+ end
78
+ end
@@ -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
@@ -44,29 +67,78 @@ module Hamster
44
67
  end
45
68
  end
46
69
 
47
- def self.dispatch(command)
70
+ def self.require_tool!(executable, instruction)
71
+ paths = executable.include?(File::SEPARATOR) ? [executable] : ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).map { |directory| File.join(directory, executable) }
72
+ return if paths.any? { |path| File.file?(path) && File.executable?(path) }
73
+
74
+ raise "Required executable #{executable.inspect} was not found; #{instruction}"
75
+ end
76
+
77
+ def self.dispatch(command, args = [])
48
78
  app_root = root
49
79
  metadata = JSON.parse(File.read(File.join(app_root, "config/hamster.json")))
50
- 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'}"))
51
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) }
52
100
  when "console", "c", "db:validate"
53
101
  adapter = File.join(app_root, "config/commands.rb")
54
102
  raise "Missing config/commands.rb; add the command adapter from the current app template" unless File.file?(adapter)
55
103
  require adapter
56
104
  if command == "db:validate"
57
105
  require_relative "schema_validation"
58
- issues = SchemaValidation.run(ApplicationCommands.database)
59
- raise issues.join("\n") unless issues.empty?
60
- 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
61
121
  else
62
122
  require_relative "console"
63
123
  Console.run(ApplicationCommands.build)
64
124
  end
65
125
  when "setup"
66
- Dir.chdir(app_root) { raise "Dependency installation failed" unless system("bundle", "install") }
126
+ require_tool!("bundle", "install Bundler with gem install bundler")
127
+ require_tool!("spin", "install the supported Spinel toolchain (including spin); see the Hamster README") if File.file?(File.join(app_root, "spin.toml"))
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
67
132
  Dir.chdir(app_root) { raise "Spin dependency vendoring failed" unless system("spin", "vendor") } if File.file?(File.join(app_root, "spin.toml"))
68
133
  Build::PostgresCompatibility.apply(app_root) if File.file?(File.join(app_root, "spin.toml"))
69
- 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
141
+ require_tool!("spin", "install the supported Spinel toolchain and run bin/hamster setup")
70
142
  output, status = Open3.capture2e("spin", "list", "--json", chdir: app_root)
71
143
  raise "Cannot resolve PostgreSQL dependency: #{output}" unless status.success?
72
144
  pg = JSON.parse(output).find { |package| package["name"] == "pg" }
@@ -82,8 +154,24 @@ module Hamster
82
154
  else
83
155
  database = Hamster::Database.new(configuration, migrations_path: File.join(app_root, "db/migrations"))
84
156
  begin
85
- database.migrate!
86
- 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
87
175
  ensure
88
176
  database.shutdown
89
177
  end
@@ -94,7 +182,10 @@ module Hamster
94
182
  issues = Build::Manifest.check(app_root)
95
183
  raise issues.join("\n") unless issues.empty?
96
184
  puts "Manifest check passed"
97
- when "build"
185
+ when "build", "build:worker"
186
+ compiler = ENV.fetch("SPINEL", "spinel")
187
+ require_tool!(compiler, "install the supported Spinel toolchain or set SPINEL to its compiler path; see the Hamster README")
188
+ require_tool!("spin", "install the supported Spinel toolchain (including spin)") if File.file?(File.join(app_root, "spin.toml"))
98
189
  Build::PostgresCompatibility.apply(app_root) if File.file?(File.join(app_root, "spin.toml"))
99
190
  Build::Manifest.generate(app_root)
100
191
  issues = Build::Manifest.check(app_root)
@@ -109,7 +200,7 @@ module Hamster
109
200
  raise "Spin dependency resolution failed: #{diagnostic}" unless status.success?
110
201
  flags.concat(Shellwords.split(output))
111
202
  end
112
- raise "Spinel compilation failed" unless system(ENV.fetch("SPINEL", "spinel"), "bin/server", *flags, "-o", temporary)
203
+ raise "Spinel compilation failed" unless system(compiler, worker_command ? "bin/worker" : "bin/server", *flags, "-o", temporary)
113
204
  end
114
205
  File.rename(temporary, binary)
115
206
  ensure
@@ -156,6 +247,8 @@ module Hamster
156
247
  end
157
248
  end
158
249
  Build::Manifest.generate(staging)
250
+ require_relative "agent_guidance"
251
+ AgentGuidance.install(staging)
159
252
  File.chmod(0755, File.join(staging, "bin/hamster"))
160
253
  raise "Destination appeared during generation" if File.exist?(destination)
161
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]