samagotchi 0.165.0 → 0.167.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +99 -1
  3. data/docs/architecture.md +1 -0
  4. data/docs/cli.md +16 -7
  5. data/docs/configuration.md +4 -1
  6. data/docs/guardrails.md +8 -3
  7. data/docs/hooks.md +4 -6
  8. data/docs/internals/bridge.md +6 -0
  9. data/docs/internals/bundles.md +2 -4
  10. data/docs/internals/engine.md +4 -5
  11. data/docs/internals/objectives.md +141 -9
  12. data/docs/internals/remote-sessions.md +6 -7
  13. data/docs/internals/web-frontend.md +62 -24
  14. data/docs/memory.md +1 -2
  15. data/docs/releasing.md +12 -3
  16. data/docs/sessions.md +24 -6
  17. data/docs/testing.md +14 -4
  18. data/lib/samagotchi/bridge.rb +1 -1
  19. data/lib/samagotchi/bundle_command/installed_check.rb +2 -14
  20. data/lib/samagotchi/bundle_command.rb +19 -11
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/cli/command.rb +10 -0
  23. data/lib/samagotchi/compat.rb +4 -14
  24. data/lib/samagotchi/config.rb +3 -0
  25. data/lib/samagotchi/context_command.rb +2 -1
  26. data/lib/samagotchi/engine/objectives.rb +20 -1
  27. data/lib/samagotchi/engine/side_requests.rb +3 -2
  28. data/lib/samagotchi/engine/turn_end.rb +4 -1
  29. data/lib/samagotchi/engine.rb +3 -0
  30. data/lib/samagotchi/extension_load.rb +2 -26
  31. data/lib/samagotchi/guardrails/approvals.rb +59 -9
  32. data/lib/samagotchi/jsonl_store.rb +61 -0
  33. data/lib/samagotchi/memory_bundle/status.rb +3 -15
  34. data/lib/samagotchi/memory_bundle/system_bundle.rb +16 -10
  35. data/lib/samagotchi/memory_command.rb +4 -2
  36. data/lib/samagotchi/objectives.rb +43 -14
  37. data/lib/samagotchi/objectives_backing.rb +124 -0
  38. data/lib/samagotchi/objectives_check.rb +19 -126
  39. data/lib/samagotchi/objectives_command.rb +14 -7
  40. data/lib/samagotchi/objectives_record.rb +104 -0
  41. data/lib/samagotchi/objectives_track.rb +353 -0
  42. data/lib/samagotchi/plugin/sessions.rb +4 -1
  43. data/lib/samagotchi/push_command.rb +2 -1
  44. data/lib/samagotchi/remote_command.rb +2 -1
  45. data/lib/samagotchi/reply_wait/poll.rb +10 -21
  46. data/lib/samagotchi/reply_wait.rb +4 -47
  47. data/lib/samagotchi/run_options.rb +1 -1
  48. data/lib/samagotchi/schedule_command.rb +6 -0
  49. data/lib/samagotchi/schedules.rb +1 -1
  50. data/lib/samagotchi/session_access/remote.rb +7 -24
  51. data/lib/samagotchi/session_commands.rb +1 -1
  52. data/lib/samagotchi/session_inbox.rb +1 -1
  53. data/lib/samagotchi/sessions_command.rb +12 -6
  54. data/lib/samagotchi/share_command.rb +2 -1
  55. data/lib/samagotchi/tool_activity.rb +11 -1
  56. data/lib/samagotchi/tool_declarations.rb +5 -1
  57. data/lib/samagotchi/tools/delegate.rb +2 -4
  58. data/lib/samagotchi/tools/objectives_tool.rb +19 -2
  59. data/lib/samagotchi/turn_stages/objectives.rb +46 -3
  60. data/lib/samagotchi/version.rb +1 -1
  61. data/lib/samagotchi/web/participant_access.rb +1 -1
  62. data/lib/samagotchi/web/public/app.js +55 -420
  63. data/lib/samagotchi/web/public/auth_lost.js +3 -1
  64. data/lib/samagotchi/web/public/bar_fold.js +1 -1
  65. data/lib/samagotchi/web/public/chip_popover.js +5 -1
  66. data/lib/samagotchi/web/public/copy.js +2 -1
  67. data/lib/samagotchi/web/public/delivery_line.js +19 -4
  68. data/lib/samagotchi/web/public/index.html +156 -49
  69. data/lib/samagotchi/web/public/info_bar.js +1 -1
  70. data/lib/samagotchi/web/public/info_bar_model.js +8 -1
  71. data/lib/samagotchi/web/public/live_timing.js +3 -0
  72. data/lib/samagotchi/web/public/no_contact_fill.js +29 -0
  73. data/lib/samagotchi/web/public/objectives.css +14 -0
  74. data/lib/samagotchi/web/public/objectives_moves.js +82 -9
  75. data/lib/samagotchi/web/public/objectives_state.js +42 -0
  76. data/lib/samagotchi/web/public/objectives_strip.js +33 -9
  77. data/lib/samagotchi/web/public/objectives_track.js +52 -0
  78. data/lib/samagotchi/web/public/objectives_wiring.js +16 -1
  79. data/lib/samagotchi/web/public/participant.html +1 -1
  80. data/lib/samagotchi/web/public/participants_panel.js +14 -7
  81. data/lib/samagotchi/web/public/question_cards.js +7 -12
  82. data/lib/samagotchi/web/public/resync_reach.js +63 -0
  83. data/lib/samagotchi/web/public/scope.js +3 -3
  84. data/lib/samagotchi/web/public/session_fields.js +1 -0
  85. data/lib/samagotchi/web/public/session_rename.js +6 -2
  86. data/lib/samagotchi/web/public/session_state.js +6 -1
  87. data/lib/samagotchi/web/public/session_sync.js +249 -0
  88. data/lib/samagotchi/web/public/session_view.js +279 -0
  89. data/lib/samagotchi/web/public/stage_frame.js +4 -2
  90. data/lib/samagotchi/web/public/stage_stall.js +134 -0
  91. data/lib/samagotchi/web/public/stage_view.js +75 -6
  92. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  93. data/lib/samagotchi/web/public/tokens.css +2 -2
  94. data/lib/samagotchi/web/public/turn_block.js +8 -0
  95. data/lib/samagotchi/web/public/turn_html.js +1 -1
  96. data/lib/samagotchi/web/public/widget_picks.js +3 -0
  97. data/lib/samagotchi/web/public/working_set_view.js +1 -1
  98. data/lib/samagotchi/web/session_access_routes.rb +4 -15
  99. data/lib/samagotchi/web/token.rb +2 -2
  100. metadata +12 -1
