@zalom/plastic 1.4.1 → 1.6.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.
@@ -0,0 +1,236 @@
1
+ #!/usr/bin/env ruby
2
+ # encoding: UTF-8
3
+ # frozen_string_literal: true
4
+
5
+ # maintenance-run - the maintenance dispatch wrapper (intent 197). DETECTS (never acquires) a
6
+ # target intent's delivery lock (Lock.fresh?) and defers if fresh; otherwise runs the
7
+ # requested tool inside MaintenanceGit.run_scoped so the change and its revisions.md receipt
8
+ # land as ONE scoped, merged commit on the store's own main, never via `git add -A`.
9
+ #
10
+ # Dry-run by DEFAULT (mirrors restore-intent-v1's higher-blast-radius default, since this
11
+ # tool commits and merges on the shared store repo); --apply is required to write anything.
12
+ #
13
+ # Usage:
14
+ # maintenance-run --tool project-links --intent <id> [--store <key>] [--plastic-home PATH] [--apply]
15
+ # maintenance-run --tool rebuild-graph [--plastic-home PATH] [--apply]
16
+ # maintenance-run --tool restore-intent-v1 <id> --at <ref> [--plastic-home PATH] [--apply] [--skip-links]
17
+ #
18
+ # project-links here is ALWAYS single-intent: --intent is required. A store-wide
19
+ # project-links sweep is the rare, owner-approved batch exception (D2) and is run directly
20
+ # with the plain `project-links` tool, never through this wrapper.
21
+ #
22
+ # --store <key> (a StoreDiscovery key, e.g. "global" or "project:dealintell") disambiguates
23
+ # a bare id that exists in more than one store (real, live examples: ids 26 and 15 both
24
+ # collide across stores today) - both project-links --intent and restore-intent-v1's own id
25
+ # resolution abort loud naming every candidate when ambiguous and --store is not given;
26
+ # never silently pick the first match.
27
+ #
28
+ # Exit codes: 0 applied or clean no-op; 1 usage error; 2 deferred (a target holds a fresh
29
+ # delivery lock); 3 the underlying tool reported failure; 4 precondition failed (the store
30
+ # working tree was not clean, or is not a git repo at all).
31
+
32
+ require "open3"
33
+ require "time"
34
+
35
+ require_relative "lib/store_discovery"
36
+ require_relative "lib/lock"
37
+ require_relative "lib/maintenance_git"
38
+
39
+ DEFAULT_HOME = File.join(Dir.home, ".plastic")
40
+
41
+ # Resolves `id` to exactly one directory. `store:` (a StoreDiscovery key) short-circuits
42
+ # resolution to that one store. Without it, more than one matching store is an ambiguity
43
+ # this method itself aborts on (never silently pick the first match - the same class of bug
44
+ # ACTION_1 fixes inside project-links itself; this helper guards every OTHER caller of
45
+ # resolve_dir_for_id, i.e. rebuild-graph's touched-id lock scan and restore-intent-v1's id
46
+ # resolution, both of which route through this one function).
47
+ def resolve_dir_for_id(discovery, id, store: nil)
48
+ matches = []
49
+ discovery[:stores].each do |s|
50
+ next if store && s[:key] != store
51
+
52
+ Dir.children(s[:store]).reject { |e| e.start_with?(".") }.each do |entry|
53
+ full = File.join(s[:store], entry)
54
+ next unless File.directory?(full)
55
+
56
+ matches << [s[:key], full] if entry.split("--", 2).first == id.to_s
57
+ end
58
+ end
59
+
60
+ return nil if matches.empty?
61
+ if matches.length > 1
62
+ abort_loud("intent #{id.inspect} is ambiguous across stores " \
63
+ "(#{matches.map(&:first).join(", ")}); pass --store <key> to disambiguate")
64
+ end
65
+ matches.first.last
66
+ end
67
+
68
+ def abort_loud(msg, code = 1)
69
+ warn "maintenance-run: #{msg}"
70
+ exit code
71
+ end
72
+
73
+ def parse_argv(argv)
74
+ opts = { tool: nil, intent: nil, store: nil, plastic_home: DEFAULT_HOME, apply: false,
75
+ at: nil, skip_links: false, id: nil }
76
+ i = 0
77
+ while i < argv.length
78
+ case argv[i]
79
+ when "--tool" then opts[:tool] = argv[i += 1]
80
+ when "--intent" then opts[:intent] = argv[i += 1]
81
+ when "--store" then opts[:store] = argv[i += 1]
82
+ when "--plastic-home" then opts[:plastic_home] = argv[i += 1]
83
+ when "--apply" then opts[:apply] = true
84
+ when "--at" then opts[:at] = argv[i += 1]
85
+ when "--skip-links" then opts[:skip_links] = true
86
+ else
87
+ opts[:id] ||= argv[i] # positional id, restore-intent-v1 only
88
+ end
89
+ i += 1
90
+ end
91
+ opts
92
+ end
93
+
94
+ def check_not_fresh!(dir, id)
95
+ return unless dir && Lock.fresh?(dir)
96
+
97
+ abort_loud("deferred: intent #{id} holds a FRESH delivery lock; an active delivery is in " \
98
+ "progress. Maintenance never acquires a lock and never waits on one; re-run " \
99
+ "once the delivery finishes or the lock goes stale.", 2)
100
+ end
101
+
102
+ def stamp
103
+ Time.now.utc.strftime("%Y%m%d%H%M%S")
104
+ end
105
+
106
+ def report_result(result)
107
+ if result[:committed]
108
+ puts "maintenance-run: applied and merged (#{result[:changed].size} path(s)): " \
109
+ "#{result[:changed].join(", ")}"
110
+ else
111
+ puts "maintenance-run: no change (already canonical)."
112
+ end
113
+ exit 0
114
+ end
115
+
116
+ def run_project_links(home, intent, store, apply)
117
+ abort_loud("--tool project-links requires --intent <id> (a store-wide sweep runs " \
118
+ "scripts/project-links directly, never through maintenance-run)") unless intent
119
+
120
+ discovery = StoreDiscovery.discover(home)
121
+ dir = resolve_dir_for_id(discovery, intent, store: store) # aborts loud itself on ambiguity
122
+ abort_loud("intent #{intent} not found under #{home}#{store ? " (--store #{store})" : ""}") unless dir
123
+ check_not_fresh!(dir, intent)
124
+
125
+ tool_path = File.expand_path("project-links", __dir__)
126
+ base_args = ["--plastic-home", home, "--intent", intent]
127
+ base_args += ["--store", store] if store
128
+
129
+ unless apply
130
+ system(RbConfig.ruby, tool_path, *base_args, "--dry-run")
131
+ exit($?.exitstatus)
132
+ end
133
+
134
+ begin
135
+ result = MaintenanceGit.run_scoped(
136
+ repo_dir: home, branch_name: "maintenance/project-links-#{intent}-#{stamp}",
137
+ commit_message: "chore: maintenance - project-links --intent #{intent}"
138
+ ) do
139
+ ok = system(RbConfig.ruby, tool_path, *base_args)
140
+ raise "project-links failed for #{intent}" unless ok
141
+ end
142
+ rescue MaintenanceGit::DirtyWorkingTree, MaintenanceGit::NotAGitRepo => e
143
+ abort_loud(e.message, 4)
144
+ rescue RuntimeError => e
145
+ abort_loud(e.message, 3)
146
+ end
147
+ report_result(result)
148
+ end
149
+
150
+ def run_rebuild_graph(home, apply)
151
+ tool_path = File.expand_path("rebuild-graph", __dir__)
152
+ load tool_path unless defined?(RebuildGraph) # matches test/*_test.rb's own load convention
153
+
154
+ discovery = StoreDiscovery.discover(home)
155
+ dry = RebuildGraph.new(plastic_home: home, dry_run: true)
156
+ dry_results = dry.run
157
+ touched_ids = dry_results.values.flat_map { |r| r[:changes].map { |c| c[:intent] } }.uniq
158
+
159
+ touched_ids.each { |id| check_not_fresh!(resolve_dir_for_id(discovery, id), id) }
160
+
161
+ unless apply
162
+ puts "maintenance-run: DRY RUN, #{touched_ids.size} intent(s) would change: #{touched_ids.join(", ")}"
163
+ exit 0
164
+ end
165
+
166
+ begin
167
+ result = MaintenanceGit.run_scoped(
168
+ repo_dir: home, branch_name: "maintenance/rebuild-graph-#{stamp}",
169
+ commit_message: "chore: maintenance - rebuild-graph"
170
+ ) do
171
+ ok = system(RbConfig.ruby, tool_path, "--plastic-home", home)
172
+ raise "rebuild-graph failed" unless ok
173
+ end
174
+ rescue MaintenanceGit::DirtyWorkingTree, MaintenanceGit::NotAGitRepo => e
175
+ abort_loud(e.message, 4)
176
+ rescue RuntimeError => e
177
+ abort_loud(e.message, 3)
178
+ end
179
+ report_result(result)
180
+ end
181
+
182
+ def run_restore_intent_v1(home, id, at, store, apply, skip_links)
183
+ abort_loud("restore-intent-v1 requires an intent id and --at <ref>") unless id && at
184
+
185
+ discovery = StoreDiscovery.discover(home)
186
+ # NOTE: restore-intent-v1's own CLI (scripts/restore-intent-v1:219-238, find_intent_dir)
187
+ # already aborts loud on a cross-store id collision; this resolve_dir_for_id call is only
188
+ # for the LOCK CHECK here (maintenance-run must know which one directory to check
189
+ # Lock.fresh? against). --store is honored the same way for consistency; if omitted and
190
+ # the id is ambiguous, this call aborts BEFORE restore-intent-v1 itself would have run.
191
+ dir = resolve_dir_for_id(discovery, id, store: store)
192
+ abort_loud("intent #{id} not found under #{home}#{store ? " (--store #{store})" : ""}") unless dir
193
+ check_not_fresh!(dir, id)
194
+
195
+ tool_path = File.expand_path("restore-intent-v1", __dir__)
196
+ args = [tool_path, id, "--at", at, "--plastic-home", home]
197
+ args << "--skip-links" if skip_links
198
+
199
+ unless apply
200
+ system(RbConfig.ruby, *args)
201
+ exit($?.exitstatus)
202
+ end
203
+
204
+ begin
205
+ result = MaintenanceGit.run_scoped(
206
+ repo_dir: home, branch_name: "maintenance/restore-intent-v1-#{id}-#{stamp}",
207
+ commit_message: "chore: maintenance - restore-intent-v1 #{id}"
208
+ ) do
209
+ ok = system(RbConfig.ruby, *args, "--apply")
210
+ raise "restore-intent-v1 failed for #{id}" unless ok
211
+ end
212
+ rescue MaintenanceGit::DirtyWorkingTree, MaintenanceGit::NotAGitRepo => e
213
+ abort_loud(e.message, 4)
214
+ rescue RuntimeError => e
215
+ abort_loud(e.message, 3)
216
+ end
217
+ report_result(result)
218
+ end
219
+
220
+ def main(argv)
221
+ opts = parse_argv(argv)
222
+ abort_loud("--tool is required (project-links|rebuild-graph|restore-intent-v1)") unless opts[:tool]
223
+
224
+ case opts[:tool]
225
+ when "project-links"
226
+ run_project_links(opts[:plastic_home], opts[:intent], opts[:store], opts[:apply])
227
+ when "rebuild-graph" then run_rebuild_graph(opts[:plastic_home], opts[:apply])
228
+ when "restore-intent-v1"
229
+ run_restore_intent_v1(opts[:plastic_home], opts[:id], opts[:at], opts[:store], opts[:apply], opts[:skip_links])
230
+ else
231
+ abort_loud("unknown --tool #{opts[:tool].inspect} " \
232
+ "(expected project-links|rebuild-graph|restore-intent-v1)")
233
+ end
234
+ end
235
+
236
+ main(ARGV) if $PROGRAM_NAME == __FILE__
@@ -18,11 +18,16 @@
18
18
  # reported in the audit, never silently deleted. Pass --drop-unbacked-links to
19
19
  # delete orphan candidates deliberately (reported separately from a silent
20
20
  # drop). A line that resolves to nothing (a broken or mistyped wikilink) is
21
- # still dropped silently, exactly as before: it names no real relationship to
22
- # lose.
21
+ # still dropped from the file (it names no real relationship to keep), but
22
+ # reported in the audit as a malformed-reference finding rather than
23
+ # vanishing without a trace (intent 197).
23
24
  #
24
25
  # Usage:
25
26
  # project-links [--plastic-home PATH] [--dry-run] [--audit-path PATH] [--drop-unbacked-links]
27
+ # [--intent <id> [--store <key>]]
28
+ #
29
+ # --store only matters when --intent alone is ambiguous across stores (the tool
30
+ # aborts loud, naming every candidate store, rather than silently picking one).
26
31
  #
27
32
  # Pure-Ruby (no bash). The pure logic lives in lib/links_projection.rb and
28
33
  # lib/links_section.rb; this shell does only discovery, IO, and reporting. It reads
@@ -38,6 +43,7 @@ require_relative "lib/graph_rebuild"
38
43
  require_relative "lib/links_projection"
39
44
  require_relative "lib/links_section"
40
45
  require_relative "lib/store_discovery"
46
+ require_relative "lib/revisions_writer"
41
47
 
42
48
  class ProjectLinks
43
49
  DEFAULT_HOME = File.join(Dir.home, ".plastic")
@@ -47,10 +53,12 @@ class ProjectLinks
47
53
  "projects/plastic/store/72--links-graph-projection/resources/audit--links-projection.md"
48
54
 
49
55
  def initialize(plastic_home: DEFAULT_HOME, dry_run: false, audit_path: nil,
50
- drop_unbacked_links: false)
56
+ drop_unbacked_links: false, intent: nil, store: nil)
51
57
  @plastic_home = plastic_home
52
58
  @dry_run = dry_run
53
59
  @drop_unbacked_links = drop_unbacked_links
60
+ @intent = intent && intent.to_s
61
+ @store = store
54
62
 
55
63
  # A dry run must NOT stomp the canonical audit (humans run --dry-run to review
56
64
  # the plan). With no explicit --audit-path, a dry run writes a `.dry-run.md`
@@ -68,7 +76,7 @@ class ProjectLinks
68
76
  end
69
77
  end
70
78
 
71
- attr_reader :plastic_home, :dry_run, :audit_path, :drop_unbacked_links
79
+ attr_reader :plastic_home, :dry_run, :audit_path, :drop_unbacked_links, :intent, :store
72
80
 
73
81
  # Every store in scope: global plus every projects/<slug>/store directory that exists
74
82
  # (intent 189). Shares its definition with rebuild-graph, doctor.rb, and new-intent via
@@ -130,13 +138,23 @@ class ProjectLinks
130
138
 
131
139
  relocation_map = GraphRebuild.build_relocation_map(index_texts)
132
140
 
141
+ target_store_key = intent ? resolve_target_store(store_list, nodes_by_store, intent) : nil
142
+
133
143
  results = {}
134
144
  store_list.each do |s|
135
145
  key = s[:key]
136
- results[key] = project_store(
137
- key, nodes_by_store[key],
138
- relocation_map: relocation_map, store_index: store_index, node_index: node_index
139
- )
146
+ if intent
147
+ results[key] = (key == target_store_key) ? project_store(
148
+ key, nodes_by_store[key],
149
+ relocation_map: relocation_map, store_index: store_index, node_index: node_index,
150
+ only: intent
151
+ ) : { entries: [], counts: Hash.new(0) }
152
+ else
153
+ results[key] = project_store(
154
+ key, nodes_by_store[key],
155
+ relocation_map: relocation_map, store_index: store_index, node_index: node_index
156
+ )
157
+ end
140
158
  end
141
159
 
142
160
  emit_audit(store_list, results)
@@ -146,9 +164,10 @@ class ProjectLinks
146
164
  # Project every intent in ONE store. Returns
147
165
  # { entries: [ {id:, status:, before:, after:, error:, orphans_preserved:,
148
166
  # orphans_dropped_optin:} ], counts: {...} }.
149
- def project_store(referer_store, nodes, relocation_map:, store_index:, node_index:)
167
+ def project_store(referer_store, nodes, relocation_map:, store_index:, node_index:, only: nil)
150
168
  entries = []
151
169
  nodes.each do |id, node|
170
+ next if only && id != only
152
171
  resolve = ->(ref) do
153
172
  LinksProjection.resolve_ref_projection(
154
173
  ref, referer_store: referer_store,
@@ -164,7 +183,7 @@ class ProjectLinks
164
183
  canonical_text = LinksProjection.section(
165
184
  sources: node[:sources], chain: node[:chain], resolve: resolve
166
185
  )
167
- kept, dropped_optin = orphan_split(old_text, canonical_text, referer_store,
186
+ kept, dropped_optin, dead = orphan_split(old_text, canonical_text, referer_store,
168
187
  store_index, node_index)
169
188
  section_text = LinksProjection.render_entries(
170
189
  LinksProjection.parse_entries(canonical_text) + kept
@@ -172,42 +191,107 @@ class ProjectLinks
172
191
  updated = LinksSection.rewrite(content, section_text)
173
192
  rescue LinksProjection::UnresolvedRef, LinksSection::AmbiguousLinks => e
174
193
  entries << { id: id, status: :failed, error: e.message,
175
- orphans_preserved: [], orphans_dropped_optin: [] }
194
+ orphans_preserved: [], orphans_dropped_optin: [], orphans_dead: [] }
176
195
  next
177
196
  end
178
197
 
179
198
  if updated == content
180
- entries << { id: id, status: :unchanged,
181
- orphans_preserved: kept, orphans_dropped_optin: dropped_optin }
199
+ entries << { id: id, status: :unchanged, orphans_preserved: kept,
200
+ orphans_dropped_optin: dropped_optin, orphans_dead: dead }
182
201
  next
183
202
  end
184
203
 
185
204
  status = had_links ? :regenerated : :added
186
- File.write(node[:path], updated) unless dry_run
205
+
206
+ unless dry_run
207
+ begin
208
+ RevisionsWriter.append!(
209
+ File.dirname(node[:path]),
210
+ why: revision_why(status, kept, dropped_optin, dead),
211
+ rule: "links-projection",
212
+ prior_location: "#{node[:basename]}.md ## Links",
213
+ change: revision_change(old_text, section_text)
214
+ )
215
+ rescue RevisionsWriter::WriteFailed => e
216
+ entries << { id: id, status: :failed, error: e.message,
217
+ orphans_preserved: [], orphans_dropped_optin: [], orphans_dead: [] }
218
+ next
219
+ end
220
+ File.write(node[:path], updated)
221
+ end
222
+
187
223
  entries << { id: id, status: status, before: old_text, after: section_text,
188
- orphans_preserved: kept, orphans_dropped_optin: dropped_optin }
224
+ orphans_preserved: kept, orphans_dropped_optin: dropped_optin, orphans_dead: dead }
189
225
  end
190
226
 
191
227
  counts = entries.each_with_object(Hash.new(0)) { |e, h| h[e[:status]] += 1 }
192
228
  { entries: entries, counts: counts }
193
229
  end
194
230
 
231
+ # Resolves --intent to exactly ONE store key, aborting loud on ambiguity (mirrors
232
+ # scripts/restore-intent-v1's find_intent_dir, which solves this identical cross-store
233
+ # id-collision problem the same way). `store:` (explicit --store) short-circuits resolution
234
+ # when the caller already knows which store; otherwise every store containing a matching
235
+ # id is a candidate, and more than one is a hard abort (never silently pick one). An id
236
+ # found in NO store is not an error (unlike restore-intent-v1's higher blast radius): it
237
+ # resolves to nil, so every store gets the synthetic zero-activity result in `run` (a
238
+ # provably observable no-op, not a crash) rather than aborting a caller that may be
239
+ # running this defensively (e.g. before an id is known to exist yet).
240
+ def resolve_target_store(store_list, nodes_by_store, intent)
241
+ if store
242
+ abort "project-links: --store #{store.inspect} has no intent #{intent.inspect}" \
243
+ unless nodes_by_store[store]&.key?(intent)
244
+ return store
245
+ end
246
+
247
+ candidates = store_list.select { |s| nodes_by_store[s[:key]].key?(intent) }.map { |s| s[:key] }
248
+ return nil if candidates.empty?
249
+ if candidates.length > 1
250
+ abort "project-links: intent #{intent.inspect} is ambiguous across stores " \
251
+ "(#{candidates.join(", ")}); pass --store <key> to disambiguate (e.g. --store " \
252
+ "#{candidates.first})"
253
+ end
254
+ candidates.first
255
+ end
256
+
257
+ # Renders the one-sentence "Why" for a project-links-authored receipt. Free text; the
258
+ # [rule: tag] suffix is appended by RevisionsWriter itself, not here.
259
+ def revision_why(status, kept, dropped_optin, dead)
260
+ parts = []
261
+ parts << (status == :added ? "added a missing ## Links section" : "regenerated ## Links to match frontmatter")
262
+ parts << "dropped #{dead.size} unresolvable reference(s)" unless dead.empty?
263
+ parts << "dropped #{dropped_optin.size} unbacked-but-resolvable reference(s) (--drop-unbacked-links)" unless dropped_optin.empty?
264
+ parts.join("; ")
265
+ end
266
+
267
+ def revision_change(before_text, after_text)
268
+ "## Links regenerated (before -> after)\n\n BEFORE:\n" \
269
+ "#{block_lines(before_text).map { |l| " #{l}" }.join("\n")}\n\n AFTER:\n" \
270
+ "#{block_lines(after_text).map { |l| " #{l}" }.join("\n")}"
271
+ end
272
+
195
273
  # Split the OLD (pre-mutation) `## Links` entries into orphans to KEEP
196
274
  # (unbacked by frontmatter but resolve to a real, currently-discovered
197
275
  # intent) vs DROP under the explicit --drop-unbacked-links opt-in. An entry
198
- # that resolves nowhere is neither: it is dropped silently, exactly as before
199
- # intent 192 (this is dealintell 3b's three broken single-dash lines:
200
- # garbage, not data). Returns [kept_entries, dropped_optin_entries], both
201
- # [{target:, label:}].
276
+ # that resolves nowhere is neither: it is dropped from the file (nothing real to
277
+ # preserve) but reported as a malformed-reference finding, not silently (intent 197;
278
+ # this is dealintell 3b's three broken single-dash lines: garbage, not data).
279
+ # Returns [kept_entries, dropped_optin_entries, dead_entries].
202
280
  def orphan_split(old_text, canonical_text, referer_store, store_index, node_index)
203
281
  canonical_targets = LinksProjection.parse_entries(canonical_text).map { |e| e[:target] }
204
282
  kept = []
205
283
  dropped_optin = []
284
+ dead = []
206
285
  LinksProjection.parse_entries(old_text).each do |oe|
207
286
  next if canonical_targets.include?(oe[:target]) # already backed; not an orphan
208
287
 
209
288
  label = resolve_orphan_label(oe[:target], referer_store, store_index, node_index)
210
- next if label.nil? # dead: not backed AND does not resolve; silent drop, as before
289
+ if label.nil?
290
+ # Resolves to nothing: still dropped from the file (nothing real to preserve),
291
+ # but no longer silent. Reported as a malformed-orphan candidate in the audit.
292
+ dead << { target: oe[:target] }
293
+ next
294
+ end
211
295
 
212
296
  if drop_unbacked_links
213
297
  dropped_optin << oe
@@ -215,7 +299,7 @@ class ProjectLinks
215
299
  kept << { target: oe[:target], label: label }
216
300
  end
217
301
  end
218
- [kept, dropped_optin]
302
+ [kept, dropped_optin, dead]
219
303
  end
220
304
 
221
305
  # Does `target` (already in projected `id--slug` or `store:id--slug` form)
@@ -267,6 +351,7 @@ class ProjectLinks
267
351
  lines << "# Audit: store-wide ## Links projection (intent 72)"
268
352
  lines << ""
269
353
  lines << "Generated: #{Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ")}#{dry_run ? " (DRY RUN)" : ""}"
354
+ lines << "Scoped to intent #{intent} only (--intent)." if intent
270
355
  lines << ""
271
356
 
272
357
  total = STATUS_ORDER.to_h do |st|
@@ -274,11 +359,13 @@ class ProjectLinks
274
359
  end
275
360
  total_preserved = store_list.sum { |s| results[s[:key]][:entries].sum { |e| Array(e[:orphans_preserved]).size } }
276
361
  total_dropped_optin = store_list.sum { |s| results[s[:key]][:entries].sum { |e| Array(e[:orphans_dropped_optin]).size } }
362
+ total_dead = store_list.sum { |s| results[s[:key]][:entries].sum { |e| Array(e[:orphans_dead]).size } }
277
363
  lines << "Totals across all stores: " \
278
364
  "regenerated #{total[:regenerated]}, added #{total[:added]}, " \
279
365
  "unchanged #{total[:unchanged]}, failed #{total[:failed]}. " \
280
366
  "Unbacked Links lines preserved as orphan candidates: #{total_preserved}" \
281
- "#{drop_unbacked_links ? ", dropped via --drop-unbacked-links: #{total_dropped_optin}" : ""}."
367
+ "#{drop_unbacked_links ? ", dropped via --drop-unbacked-links: #{total_dropped_optin}" : ""}" \
368
+ ", malformed references found: #{total_dead}."
282
369
  lines << ""
283
370
 
284
371
  unless missing_stores.empty?
@@ -321,6 +408,17 @@ class ProjectLinks
321
408
  lines << ""
322
409
  end
323
410
 
411
+ dead_refs = res[:entries].flat_map { |e| Array(e[:orphans_dead]).map { |o| [e[:id], o] } }
412
+ unless dead_refs.empty?
413
+ lines << "### Malformed references found, dropped silently before this fix (#{dead_refs.size})"
414
+ lines << "Resolve to no real intent under any known store; these are dropped from the " \
415
+ "regenerated ## Links section (nothing real to preserve), but were previously " \
416
+ "invisible to every check. Confirm each is genuinely dead (a typo'd slug, a " \
417
+ "sibling wrongly linked) rather than a missing store/relocation before trusting."
418
+ dead_refs.each { |id, o| lines << "- #{id}: -> #{o[:target]}" }
419
+ lines << ""
420
+ end
421
+
324
422
  sample = res[:entries].select { |e| %i[regenerated added].include?(e[:status]) }.first(5)
325
423
  next if sample.empty?
326
424
 
@@ -356,6 +454,8 @@ if $PROGRAM_NAME == __FILE__
356
454
  dry = false
357
455
  audit = nil
358
456
  drop = false
457
+ intent = nil
458
+ store = nil
359
459
  i = 0
360
460
  while i < ARGV.length
361
461
  case ARGV[i]
@@ -363,14 +463,17 @@ if $PROGRAM_NAME == __FILE__
363
463
  when "--dry-run" then dry = true; i += 1
364
464
  when "--audit-path" then audit = ARGV[i + 1]; i += 2
365
465
  when "--drop-unbacked-links" then drop = true; i += 1
466
+ when "--intent" then intent = ARGV[i + 1]; i += 2
467
+ when "--store" then store = ARGV[i + 1]; i += 2
366
468
  else
367
469
  abort "project-links: unknown argument #{ARGV[i].inspect} " \
368
- "(usage: --plastic-home PATH | --dry-run | --audit-path PATH | --drop-unbacked-links)"
470
+ "(usage: --plastic-home PATH | --dry-run | --audit-path PATH | " \
471
+ "--drop-unbacked-links | --intent <id> [--store <key>])"
369
472
  end
370
473
  end
371
474
 
372
475
  tool = ProjectLinks.new(plastic_home: home, dry_run: dry, audit_path: audit,
373
- drop_unbacked_links: drop)
476
+ drop_unbacked_links: drop, intent: intent, store: store)
374
477
  results = tool.run
375
478
  totals = ProjectLinks::STATUS_ORDER.to_h do |st|
376
479
  [st, results.values.sum { |r| r[:counts][st] }]
@@ -25,6 +25,7 @@ require_relative "lib/graph_rebuild"
25
25
  require_relative "lib/frontmatter_writer"
26
26
  require_relative "lib/intent_validator"
27
27
  require_relative "lib/store_discovery"
28
+ require_relative "lib/revisions_writer"
28
29
 
29
30
  class RebuildGraph
30
31
  DEFAULT_HOME = File.join(Dir.home, ".plastic")
@@ -47,6 +48,7 @@ class RebuildGraph
47
48
  def initialize(plastic_home: DEFAULT_HOME, dry_run: false, audit_path: nil)
48
49
  @plastic_home = plastic_home
49
50
  @dry_run = dry_run
51
+ @write_failures = []
50
52
 
51
53
  # A dry run must NOT stomp the canonical audit (the spec/checklist tell humans
52
54
  # to run --dry-run to review the plan). When no explicit --audit-path is given,
@@ -64,7 +66,11 @@ class RebuildGraph
64
66
  end
65
67
  end
66
68
 
67
- attr_reader :plastic_home, :dry_run, :audit_path
69
+ attr_reader :plastic_home, :dry_run, :audit_path, :write_failures
70
+
71
+ def any_write_failures?
72
+ !write_failures.empty?
73
+ end
68
74
 
69
75
  # Every store in scope: global plus every projects/<slug>/store directory that exists
70
76
  # (intent 189). A superset of reality, not a hardcoded list: missing a real store here
@@ -140,11 +146,15 @@ class RebuildGraph
140
146
  results
141
147
  end
142
148
 
143
- # Write changed frontmatter back via the minimal style-preserving writer.
149
+ # Write changed frontmatter back via the minimal style-preserving writer. Every applied
150
+ # change writes a revisions.md receipt FIRST (intent 197): if the receipt cannot be
151
+ # written, the frontmatter change is withheld (reported in write_failures) rather than
152
+ # left unrecorded.
144
153
  def write_back(store_list, nodes_by_store, results)
145
154
  store_list.each do |s|
146
155
  key = s[:key]
147
156
  new_nodes = results[key][:nodes]
157
+ changes_by_id = results[key][:changes].group_by { |c| c[:intent] }
148
158
  nodes_by_store[key].each do |id, original|
149
159
  rebuilt = new_nodes[id]
150
160
  next if rebuilt.nil?
@@ -154,7 +164,22 @@ class RebuildGraph
154
164
  updated = FrontmatterWriter.rewrite_arrays(content,
155
165
  sources: rebuilt[:sources],
156
166
  chain: rebuilt[:chain])
157
- File.write(original[:path], updated) if updated != content
167
+ next if updated == content
168
+
169
+ id_changes = changes_by_id[id] || []
170
+ begin
171
+ RevisionsWriter.append!(
172
+ File.dirname(original[:path]),
173
+ why: "graph rebuild: #{id_changes.map { |c| c[:kind] }.uniq.join(", ")}",
174
+ rule: "graph-rebuild",
175
+ prior_location: "#{File.basename(original[:path], ".md")}.md frontmatter - sources/chain",
176
+ change: id_changes.map { |c| format_change(c) }.join("; ")
177
+ )
178
+ rescue RevisionsWriter::WriteFailed => e
179
+ @write_failures << { id: id, error: e.message }
180
+ next
181
+ end
182
+ File.write(original[:path], updated)
158
183
  end
159
184
  end
160
185
  end
@@ -191,6 +216,13 @@ class RebuildGraph
191
216
  lines << ""
192
217
  end
193
218
 
219
+ unless write_failures.empty?
220
+ lines << "## Frontmatter changes that could NOT be written (revisions.md receipt failed)"
221
+ lines << ""
222
+ write_failures.each { |f| lines << "- #{f[:id]}: #{f[:error]}" }
223
+ lines << ""
224
+ end
225
+
194
226
  unless missing_stores.empty?
195
227
  lines << "## Registered projects with no store on disk"
196
228
  lines << ""
@@ -266,4 +298,6 @@ if $PROGRAM_NAME == __FILE__
266
298
  puts "rebuild-graph #{dry ? "DRY RUN" : "applied"}: #{total} change(s) across #{results.size} store(s)."
267
299
  puts "Unknown-store refs preserved (not dropped): #{preserved}" if preserved.positive?
268
300
  puts "Audit: #{tool.audit_path}"
301
+ puts "Write failures (receipt could not be recorded, change withheld): #{tool.write_failures.size}" if tool.any_write_failures?
302
+ exit 1 if tool.any_write_failures?
269
303
  end