@@ -106,6 +106,9 @@ module Samagotchi
106
106
  chi bundle build --scope system --out ./my-bundle/ identity.md work.md
107
107
  TEXT
108
108
  TRASH_HELP = "Usage: chi bundle trash [--empty] [--dry-run] [--older-than DAYS]"
109
+ STATUS_HELP = "Usage: chi bundle status [<bundle>]"
110
+ DIFF_HELP = "Usage: chi bundle diff <bundle> [file]"
111
+ LIST_HELP = "Usage: chi bundle list"
109
112
 
110
113
  # The subcommands' flags: --help only; a word not starting with -- is
111
114
  # a positional (install's source, -h included). --scope takes whatever
@@ -134,6 +137,8 @@ module Samagotchi
134
137
  f.switch "--dry-run"
135
138
  f.value "--older-than"
136
139
  end
140
+ # status, diff and list take no flag: --help, else an unknown one.
141
+ NO_FLAGS = CLI::Flags.new(help: %w[--help], flag_pattern: /\A--/)
137
142
 
138
143
  # @param argv [Array<String>] the arguments after "bundle"
139
144
  def initialize(argv, stdin: $stdin, stdout: $stdout, stderr: $stderr)
@@ -157,7 +162,7 @@ module Samagotchi
157
162
  when "uninstall" then uninstall(@argv[1..])
158
163
  when "status" then status(@argv[1..])
159
164
  when "diff" then diff(@argv[1..])
160
- when "list" then list
165
+ when "list" then list(@argv[1..])
161
166
  when "build" then build(@argv[1..])
162
167
  when "trash" then trash(@argv[1..])
163
168
  when "new" then new_bundle(@argv[1..])
@@ -536,7 +541,10 @@ module Samagotchi
536
541
  end
537
542
 
538
543
  def status(rest)
539
- name = rest.find { |a| !a.start_with?("--") }
544
+ parsed = parse_flags(NO_FLAGS, rest, "status", help: STATUS_HELP)
545
+ return parsed if parsed.is_a?(Integer)
546
+
547
+ name = parsed.args.first
540
548
  require "json"
541
549
  if name
542
550
  st = Samagotchi::MemoryBundle::Status.bundle_status(name)
@@ -573,10 +581,6 @@ module Samagotchi
573
581
  commit = st.provenance.source_commit
574
582
  @stdout.puts " trust_level: #{trust}"
575
583
  @stdout.puts " source_commit: #{commit}" if commit
576
- unless st.retired_hooks.empty?
577
- @stdout.puts " Hooks (#{st.retired_hooks.size}): not loaded: #{Samagotchi::MemoryBundle::Manifest::HooksRetired::WORDS}"
578
- st.retired_hooks.each { |file, state| @stdout.puts " #{file} [#{state}]" }
579
- end
580
584
  print_assets("Rules", st.rules, " (edited after install: not loaded; reinstall the bundle)")
581
585
  print_assets("Scripts", st.scripts, " (edited after install: the next install replaces it, a copy kept in the trash)")
582
586
  if (plugin = st.plugin)
@@ -598,17 +602,15 @@ module Samagotchi
598
602
 
599
603
  st = Samagotchi::MemoryBundle::Status.bundle_status(bname)
600
604
  mods = st.files.values.count { |v| v[:behind] || v[:missing] || v[:unreadable] }
601
- hook_info = st.retired_hooks.empty? ? "" : " hooks=#{st.retired_hooks.size}"
602
605
  plugin = st.plugin
603
606
  mods += 1 if plugin && (plugin[:state] != "ok" || plugin[:requires_failure])
604
- mods += 1 unless st.retired_hooks.empty?
605
607
  # A rule that is missing or edited doesn't load; a script runs edited.
606
608
  mods += st.rules.values.count { |state| state != "ok" } + st.scripts.values.count("missing")
607
609
  mods += 1 if st.scope_error
608
610
  plugin_info = plugin ? " plugin=#{plugin[:file]}" : ""
609
611
  includes = st.provenance.includes
610
612
  includes_info = includes ? " includes=#{includes.join(",")}" : ""
611
- @stdout.puts " #{bname} v#{st.provenance.version}#{dev_label(st.provenance)} scope=#{status_scope(st)} files=#{st.files.size}#{hook_info}#{plugin_info}#{includes_info} issues=#{mods}"
613
+ @stdout.puts " #{bname} v#{st.provenance.version}#{dev_label(st.provenance)} scope=#{status_scope(st)} files=#{st.files.size}#{plugin_info}#{includes_info} issues=#{mods}"
612
614
  end
613
615
  end
614
616
  0
@@ -642,7 +644,10 @@ module Samagotchi
642
644
  def status_scope(st) = st.scope_error ? "#{st.scope} (unknown)" : st.scope
643
645
 
644
646
  def diff(rest)
645
- args = rest.reject { |a| a.start_with?("--") }
647
+ parsed = parse_flags(NO_FLAGS, rest, "diff", help: DIFF_HELP)
648
+ return parsed if parsed.is_a?(Integer)
649
+
650
+ args = parsed.args
646
651
  bname = args[0]
647
652
  file_arg = args[1]
648
653
  if bname.nil? || bname.empty?
@@ -750,7 +755,10 @@ module Samagotchi
750
755
  @stdout.puts File.exist?(current) ? File.read(current) : "(missing)"
751
756
  end
752
757
 
753
- def list
758
+ def list(rest)
759
+ parsed = parse_flags(NO_FLAGS, rest, "list", help: LIST_HELP)
760
+ return parsed if parsed.is_a?(Integer)
761
+
754
762
  listing = Samagotchi::MemoryBundle::Listing
755
763
  shipped = listing.shipped
756
764
  installed = listing.installed(shipped: shipped)
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.165.0
3
+ version: 0.167.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -35,6 +35,16 @@ module Samagotchi
35
35
  Exit::USAGE
36
36
  end
37
37
 
38
+ # The one refusal of a --format value the command doesn't print
39
+ # (nil, no --format, is the text). The caller returns what it gives.
40
+ # @param formats [Array<String>] the values the command takes
41
+ # @return [Integer, nil] the usage exit status, or nil for a format it takes
42
+ def format_refusal(format, formats = %w[text json])
43
+ return nil if format.nil? || formats.include?(format)
44
+
45
+ usage_error("unknown format #{format.inspect}: use --format #{formats.join("|")}")
46
+ end
47
+
38
48
  # +argv+ through +flags+ (a Flags), help and usage errors done.
39
49
  # @return [Flags::Result, Integer] the result, or the exit status
40
50
  # after the help (0) or a usage error (2)
@@ -19,20 +19,10 @@ module Samagotchi
19
19
  files: ["lib/samagotchi/bridge/card_store.rb"],
20
20
  what: "CardStore#seed_v1 reads a cards.json from before the turn log; its comment says a retention " \
21
21
  "period after the release that wrote version 2 (0.151.0, 2026-11-05)"),
22
- Shim.new(id: :merge_inference, added_in: "0.157.0", remove_after: "0.165.0",
23
- files: ["lib/samagotchi/reply_wait/poll.rb", "lib/samagotchi/tools/delegate.rb"],
24
- what: "a wait infers a merged steer when the worker wrote no merge record (a 0.156 worker)"),
25
- Shim.new(id: :session_not_found_words, added_in: "0.156.0", remove_after: "0.165.0",
26
- files: ["lib/samagotchi/session_access/remote.rb"],
27
- what: "SESSION_NOT_FOUND also reads chi web 0.155.0's \"Session not found: X\" (its comment: compat N-1)"),
28
- Shim.new(id: :remote_refusal_details, added_in: "0.122.0", remove_after: "0.165.0",
29
- files: ["lib/samagotchi/session_access/remote.rb"],
30
- what: "context_missing? and no_provider? read an older chi web's 404 detail words, before their error codes"),
31
- Shim.new(id: :retired_class_file_hooks, added_in: "0.158.0", remove_after: "0.166.0",
32
- files: ["lib/samagotchi/extension_load.rb", "lib/samagotchi/memory_bundle/status.rb",
33
- "lib/samagotchi/bundle_command/installed_check.rb"],
34
- what: "a 0.157 install record's class-file hooks: announced as not loading, shown and checked until " \
35
- "an upgrade or uninstall clears them (installed state, not protocol)")
22
+ Shim.new(id: :approvals_array_read, added_in: "0.166.0", remove_after: "0.167.0",
23
+ files: ["lib/samagotchi/guardrails/approvals.rb"],
24
+ what: "Approvals#parse reads approvals.json as the list 0.165 and before write, beside the versioned " \
25
+ "store, and #version_list rewrites it versioned on that first read")
36
26
  ].freeze
37
27
 
38
28
  module_function
@@ -262,6 +262,9 @@ module Samagotchi
262
262
 
263
263
  # Check this (ObjectivesCheck): a cheap configured model for its one side request; nil is the session's.
264
264
  Entry.new(key: "objectives.check_model", yaml_path: %w[objectives check_model], type: :string, default: nil, expose: %i[config], lifecycle: :next_matching_turn_display_poll_write),
265
+ # The tracker (ObjectivesTrack): on, it also reads the list by itself after an owner's turn that did work and
266
+ # recorded no move (on objectives.check_model); off, only /objectives track and Where are we? do.
267
+ Entry.new(key: "objectives.tracker", yaml_path: %w[objectives tracker], type: :enum, default: "off", expose: %i[config], enum_values: %w[off on], lifecycle: :next_matching_turn_display_poll_write),
265
268
  # System 1 on the objectives (ObjectivesAudit): audit saves a yes/no per active objective on what comes in and goes
266
269
  # out, acted on by nothing; off (no conversation text goes to a System 1 host for it). Host and model: system_one.*.
267
270
  Entry.new(key: "objectives.system_one", yaml_path: %w[objectives system_one], type: :enum, default: "off", expose: %i[config], enum_values: %w[off audit], lifecycle: :next_matching_turn_display_poll_write),
@@ -249,7 +249,8 @@ module Samagotchi
249
249
 
250
250
  def run_ls(options, args)
251
251
  format = options[:format]
252
- return usage_error("unknown format #{format.inspect}: use --format text|json") unless [nil, "text", "json"].include?(format)
252
+ refused = format_refusal(format)
253
+ return refused if refused
253
254
 
254
255
  targets = targets(options, args) or return CLI::Exit::FAILED
255
256
  rows = targets.flat_map { |target| @access.context_entries(target).map { |entry| row(target, entry) } }
@@ -5,7 +5,7 @@ module Samagotchi
5
5
  # The session's objectives (TurnStages::Objectives, forwarded): the view
6
6
  # announced when it changed, the model's proposals kept as cards until
7
7
  # the turn is over, System 1's audit of them (ObjectivesAudit); and
8
- # Check this's side request. Reads @objectives_stage, @side_judgments,
8
+ # Check this's and the tracker's side requests. Reads @objectives_stage, @side_judgments,
9
9
  # @host_registry, @session.
10
10
  module ObjectivesPart
11
11
  # The session's objectives as the page draws them, when that differs
@@ -36,6 +36,15 @@ module Samagotchi
36
36
  cancel_controller: nil, model: model, source: ObjectivesCheck::SOURCE)
37
37
  end
38
38
 
39
+ # The tracker (ObjectivesTrack)'s one side request, under its own kind so
40
+ # /stats counts it apart. +cancel_controller+: the automatic read's, which
41
+ # the owner's next turn cancels (raises LLM::RequestCancelled then).
42
+ # @return [String] the answer
43
+ def ask_objective_track(request, model:, cancel_controller: nil)
44
+ ask_side_model(request, timeout: ObjectivesTrack::TIMEOUT_SECONDS, max_tokens: ObjectivesTrack::MAX_TOKENS,
45
+ cancel_controller: cancel_controller, model: model, source: ObjectivesTrack::SOURCE)
46
+ end
47
+
39
48
  # A change the model proposes (the objectives tool), kept until the turn
40
49
  # is over (TurnStages::Objectives#propose).
41
50
  # @return [Boolean] false past Objectives::PROPOSALS_PER_TURN
@@ -55,6 +64,16 @@ module Samagotchi
55
64
  Log.warn(:turn, "objectives_proposal_failed", error: e.class.name, msg: e.message)
56
65
  end
57
66
 
67
+ # After a completed turn (#complete_turn, beside the stage's outgoing):
68
+ # with objectives.tracker on, the tracker by itself, when the turn did
69
+ # work and recorded no move (TurnStages::Objectives#track). It only
70
+ # informs: a failure is logged.
71
+ def track_objectives_after(turn)
72
+ @objectives_stage.track(turn, engine: self)
73
+ rescue StandardError => e
74
+ Log.warn(:turn, "objectives_track_start_failed", error: e.class.name, msg: e.message)
75
+ end
76
+
58
77
  # The stage over this Engine's side asks (built in #initialize, once
59
78
  # the host registry is). Each call takes its values: the recorder,
60
79
  # the sessions dir, the running conversation.
@@ -41,8 +41,9 @@ module Samagotchi
41
41
  # command's ask_model between turns).
42
42
  # @return [String, nil]
43
43
  def side_author(kind)
44
- # Check this is only ever the owner's, whichever turn runs as it ends.
45
- return nil if kind.to_s == ObjectivesCheck::SOURCE
44
+ # Check this and the tracker are only ever the owner's, whichever turn
45
+ # runs as they end.
46
+ return nil if [ObjectivesCheck::SOURCE, ObjectivesTrack::SOURCE].include?(kind.to_s)
46
47
 
47
48
  # One read each of the published contexts (TurnState): any thread.
48
49
  running = turn_context
@@ -117,7 +117,10 @@ module Samagotchi
117
117
  # a display version of the answer (AnswerDisplay) and event[:refs]
118
118
  # for refs on it (AnswerRefs).
119
119
  session = turn.session
120
- @objectives_stage.outgoing(turn, result, recorder: system_one_recorder) unless canceled || result.exhausted?
120
+ unless canceled || result.exhausted?
121
+ @objectives_stage.outgoing(turn, result, recorder: system_one_recorder)
122
+ track_objectives_after(turn)
123
+ end
121
124
  display = AnswerDisplay.new(session.messages)
122
125
  refs = AnswerRefs.new(session.messages, cwd: session.working_directory)
123
126
  after_turn = { type: :after_turn, status: canceled ? "canceled" : "completed",
@@ -974,6 +974,9 @@ module Samagotchi
974
974
  # cross-thread state is set here and cleared in #release_turn only.
975
975
  def begin_turn(session, prompt, on_event:, cancel_controller:, origin:, continue:, id: nil, verify: nil, revises: nil,
976
976
  input_waiting: nil)
977
+ # The tracker's automatic read still out: any turn's start frees its
978
+ # request first, before this turn's own probes and waits.
979
+ @objectives_stage.cancel_track
977
980
  origin = TurnOrigin.of(origin)
978
981
  # A participant's Verify fresh child: every turn is theirs (their
979
982
  # author, boundary and cap), whoever started it.
@@ -33,15 +33,9 @@ module Samagotchi
33
33
  end
34
34
 
35
35
  # The hooks: config.yml's (Hooks::Loader; an empty Registry without a
36
- # hooks config). An installed record that still has class-file hooks (a
37
- # 0.157 install) adds a not-required failure each, which the Engine
38
- # announces at the first turn: they don't load (#tell_retired_hooks;
39
- # compat shim retired_class_file_hooks: Compat::SHIMS).
36
+ # hooks config).
40
37
  # @return [Hooks::Registry]
41
- def hooks
42
- tell_retired_hooks
43
- hooks_from_config
44
- end
38
+ def hooks = hooks_from_config
45
39
 
46
40
  # Load the installed bundles' plugins into +registries+; one that fails
47
41
  # goes to +failures+, a required one (a guardrail plugin) to the hook
@@ -71,23 +65,5 @@ module Samagotchi
71
65
 
72
66
  Hooks::Registry.new
73
67
  end
74
-
75
- # One failure per record whose hooks: map isn't empty; an empty
76
- # hooks/ dir is not one, nor a manifest.json that doesn't read (the
77
- # plugin loader and the rules report that: a record holding only hooks/
78
- # with an unreadable manifest.json is silent at start, as its hooks
79
- # wouldn't load anyway; `chi bundle status` lists it unreadable).
80
- def tell_retired_hooks
81
- require_relative "memory_bundle/provenance"
82
- MemoryBundle::Provenance.each_installed(holding: :hooks) do |bundle_name, bundle|
83
- next if bundle.error?
84
-
85
- Log.warn(:hooks, "bundle_hooks_retired", bundle: bundle_name, hooks: bundle.hooks.size)
86
- @hook_failures.add("hooks (bundle #{bundle_name})", MemoryBundle::Manifest::HooksRetired::WORDS, required: false)
87
- end
88
- rescue StandardError => e
89
- Log.error(:hooks, "bundles_load_failed", echo: "[samagotchi:hooks] failed to read the installed bundles: #{e.class}: #{e.message}",
90
- error: e.class.name)
91
- end
92
68
  end
93
69
  end
@@ -6,6 +6,7 @@ require "fileutils"
6
6
  require "time"
7
7
  require_relative "../atomic_file"
8
8
  require_relative "../log"
9
+ require_relative "../state_format"
9
10
  require_relative "approval"
10
11
 
11
12
  module Samagotchi
@@ -26,8 +27,16 @@ module Samagotchi
26
27
  # "once" is never stored. A file that doesn't parse is moved aside to
27
28
  # approvals.json.corrupt-<UTC time>[-N], with a warning, and the store
28
29
  # starts empty: it only means more asks, and nothing is overwritten.
30
+ #
31
+ # The file is a versioned store, {"version", "approvals": [...]}
32
+ # (FORMAT); a write keeps its version and the keys this chi doesn't
33
+ # know. A list of entries (what 0.165 and before write) is read too,
34
+ # and rewritten as the versioned store under the lock on that first
35
+ # read (compat shim approvals_array_read).
29
36
  class Approvals
30
37
  FILE = "approvals.json"
38
+ COLLECTION = "approvals"
39
+ FORMAT = StateFormat.new(version: 1, members: [StateFormat.required(:scope), StateFormat.extra(:extra, in_version: 1)])
31
40
  STORED_SCOPES = %w[session repo rule].freeze
32
41
  # Rules a stored answer allows only for its session: their asks offer
33
42
  # once/session, and a repo entry for the same call (from another
@@ -50,13 +59,13 @@ module Samagotchi
50
59
 
51
60
  # @return [Array<Hash>] the entries (string keys), oldest first
52
61
  def entries
53
- read
62
+ read.first
54
63
  end
55
64
 
56
65
  # @param verdict [Verdict] an ask with its targets and context
57
66
  # @return [Hash, nil] the first entry that allows it
58
67
  def match(verdict)
59
- self.class.find_in(read, verdict)
68
+ self.class.find_in(read.first, verdict)
60
69
  end
61
70
 
62
71
  # Store the verdict's allowed scope (not "once").
@@ -158,10 +167,13 @@ module Samagotchi
158
167
  private
159
168
 
160
169
  # @param locked [Boolean] the caller holds the store's lock
170
+ # @return [Array(Array<Hash>, StateFormat::Document)] the entries and,
171
+ # for a versioned store, its document (nil for a list or no file)
161
172
  def read(locked: false)
162
- return [] unless File.exist?(@path)
173
+ return [[], nil] unless File.exist?(@path)
163
174
 
164
- parse(File.read(@path))
175
+ list, document = parse(File.read(@path))
176
+ document ? [list, document] : version_list(locked: locked) || [list, nil]
165
177
  rescue JSON::ParserError, SystemCallError => e
166
178
  aside = begin
167
179
  locked ? set_aside : with_lock { set_aside }
@@ -175,14 +187,48 @@ module Samagotchi
175
187
  where = aside ? "moved it to #{aside}" : "left it in place"
176
188
  @warn.call("[samagotchi:guardrails] #{@path} is unreadable (#{e.message}); #{where}, no stored approvals apply")
177
189
  end
178
- []
190
+ [[], nil]
179
191
  end
180
192
 
193
+ # @return [Array(Array<Hash>, StateFormat::Document)] as #read's
181
194
  def parse(text)
182
195
  data = JSON.parse(text)
183
- raise JSON::ParserError, "not a list" unless data.is_a?(Array)
196
+ case data
197
+ when Hash
198
+ raise JSON::ParserError, "#{COLLECTION} is not a list" unless data.fetch(COLLECTION, []).is_a?(Array)
199
+
200
+ document = FORMAT.read(data, collection: COLLECTION)
201
+ # An entry it can't read (no scope) is kept as it is: it matches
202
+ # nothing, and a write keeps it for the chi that wrote it.
203
+ [document.entries.map(&:raw).select { |e| e.is_a?(Hash) }, document]
204
+ # compat shim approvals_array_read: the list 0.165 and before write.
205
+ when Array then [data.select { |e| e.is_a?(Hash) }, nil]
206
+ else raise JSON::ParserError, "not a list or a versioned store"
207
+ end
208
+ end
209
+
210
+ # compat shim approvals_array_read: rewrite a list as the versioned
211
+ # store, under the lock, if it is still a list. One that can't be
212
+ # written (a read-only state dir) or changed meanwhile is read as it
213
+ # is this time.
214
+ # @return [Array(Array<Hash>, StateFormat::Document), nil] as #read's; nil when not rewritten
215
+ def version_list(locked:)
216
+ locked ? version_list! : with_lock { version_list! }
217
+ rescue JSON::ParserError, SystemCallError
218
+ nil
219
+ end
220
+
221
+ def version_list!
222
+ list, document = parse(File.read(@path))
223
+ return [list, document] if document
224
+
225
+ document = FORMAT.read({ COLLECTION => list }, collection: COLLECTION)
226
+ write(document)
227
+ [list, document]
228
+ end
184
229
 
185
- data.select { |e| e.is_a?(Hash) }
230
+ def write(document)
231
+ AtomicFile.write(@path, JSON.pretty_generate(FORMAT.write(document, collection: COLLECTION, updated_at: nil)))
186
232
  end
187
233
 
188
234
  # Under the lock: rename the file aside if it is still unreadable.
@@ -215,11 +261,15 @@ module Samagotchi
215
261
  end
216
262
  end
217
263
 
264
+ # Writes the versioned store: one read keeps its version and the
265
+ # keys this chi doesn't know; no file (or one that couldn't be
266
+ # rewritten on read) starts at FORMAT's version.
218
267
  def update
219
268
  with_lock do
220
- list = read(locked: true)
269
+ list, document = read(locked: true)
221
270
  yield list
222
- AtomicFile.write(@path, JSON.pretty_generate(list))
271
+ document ||= FORMAT.read({}, collection: COLLECTION)
272
+ write(document.with(entries: list))
223
273
  end
224
274
  end
225
275
 
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "json"
5
+ require "time"
6
+
7
+ module Samagotchi
8
+ # One append-only JSONL file beside a session (FILE in its folder, 0600): a
9
+ # line is a Hash stamped with its time, and a broken line reads as none. The
10
+ # generic half of a side reader's state (ObjectivesCheck, ObjectivesTrack):
11
+ # what a line means, and which is the latest, stays with its reader.
12
+ class JsonlStore
13
+ attr_reader :file
14
+
15
+ # @param file [String] the file's name in a session's folder
16
+ def initialize(file)
17
+ @file = file
18
+ end
19
+
20
+ # Append one line, +now+ as its "at".
21
+ def write(session_dir, now: Time.now, **fields)
22
+ FileUtils.mkdir_p(session_dir)
23
+ File.open(File.join(session_dir, file), File::WRONLY | File::APPEND | File::CREAT, 0o600) do |io|
24
+ io.write("#{JSON.generate({ at: now.utc.iso8601(3), **fields })}\n")
25
+ end
26
+ end
27
+
28
+ # Every line that reads as a Hash, oldest first; none with no file.
29
+ # @return [Array<Hash>]
30
+ def lines(session_dir)
31
+ File.readlines(File.join(session_dir, file), chomp: true).filter_map do |raw|
32
+ line = JSON.parse(raw)
33
+ line if line.is_a?(Hash)
34
+ rescue JSON::ParserError
35
+ nil
36
+ end
37
+ rescue SystemCallError
38
+ []
39
+ end
40
+
41
+ # A line's "at"; the epoch for one that has none or a bad one.
42
+ def self.time_of(line)
43
+ Time.iso8601(line["at"].to_s)
44
+ rescue ArgumentError
45
+ Time.at(0)
46
+ end
47
+
48
+ # Whether the worker that wrote a running line still lives: a line with no
49
+ # pid is taken as alive (its time limit still frees it).
50
+ def self.worker_alive?(pid)
51
+ return true unless pid.is_a?(Integer)
52
+
53
+ Process.kill(0, pid)
54
+ true
55
+ rescue Errno::EPERM
56
+ true
57
+ rescue Errno::ESRCH
58
+ false
59
+ end
60
+ end
61
+ end
@@ -17,8 +17,7 @@ module Samagotchi
17
17
  # A bundle as this chi reads it now (what chi bundle status prints):
18
18
  # its stored record, the scope it resolves to (scope_error when it
19
19
  # can't), the folder its files belong in, what each file looks like on
20
- # disk, its installed plugin, the class-file hooks its record still
21
- # has (retired_hooks: they don't load), and its needs
20
+ # disk, its installed plugin, and its needs
22
21
  # with what this process's PATH found. The +files+ entries and +plugin+
23
22
  # stay Hashes: their fields differ per case (an unchecked file has no
24
23
  # paths at all). An entry's behind is its FileStanding::Behind, nil for a
@@ -27,7 +26,7 @@ module Samagotchi
27
26
  # rules and scripts: each recorded one by name, "ok", "modified" or
28
27
  # "missing" (asset_states).
29
28
  Report = Data.define(:provenance, :scope, :scope_error, :target_dir, :files, :plugin,
30
- :rules, :scripts, :retired_hooks, :needs)
29
+ :rules, :scripts, :needs)
31
30
 
32
31
  # A scope this chi can't resolve (a newer chi's, a hand edit) isn't
33
32
  # guessed: scope_error says so, target_dir is nil and each file is
@@ -75,7 +74,7 @@ module Samagotchi
75
74
  target_dir: target_dir, files: details, plugin: plugin_status(provenance, bundle),
76
75
  rules: asset_states(provenance.guardrails_dir, :rule, bundle.guardrails),
77
76
  scripts: asset_states(provenance.scripts_dir, :script, bundle.scripts),
78
- retired_hooks: retired_hooks(provenance, bundle), needs: needs_status(bundle))
77
+ needs: needs_status(bundle))
79
78
  end
80
79
 
81
80
  # A FileState digest as the Report has it: nil for none, or one that
@@ -83,17 +82,6 @@ module Samagotchi
83
82
  def self.digest_or_nil(digest) = digest == :unreadable ? nil : digest
84
83
  private_class_method :digest_or_nil
85
84
 
86
- # The class-file hooks the record still has (a 0.157 install's; chi
87
- # loads none, Manifest::HooksRetired), each "present" or "missing" in
88
- # hooks/, by name; {} for none (compat shim retired_class_file_hooks:
89
- # Compat::SHIMS).
90
- # @return [Hash{String => String}]
91
- def self.retired_hooks(provenance, bundle)
92
- bundle.hooks.keys.sort.to_h do |file|
93
- [file, File.exist?(File.join(provenance.hooks_dir, file)) ? "present" : "missing"]
94
- end
95
- end
96
-
97
85
  # Each recorded rule or script: "missing" (not there), "modified" (its
98
86
  # AssetState is edited: the next install replaces it, a copy kept in
99
87
  # the trash; an edited rule doesn't load) or "ok"; {} for none.
@@ -111,7 +111,7 @@ module Samagotchi
111
111
  from = bundle&.version.to_s
112
112
 
113
113
  if bundle.nil?
114
- dry_run ? result(:installed, to: to) : install_fresh(to)
114
+ dry_run ? planned_install(to) : install_fresh(to)
115
115
  elsif installed_newer?(from, to)
116
116
  # Running an older checkout/gem: never downgrade the user's system memories
117
117
  # (not even to restore a missing file). `chi self` shows installed vs shipped.
@@ -182,18 +182,24 @@ module Samagotchi
182
182
  end
183
183
 
184
184
  def install_fresh(to)
185
- installer = Installer.new(
186
- source: GEM_BUNDLE_DIR,
187
- name: BUNDLE_NAME,
188
- scope: SCOPE,
189
- force: false,
190
- strict: true,
191
- shipped_dir: File.dirname(GEM_BUNDLE_DIR)
192
- )
185
+ installer = fresh_installer
193
186
  installer.run
194
187
  result(:installed, to: to, warnings: installer.warnings)
195
188
  end
196
189
 
190
+ # A dry run's answer for a fresh install: its checksum mismatches, as
191
+ # planned_update gives an upgrade's.
192
+ def planned_install(to)
193
+ installer = fresh_installer(dry_run: true)
194
+ installer.run
195
+ result(:installed, to: to, warnings: installer.warnings.grep(/\AChecksum mismatch/))
196
+ end
197
+
198
+ def fresh_installer(dry_run: false)
199
+ Installer.new(source: GEM_BUNDLE_DIR, name: BUNDLE_NAME, scope: SCOPE, force: false, strict: true,
200
+ dry_run: dry_run, shipped_dir: File.dirname(GEM_BUNDLE_DIR))
201
+ end
202
+
197
203
  # Installer handles fast_forward/keep/noop; a conflict keeps the local
198
204
  # file, and its own warning is left out (behind says it).
199
205
  def upgrade_existing(from, to)
@@ -294,7 +300,7 @@ module Samagotchi
294
300
  dry_run: dry_run, shipped_dir: File.dirname(GEM_BUNDLE_DIR))
295
301
  end
296
302
  private_class_method :with_lock, :note_newer_installed, :install_fresh, :keep_manifest, :upgrade_existing, :verify_files_present, :restore_file, :remerge,
297
- :upgrade_installer, :result, :planned_update
303
+ :upgrade_installer, :result, :planned_update, :planned_install, :fresh_installer
298
304
  end
299
305
  end
300
306
  end
@@ -179,7 +179,8 @@ module Samagotchi
179
179
  return usage_error("ls takes no NAME (unexpected #{args.first})") unless args.empty?
180
180
 
181
181
  format = options[:format]
182
- return usage_error("unknown format #{format.inspect}: use --format text|json") unless [nil, "text", "json"].include?(format)
182
+ refused = format_refusal(format)
183
+ return refused if refused
183
184
 
184
185
  rows = self.class.entries(options[:scope])
185
186
  if format == "json"
@@ -215,7 +216,8 @@ module Samagotchi
215
216
  return usage_error("usage takes no NAME (unexpected #{args.first})") unless args.empty?
216
217
 
217
218
  format = options[:format]
218
- return usage_error("unknown format #{format.inspect}: use --format text|json") unless [nil, "text", "json"].include?(format)
219
+ refused = format_refusal(format)
220
+ return refused if refused
219
221
  return usage_error("--top must be a positive integer") unless options[:top].nil? || options[:top].to_s.match?(/\A[1-9]\d*\z/)
220
222
  return usage_error("--top must be at most #{TOP_LIMIT}") if options[:top].to_i > TOP_LIMIT
221
223