teaimforge 0.19.0__py3-none-any.whl

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.
teaimforge/cli.py ADDED
@@ -0,0 +1,823 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The command line every team shares.
3
+
4
+ A team builds one :class:`App` from its ``Domain`` and gets every generic
5
+ command: ``init``, ``new``, ``move``, ``rename``, ``assign``, ``show``, ``list``,
6
+ ``ledger``, ``reindex``, ``archive``, ``verify``, ``migrate``, ``backup``,
7
+ ``restore``, and the ``gate``, ``finding``, ``insight``, ``msg`` and ``hook``
8
+ groups. A team adds to it through a few hooks rather than copying it:
9
+
10
+ - ``new_options`` and ``new_fields``: extra options on ``new`` and the rule that
11
+ turns them into the new item's front-matter;
12
+ - ``list_filters``: front-matter fields ``list`` can filter on (``--NAME VALUE``);
13
+ - ``show_fields``: front-matter fields ``show`` prints when set;
14
+ - ``commands``: commands of the team's own, or a replacement for a core one.
15
+
16
+ Every write runs under a pinned identity, resolved before anything else;
17
+ commands that write nothing run without one.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import os
24
+ import sys
25
+ from collections.abc import Callable, Mapping, Sequence
26
+ from dataclasses import dataclass, field, replace
27
+ from pathlib import Path
28
+ from typing import Any, NoReturn
29
+
30
+ from .archive import Archiver, kept_dir
31
+ from .backup import Backups
32
+ from .config import init_project, load_config
33
+ from .domain import Domain
34
+ from .errors import ExitCode, ForgeError
35
+ from .events import EventStore
36
+ from .findings import RESOLUTIONS, Findings
37
+ from .gates import CHANNELS, Gate, Gates
38
+ from .identity import Identity, resolve, run_hook
39
+ from .index import Index, require_type
40
+ from .insights import Insights
41
+ from .items import Item, Items
42
+ from .ledger import Ledger
43
+ from .messages import KINDS as MSG_KINDS
44
+ from .messages import PRIORITIES as MSG_PRIORITIES
45
+ from .messages import STATES as MSG_STATES
46
+ from .messages import Messages
47
+ from .migrate import Migrator, Plan
48
+ from .output import Output
49
+ from .paths import Layout, find_root
50
+ from .views import describe_item
51
+ from .walls import lane_guard_hook
52
+
53
+ Builder = Callable[[argparse.ArgumentParser], None]
54
+ NewFields = Callable[[argparse.Namespace, Items, Identity], dict[str, Any]]
55
+ _DASH = " — "
56
+
57
+ #: Commands that run without a pinned identity: they write no events.
58
+ NO_IDENTITY = frozenset(
59
+ {"init", "verify", "show", "list", "gate list", "hook identity", "hook lane-guard"}
60
+ )
61
+ #: Commands that write nothing when given ``--check``.
62
+ CHECK_ONLY = frozenset({"ledger", "migrate"})
63
+
64
+
65
+ class _Parser(argparse.ArgumentParser):
66
+ """An argparse parser that raises instead of printing and exiting with 2."""
67
+
68
+ def error(self, message: str) -> NoReturn:
69
+ raise ForgeError(ExitCode.USAGE, "usage", message)
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Context:
74
+ """What a command handler gets: the app, its arguments, output and pinned identity."""
75
+
76
+ app: App
77
+ args: argparse.Namespace
78
+ out: Output
79
+ identity: Identity | None = None
80
+
81
+ @property
82
+ def domain(self) -> Domain:
83
+ return self.app.domain
84
+
85
+ def who(self) -> Identity:
86
+ """The pinned identity; an internal error if the command was not given one."""
87
+ if self.identity is None:
88
+ raise ForgeError(ExitCode.INTERNAL, "no_identity", f"{self.args.command_name} wrote")
89
+ return self.identity
90
+
91
+ def emit(
92
+ self,
93
+ store: EventStore,
94
+ event_type: str,
95
+ data: Mapping[str, Any] | None = None,
96
+ *,
97
+ item: str | None = None,
98
+ title: str | None = None,
99
+ ) -> dict[str, Any]:
100
+ """Append an event as the pinned identity. There is no way to name another actor."""
101
+ who = self.who()
102
+ return store.append(
103
+ event_type, actor=who.role, session=who.session, data=data, item=item, title=title
104
+ )
105
+
106
+ def root(self) -> Path | None:
107
+ root = getattr(self.args, "root", None)
108
+ return Path(root) if root else None
109
+
110
+ def layout(self) -> tuple[Layout, Mapping[str, Any]]:
111
+ """The project's layout and validated config."""
112
+ layout = find_root(self.domain, explicit=self.root())
113
+ return layout, load_config(layout, self.domain).data
114
+
115
+ def items(self) -> Items:
116
+ layout, config = self.layout()
117
+ return Items(layout, self.domain, self.identity, config)
118
+
119
+
120
+ Handler = Callable[[Context], None]
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class Command:
125
+ """One command as typed (``"gate rule"``), its arguments and its handler."""
126
+
127
+ name: str
128
+ help: str
129
+ run: Handler
130
+ build: Builder | None = None
131
+ group_help: str = "" # for the first command of a new group
132
+ writes: bool = True # False: runs without a pinned identity and writes no events
133
+
134
+
135
+ def _no_args(_: argparse.ArgumentParser) -> None:
136
+ """Command takes no arguments."""
137
+
138
+
139
+ def _id(p: argparse.ArgumentParser, name: str = "id", help_text: str = "item ID") -> None:
140
+ p.add_argument(name, metavar=name.upper(), help=help_text)
141
+
142
+
143
+ class App:
144
+ """A team's command line: the core commands plus the team's hooks."""
145
+
146
+ def __init__( # noqa: PLR0913 - each hook is optional and named
147
+ self,
148
+ domain: Domain,
149
+ *,
150
+ version: str,
151
+ description: str,
152
+ new_options: Builder | None = None,
153
+ new_fields: NewFields | None = None,
154
+ list_filters: Sequence[str] = (),
155
+ show_fields: Sequence[str] = (),
156
+ commands: Sequence[Command] = (),
157
+ ) -> None:
158
+ self.domain = domain
159
+ self.version = version
160
+ self.description = description
161
+ self.new_options = new_options
162
+ self.new_fields = new_fields
163
+ self.list_filters = tuple(list_filters)
164
+ self.show_fields = tuple(show_fields)
165
+ unknown = sorted(set(self.list_filters) - set(domain.item_schema))
166
+ if unknown:
167
+ raise ValueError(f"list_filters: not item fields: {', '.join(unknown)}")
168
+ self.commands: dict[str, Command] = {c.name: c for c in _core_commands(self)}
169
+ self.commands.update({c.name: c for c in commands})
170
+ self.handlers: dict[str, Handler] = {name: c.run for name, c in self.commands.items()}
171
+
172
+ @property
173
+ def prog(self) -> str:
174
+ return self.domain.name
175
+
176
+ def command_names(self) -> list[str]:
177
+ return list(self.commands)
178
+
179
+ def needs_identity(self, args: argparse.Namespace) -> bool:
180
+ """Whether a parsed command must run under a pinned role."""
181
+ if args.command_name in CHECK_ONLY:
182
+ return not args.check
183
+ command = self.commands.get(args.command_name)
184
+ return command.writes if command else True
185
+
186
+ def _global_options(self) -> _Parser:
187
+ """Options accepted both before and after the command name."""
188
+ common = _Parser(add_help=False, argument_default=argparse.SUPPRESS)
189
+ common.add_argument("--json", action="store_true", help="one JSON document on stdout")
190
+ common.add_argument(
191
+ "--root",
192
+ metavar="PATH",
193
+ help=f"repository root (default: nearest {self.domain.state_dir}/)",
194
+ )
195
+ common.add_argument("--quiet", action="store_true", help="errors only")
196
+ return common
197
+
198
+ def build_parser(self) -> argparse.ArgumentParser:
199
+ common = self._global_options()
200
+ parser = _Parser(
201
+ prog=self.prog,
202
+ description=self.description,
203
+ epilog="commands:\n" + "\n".join(f" {name}" for name in self.commands),
204
+ formatter_class=argparse.RawDescriptionHelpFormatter,
205
+ parents=[common],
206
+ )
207
+ parser.add_argument("--version", action="version", version=f"{self.prog} {self.version}")
208
+ sub = parser.add_subparsers(dest="command", metavar="COMMAND", required=True)
209
+ groups: dict[str, Any] = {}
210
+ for name, command in self.commands.items():
211
+ head, _, tail = name.partition(" ")
212
+ if tail:
213
+ if head not in groups:
214
+ g = sub.add_parser(head, help=command.group_help, parents=[common])
215
+ groups[head] = g.add_subparsers(
216
+ dest="subcommand", metavar="SUBCOMMAND", required=True
217
+ )
218
+ p = groups[head].add_parser(tail, help=command.help, parents=[common])
219
+ else:
220
+ p = sub.add_parser(name, help=command.help, parents=[common])
221
+ (command.build or _no_args)(p)
222
+ p.set_defaults(command_name=name)
223
+ return parser
224
+
225
+ def run(self, args: argparse.Namespace, out: Output) -> None:
226
+ """Dispatch a parsed command: pin identity first, so a refusal comes before anything."""
227
+ identity = resolve(self.domain) if self.needs_identity(args) else None
228
+ handler = self.handlers.get(args.command_name)
229
+ if handler is None:
230
+ raise ForgeError(
231
+ ExitCode.INTERNAL,
232
+ "not_implemented",
233
+ f"'{args.command_name}' is not implemented in this release",
234
+ )
235
+ handler(Context(self, args, out, identity))
236
+
237
+ def main(self, argv: Sequence[str] | None = None) -> int:
238
+ """Entry point. Returns the process exit code."""
239
+ arguments = list(sys.argv[1:] if argv is None else argv)
240
+ out = Output(prog=self.prog, json_mode="--json" in arguments)
241
+ try:
242
+ args = self.build_parser().parse_args(arguments)
243
+ out = Output(
244
+ prog=self.prog,
245
+ json_mode=getattr(args, "json", False),
246
+ quiet=getattr(args, "quiet", False),
247
+ )
248
+ self.run(args, out)
249
+ except ForgeError as err:
250
+ out.error(err)
251
+ return int(err.code)
252
+ except Exception as exc: # last resort: never show a traceback by default
253
+ if os.environ.get(self.domain.env("DEBUG")) == "1":
254
+ raise
255
+ detail = f"{type(exc).__name__}: {exc}"
256
+ out.error(ForgeError(ExitCode.INTERNAL, "internal_error", detail))
257
+ return int(ExitCode.INTERNAL)
258
+ return int(ExitCode.OK)
259
+
260
+
261
+ # ------------------------------------------------------------------ builders
262
+
263
+
264
+ @dataclass(frozen=True)
265
+ class _Builders:
266
+ """Argument builders that need the app (its domain and hooks)."""
267
+
268
+ app: App
269
+ _types: tuple[str, ...] = field(init=False)
270
+
271
+ def __post_init__(self) -> None:
272
+ object.__setattr__(self, "_types", tuple(t.name for t in self.app.domain.item_types))
273
+
274
+ def init(self, p: argparse.ArgumentParser) -> None:
275
+ p.add_argument("--project", metavar="NAME", help="project name (default: the folder name)")
276
+
277
+ def new(self, p: argparse.ArgumentParser) -> None:
278
+ p.add_argument("type", choices=self._types, help="item type")
279
+ p.add_argument("title", help="short title, 1-80 characters")
280
+ if self.app.new_options:
281
+ self.app.new_options(p)
282
+
283
+ def move(self, p: argparse.ArgumentParser) -> None:
284
+ _id(p)
285
+ p.add_argument("state", metavar="STATE", help="target state")
286
+ p.add_argument("--note")
287
+
288
+ def rename(self, p: argparse.ArgumentParser) -> None:
289
+ _id(p)
290
+ p.add_argument("title", help="new title")
291
+
292
+ def assign(self, p: argparse.ArgumentParser) -> None:
293
+ _id(p)
294
+ p.add_argument("role", help="role name")
295
+ p.add_argument("--task")
296
+
297
+ def list(self, p: argparse.ArgumentParser) -> None:
298
+ p.add_argument("--type", choices=self._types)
299
+ p.add_argument("--state", metavar="STATE")
300
+ for name in self.app.list_filters:
301
+ p.add_argument(f"--{name.replace('_', '-')}", dest=f"where_{name}", metavar="VALUE")
302
+ if self.app.domain.parent_fields:
303
+ p.add_argument("--parent", metavar="ID", help="only the children of this item")
304
+ p.add_argument("--open", action="store_true", help="only items still being worked on")
305
+
306
+ def check(self, p: argparse.ArgumentParser) -> None:
307
+ p.add_argument("--check", action="store_true", help="report only; change nothing")
308
+
309
+ def gate_open(self, p: argparse.ArgumentParser) -> None:
310
+ kinds = tuple(k.name for k in self.app.domain.gate_kinds)
311
+ p.add_argument("kind", choices=kinds, metavar="KIND", help="gate kind")
312
+ p.add_argument("id", nargs="?", metavar="ID", help="item ID; omit for a project gate")
313
+ p.add_argument("--summary", required=True, help="what is being decided, 1-200 characters")
314
+ p.add_argument("--option", action="append", default=[], help="an answer offered")
315
+
316
+ def gate_rule(self, p: argparse.ArgumentParser) -> None:
317
+ _id(p, "gate", "gate ID, e.g. WID-0001:REVIEW:1")
318
+ p.add_argument("ruling", metavar="RULING", help="one of the gate kind's rulings")
319
+ targets = sorted({t for k in self.app.domain.gate_kinds for t in k.revise_targets})
320
+ p.add_argument("--target", choices=targets or None, help="where a revise ruling sends it")
321
+ p.add_argument("--note", help="required by some rulings")
322
+ p.add_argument(
323
+ "--review-by", metavar="YYYY-MM-DD", help="when an accepted risk is reviewed"
324
+ )
325
+ p.add_argument("--party", help="who a risk is shared with or transferred to")
326
+ p.add_argument("--channel", choices=CHANNELS, help="where the ruling was made")
327
+
328
+ def gate_list(self, p: argparse.ArgumentParser) -> None:
329
+ p.add_argument("--open", action="store_true", help="only gates awaiting a ruling")
330
+ p.add_argument("--item", metavar="ID", help="only gates on this item")
331
+
332
+ def finding_add(self, p: argparse.ArgumentParser) -> None:
333
+ _id(p)
334
+ p.add_argument("summary")
335
+ p.add_argument("--severity", choices=self.app.domain.severities, required=True)
336
+ p.add_argument("--rule", metavar="RULE-ID")
337
+ p.add_argument("--at", metavar="PLACE", help="path, path:line, path#anchor or path@mm:ss")
338
+
339
+ def finding_resolve(self, p: argparse.ArgumentParser) -> None:
340
+ _id(p, "finding", "finding ID")
341
+ p.add_argument("--how", choices=RESOLUTIONS, required=True)
342
+
343
+ def insight_add(self, p: argparse.ArgumentParser) -> None:
344
+ p.add_argument("summary")
345
+ p.add_argument("--from", dest="from_item", metavar="ID")
346
+ p.add_argument("--tag", action="append", default=[])
347
+
348
+ def msg_send(self, p: argparse.ArgumentParser) -> None:
349
+ p.add_argument("body", help="the message, at most 8 KiB; put larger content in a file")
350
+ p.add_argument("--from", dest="sender", required=True, metavar="ROLE", help="who said it")
351
+ p.add_argument("--to", required=True, metavar="ROLE", help="who it is for")
352
+ p.add_argument("--kind", choices=MSG_KINDS, required=True)
353
+ p.add_argument("--priority", choices=MSG_PRIORITIES, default="normal")
354
+ p.add_argument("--reply-to", metavar="MSG-ID")
355
+
356
+ def msg_state(self, p: argparse.ArgumentParser) -> None:
357
+ _id(p, "msg", "message ID")
358
+ p.add_argument("state", choices=MSG_STATES)
359
+ p.add_argument("--until", metavar="TIMESTAMP", help="required with snoozed")
360
+
361
+ def backup(self, p: argparse.ArgumentParser) -> None:
362
+ p.add_argument(
363
+ "--to", metavar="DIR", help="folder outside the project (default: backup.dir)"
364
+ )
365
+ p.add_argument(
366
+ "--recipient",
367
+ action="append",
368
+ default=[],
369
+ metavar="KEY",
370
+ help="age or SSH public key that can decrypt it; repeatable "
371
+ "(default: backup.recipients)",
372
+ )
373
+
374
+ def restore(self, p: argparse.ArgumentParser) -> None:
375
+ p.add_argument("archive", metavar="ARCHIVE")
376
+ p.add_argument("--identity", required=True, metavar="FILE", help="age identity file")
377
+
378
+
379
+ def _core_commands(app: App) -> list[Command]:
380
+ b = _Builders(app)
381
+ state = app.domain.state_dir
382
+ commands = [
383
+ Command("init", f"create {state}/ for this repository", _cmd_init, b.init),
384
+ Command("new", "create an item", _cmd_new, b.new),
385
+ Command("move", "move an item to another state", _cmd_move, b.move),
386
+ Command("rename", "rename an item", _cmd_rename, b.rename),
387
+ Command("assign", "assign an item to a role", _cmd_assign, b.assign),
388
+ Command("show", "show an item, its state, gates, findings and history", _cmd_show, _id),
389
+ Command("list", "list items in ID order", _cmd_list, b.list),
390
+ Command("ledger", "regenerate LEDGER.md", _cmd_ledger, b.check),
391
+ Command("reindex", "rebuild the index from the event log", _cmd_reindex),
392
+ Command("archive", "roll up a closed item", _cmd_archive, _id),
393
+ Command("verify", "check the event log's hash chain", _cmd_verify),
394
+ Command("migrate", "upgrade schema versions", _cmd_migrate, b.check),
395
+ Command("backup", f"write an encrypted archive of {state}/", _cmd_backup, b.backup),
396
+ Command("restore", "restore an archive and verify it", _cmd_restore, b.restore),
397
+ Command(
398
+ "gate open",
399
+ "open a gate on an item or the project",
400
+ _cmd_gate_open,
401
+ b.gate_open,
402
+ "open, rule and list gates",
403
+ ),
404
+ Command("gate rule", "rule on a gate (operator only)", _cmd_gate_rule, b.gate_rule),
405
+ Command("gate list", "list gates", _cmd_gate_list, b.gate_list),
406
+ Command(
407
+ "finding add",
408
+ "add a finding to an item",
409
+ _cmd_finding_add,
410
+ b.finding_add,
411
+ "record and resolve findings",
412
+ ),
413
+ Command("finding resolve", "resolve a finding", _cmd_finding_resolve, b.finding_resolve),
414
+ Command("msg send", "send a message", _cmd_msg_send, b.msg_send, "relay messages"),
415
+ Command("msg state", "record a message state change", _cmd_msg_state, b.msg_state),
416
+ Command(
417
+ "insight add", "add an insight", _cmd_insight_add, b.insight_add, "record insights"
418
+ ),
419
+ Command(
420
+ "hook identity",
421
+ "PreToolUse: pin the caller's role",
422
+ _cmd_hook_identity,
423
+ group_help="Claude Code hook entry points (read hook input on stdin)",
424
+ ),
425
+ Command(
426
+ "hook lane-guard", "PreToolUse: deny reads and writes behind a wall", _cmd_hook_lane
427
+ ),
428
+ ]
429
+ return [replace(c, writes=c.name not in NO_IDENTITY) for c in commands]
430
+
431
+
432
+ # ------------------------------------------------------------------ handlers
433
+
434
+
435
+ def _where(items: Items, item: Item) -> str:
436
+ """``ID — title — path``."""
437
+ path = items.file(item).relative_to(items.layout.root)
438
+ return f"{item.label()}{_DASH}{path}"
439
+
440
+
441
+ def _cmd_init(ctx: Context) -> None:
442
+ domain = ctx.domain
443
+ layout = init_project(ctx.root() or Path.cwd(), domain, ctx.args.project)
444
+ repo = (layout.state / ".git").is_dir()
445
+ history = (
446
+ "It is a git repository of its own."
447
+ if repo
448
+ else "WARNING: git was not found, so it has no history; install git and run `git init` "
449
+ f"in {domain.state_dir}/."
450
+ )
451
+ ctx.out.result(
452
+ {"ok": True, "root": str(layout.root), "state": str(layout.state), "git": repo},
453
+ f"Initialized {domain.state_dir}/ in {layout.root}. It is private: "
454
+ f"{domain.state_dir}/ is in .gitignore and is never committed. {history}",
455
+ )
456
+
457
+
458
+ def _cmd_verify(ctx: Context) -> None:
459
+ layout, _ = ctx.layout()
460
+ result = EventStore(layout, ctx.domain).verify()
461
+ if not result.ok:
462
+ raise ForgeError(
463
+ ExitCode.DATA,
464
+ "chain_broken",
465
+ f"{layout.events} line {result.line}: {result.reason} "
466
+ f"({result.events} events before it are intact)",
467
+ )
468
+ noun = "event" if result.events == 1 else "events"
469
+ ctx.out.result(
470
+ {"ok": True, "events": result.events},
471
+ f"Event log intact: {result.events} {noun}, hash chain verified.",
472
+ )
473
+
474
+
475
+ def _cmd_new(ctx: Context) -> None:
476
+ items = ctx.items()
477
+ hook = ctx.app.new_fields
478
+ fields = hook(ctx.args, items, ctx.who()) if hook else {}
479
+ item = items.create(ctx.args.type, ctx.args.title, fields)
480
+ ctx.out.result(item.as_dict(), f"Created {_where(items, item)}")
481
+
482
+
483
+ def _cmd_rename(ctx: Context) -> None:
484
+ item, old = ctx.items().rename(ctx.args.id, ctx.args.title)
485
+ if old == item.title:
486
+ ctx.out.result(item.as_dict(), f"Unchanged: {item.label()}")
487
+ else:
488
+ ctx.out.result(item.as_dict(), f"Renamed {item.label()} (was: {old})")
489
+
490
+
491
+ def _cmd_move(ctx: Context) -> None:
492
+ item, old = ctx.items().move(ctx.args.id, ctx.args.state, ctx.args.note)
493
+ ctx.out.result({**item.as_dict(), "from": old}, f"Moved {item.label()}: {old} → {item.state}")
494
+
495
+
496
+ def _cmd_assign(ctx: Context) -> None:
497
+ item = ctx.items().assign(ctx.args.id, ctx.args.role, ctx.args.task)
498
+ ctx.out.result(item.as_dict(), f"Assigned {item.label()} to {item.assignee}")
499
+
500
+
501
+ def _cmd_archive(ctx: Context) -> None:
502
+ layout, config = ctx.layout()
503
+ done = Archiver(layout, ctx.domain, ctx.who(), config).archive(ctx.args.id)
504
+ rollup = (layout.state / done.item.path).relative_to(layout.root)
505
+ removed = f"{ctx.domain.state_dir}/{done.removed}"
506
+ if done.finished:
507
+ message = f"Finished archiving {done.item.label()}: removed {removed}, kept {rollup}"
508
+ else:
509
+ count = len(done.files)
510
+ noun = "file" if count == 1 else "files"
511
+ message = (
512
+ f"Archived {done.item.label()} ({done.previous_state}) → {rollup}; "
513
+ f"{count} {noun} rolled up, {removed} removed"
514
+ )
515
+ if done.kept:
516
+ beside = f"{ctx.domain.state_dir}/{kept_dir(done.item.id)}/"
517
+ message += f"\nKept beside it in {beside}: {', '.join(done.kept)}"
518
+ ctx.out.result(done.as_dict(), message)
519
+
520
+
521
+ def _gates(ctx: Context) -> Gates:
522
+ layout, config = ctx.layout()
523
+ return Gates(layout, ctx.domain, ctx.identity, config)
524
+
525
+
526
+ def _gate_line(gate: Gate, titles: Mapping[str, str]) -> str:
527
+ """``GATE-ID — summary — on ID — title — status``; desk-only is marked."""
528
+ on = f"{_DASH}on {gate.item}{_DASH}{titles.get(gate.item, '?')}" if gate.item else ""
529
+ desk = " (desk-only)" if gate.desk_only else ""
530
+ return f"{gate.id}{_DASH}{gate.summary}{on}{_DASH}{gate.status()}{desk}"
531
+
532
+
533
+ def _titles(ctx: Context, gates: Gates) -> dict[str, str]:
534
+ return {i.id: i.title for i in Items(gates.layout, ctx.domain).all().values()}
535
+
536
+
537
+ def _cmd_gate_open(ctx: Context) -> None:
538
+ gates = _gates(ctx)
539
+ gate = gates.open(ctx.args.kind, ctx.args.id, ctx.args.summary, ctx.args.option)
540
+ ctx.out.result(gate.as_dict(), f"Opened {_gate_line(gate, _titles(ctx, gates))}")
541
+
542
+
543
+ def _cmd_gate_rule(ctx: Context) -> None:
544
+ gates = _gates(ctx)
545
+ who = ctx.who()
546
+ channel = ctx.args.channel or ("tui" if who.session == "tui" else "console")
547
+ gate = gates.rule(
548
+ ctx.args.gate,
549
+ ctx.args.ruling,
550
+ channel=channel,
551
+ target=ctx.args.target,
552
+ note=ctx.args.note,
553
+ review_by=ctx.args.review_by,
554
+ party=ctx.args.party,
555
+ )
556
+ ctx.out.result(gate.as_dict(), f"Ruled {_gate_line(gate, _titles(ctx, gates))}")
557
+
558
+
559
+ def _cmd_gate_list(ctx: Context) -> None:
560
+ gates = _gates(ctx)
561
+ found = [
562
+ g
563
+ for g in gates.all().values()
564
+ if (not ctx.args.open or g.is_open) and (ctx.args.item is None or g.item == ctx.args.item)
565
+ ]
566
+ titles = _titles(ctx, gates)
567
+ lines = [_gate_line(g, titles) for g in found] or ["No gates."]
568
+ ctx.out.result({"gates": [g.as_dict() for g in found]}, "\n".join(lines))
569
+
570
+
571
+ def _cmd_finding_add(ctx: Context) -> None:
572
+ layout, _ = ctx.layout()
573
+ found = Findings(layout, ctx.domain, ctx.identity).add(
574
+ ctx.args.id, ctx.args.severity, ctx.args.summary, rule=ctx.args.rule, at=ctx.args.at
575
+ )
576
+ where = f" at {found.at}" if found.at else ""
577
+ ctx.out.result(
578
+ found.as_dict(), f"Raised {found.id}{_DASH}{found.severity}{_DASH}{found.summary}{where}"
579
+ )
580
+
581
+
582
+ def _cmd_finding_resolve(ctx: Context) -> None:
583
+ layout, _ = ctx.layout()
584
+ found = Findings(layout, ctx.domain, ctx.identity).resolve(ctx.args.finding, ctx.args.how)
585
+ ctx.out.result(
586
+ found.as_dict(), f"Resolved {found.id}{_DASH}{found.summary}{_DASH}{found.status()}"
587
+ )
588
+
589
+
590
+ def _cmd_insight_add(ctx: Context) -> None:
591
+ layout, _ = ctx.layout()
592
+ insight = Insights(layout, ctx.domain, ctx.identity).add(
593
+ ctx.args.summary, from_item=ctx.args.from_item, tags=ctx.args.tag
594
+ )
595
+ ctx.out.result(insight.as_dict(), f"Recorded {insight.label()}")
596
+
597
+
598
+ def _cmd_msg_send(ctx: Context) -> None:
599
+ layout, config = ctx.layout()
600
+ message = Messages(layout, ctx.domain, ctx.identity, config).send(
601
+ ctx.args.sender,
602
+ ctx.args.to,
603
+ ctx.args.kind,
604
+ ctx.args.body,
605
+ priority=ctx.args.priority,
606
+ reply_to=ctx.args.reply_to,
607
+ )
608
+ ctx.out.result(message.as_dict(), f"Relayed {message.label()}{_DASH}{message.outcome}")
609
+
610
+
611
+ def _cmd_msg_state(ctx: Context) -> None:
612
+ layout, config = ctx.layout()
613
+ message = Messages(layout, ctx.domain, ctx.identity, config).set_state(
614
+ ctx.args.msg, ctx.args.state, until=ctx.args.until
615
+ )
616
+ until = f" until {message.until}" if message.until else ""
617
+ ctx.out.result(message.as_dict(), f"{message.label()}{_DASH}{message.state}{until}")
618
+
619
+
620
+ def _show_insight(ctx: Context, layout: Layout) -> None:
621
+ insight = Insights(layout, ctx.domain).all().get(ctx.args.id)
622
+ if insight is None:
623
+ raise ForgeError(ExitCode.NOT_FOUND, "insight_not_found", f"no insight {ctx.args.id}")
624
+ tags = f" [{', '.join(insight.tags)}]" if insight.tags else ""
625
+ source = f"{_DASH}from {insight.from_item}" if insight.from_item else ""
626
+ ctx.out.result(insight.as_dict(), f"{insight.label()}{tags}{source}")
627
+
628
+
629
+ def _cmd_show(ctx: Context) -> None:
630
+ layout, _ = ctx.layout()
631
+ if ctx.args.id.startswith("INSIGHT-"):
632
+ _show_insight(ctx, layout)
633
+ return
634
+ view = describe_item(list(EventStore(layout, ctx.domain).events()), ctx.domain, ctx.args.id)
635
+ item = view.item
636
+ path = (layout.state / item.path).relative_to(layout.root)
637
+ facts = [item.type, item.state]
638
+ facts += [
639
+ f"{name} {item.fields[name]}" for name in ctx.app.show_fields if item.fields.get(name)
640
+ ]
641
+ if item.assignee:
642
+ facts.append(f"assigned {item.assignee}")
643
+ lines = [f"{item.label()}{_DASH}{path}", " " + " · ".join(facts)]
644
+ sections = (
645
+ ("Gates", [f"{g.id}{_DASH}{g.summary}{_DASH}{g.status()}" for g in view.gates]),
646
+ (
647
+ "Findings",
648
+ [
649
+ f"{f.id}{_DASH}{f.severity}{_DASH}{f.summary}{_DASH}{f.status()}"
650
+ for f in view.findings
651
+ ],
652
+ ),
653
+ ("Insights", [x.label() for x in view.insights]),
654
+ ("Children", [f"{c.id}{_DASH}{c.title}{_DASH}{c.state}" for c in view.children]),
655
+ (
656
+ "History",
657
+ [
658
+ f"{h['ts'][:16].replace('T', ' ')} {h['actor']}: {h['from']} → {h['to']}"
659
+ for h in view.history
660
+ ],
661
+ ),
662
+ )
663
+ for title, rows in sections:
664
+ if rows:
665
+ lines.append(f"{title}:")
666
+ lines.extend(f" {row}" for row in rows)
667
+ ctx.out.result(view.as_dict(), "\n".join(lines))
668
+
669
+
670
+ def _cmd_list(ctx: Context) -> None:
671
+ layout, _ = ctx.layout()
672
+ require_type(ctx.domain, ctx.args.type)
673
+ where = {
674
+ name: value
675
+ for name in ctx.app.list_filters
676
+ if (value := getattr(ctx.args, f"where_{name}", None)) is not None
677
+ }
678
+ found = Index(layout, ctx.domain).items(
679
+ type_name=ctx.args.type,
680
+ state=ctx.args.state,
681
+ where=where,
682
+ parent=getattr(ctx.args, "parent", None),
683
+ open_only=ctx.args.open,
684
+ )
685
+ lines = [_DASH.join((i.id, i.title, i.state, i.type)) for i in found] or ["No items."]
686
+ ctx.out.result({"items": [i.as_dict() for i in found]}, "\n".join(lines))
687
+
688
+
689
+ def _cmd_reindex(ctx: Context) -> None:
690
+ layout, _ = ctx.layout()
691
+ index = Index(layout, ctx.domain)
692
+ repair = index.reindex()
693
+ count = len(index.items())
694
+ lines = [f"Rebuilt the index: {count} items."]
695
+ if repair.states_fixed:
696
+ lines.append(f"Front-matter corrected from the log: {', '.join(repair.states_fixed)}")
697
+ if repair.files_recreated:
698
+ lines.append(f"Item files recreated from the log: {', '.join(repair.files_recreated)}")
699
+ if repair.archives_damaged:
700
+ # A rollup is the only copy of a closed item's files: never rebuilt, always loud.
701
+ raise ForgeError(
702
+ ExitCode.DATA,
703
+ "archive_damaged",
704
+ "missing or not matching the log: "
705
+ + ", ".join(f"{ctx.domain.state_dir}/archive/{i}.md" for i in repair.archives_damaged)
706
+ + "; restore them from a backup",
707
+ )
708
+ doc = {
709
+ "items": count,
710
+ "states_fixed": list(repair.states_fixed),
711
+ "files_recreated": list(repair.files_recreated),
712
+ "archives_damaged": [],
713
+ }
714
+ ctx.out.result(doc, "\n".join(lines))
715
+
716
+
717
+ def _cmd_ledger(ctx: Context) -> None:
718
+ layout, config = ctx.layout()
719
+ domain = ctx.domain
720
+ ledger = Ledger(layout, domain, str(config["project"]))
721
+ events = list(EventStore(layout, domain).events())
722
+ names = [f"{domain.state_dir}/{name}" for name in ledger.paths()]
723
+ if ctx.args.check:
724
+ stale = ledger.stale(events)
725
+ if stale:
726
+ raise ForgeError(
727
+ ExitCode.REFUSED,
728
+ "ledger_stale",
729
+ f"out of date: {', '.join(stale)}; run `{domain.name} ledger`",
730
+ )
731
+ ctx.out.result({"stale": []}, f"Current: {', '.join(names)}")
732
+ return
733
+ changed = ledger.write(events)
734
+ message = f"Wrote {', '.join(changed)}" if changed else f"Already current: {', '.join(names)}"
735
+ ctx.out.result({"changed": changed}, message)
736
+
737
+
738
+ def _cmd_backup(ctx: Context) -> None:
739
+ layout, config = ctx.layout()
740
+ domain = ctx.domain
741
+ settings = config["backup"]
742
+ to = ctx.args.to or settings["dir"]
743
+ if not to:
744
+ raise ForgeError(
745
+ ExitCode.USAGE,
746
+ "no_backup_dir",
747
+ "name a folder outside the project: --to DIR, or backup.dir in config.yaml",
748
+ )
749
+ recipients = ctx.args.recipient or list(settings["recipients"])
750
+ made = Backups(layout, domain, ctx.who()).create(Path(to), recipients, str(config["project"]))
751
+ noun = "recipient" if made.recipients == 1 else "recipients"
752
+ message = (
753
+ f"Backed up {domain.state_dir}/ ({made.events} events, {made.files} files) "
754
+ f"→ {made.path}, encrypted to {made.recipients} {noun}"
755
+ )
756
+ if not made.chain_ok:
757
+ message += f"\nWARNING: the event log's hash chain is broken; run `{domain.name} verify`"
758
+ ctx.out.result(made.as_dict(), message)
759
+
760
+
761
+ def _cmd_restore(ctx: Context) -> None:
762
+ domain = ctx.domain
763
+ layout = Layout.at(ctx.root() or Path.cwd(), domain)
764
+ done = Backups(layout, domain, ctx.who()).restore(
765
+ Path(ctx.args.archive), Path(ctx.args.identity)
766
+ )
767
+ ctx.out.result(
768
+ done.as_dict(),
769
+ f"Restored {domain.state_dir}/ from {done.archive.name} (made {done.created}): "
770
+ f"{done.events} events and {done.files} files verified",
771
+ )
772
+
773
+
774
+ def describe_plan(plan: Plan) -> str:
775
+ """``3 events, 2 item files (WID-0001, WID-0002), config.yaml``."""
776
+ parts = []
777
+ if plan.events:
778
+ parts.append(f"{plan.events} event{'s' if plan.events != 1 else ''}")
779
+ if plan.items:
780
+ ids = ", ".join(i for i, _ in plan.items)
781
+ parts.append(f"{len(plan.items)} item file{'s' if len(plan.items) != 1 else ''} ({ids})")
782
+ if plan.config:
783
+ parts.append("config.yaml")
784
+ parts += [f"{name} (retired)" for name in plan.retired]
785
+ return ", ".join(parts)
786
+
787
+
788
+ def _cmd_migrate(ctx: Context) -> None:
789
+ layout, config = ctx.layout()
790
+ domain = ctx.domain
791
+ migrator = Migrator(layout, domain, ctx.identity, config)
792
+ if ctx.args.check:
793
+ plan = migrator.plan()
794
+ if not plan.empty:
795
+ raise ForgeError(
796
+ ExitCode.REFUSED,
797
+ "migration_needed",
798
+ f"older than this release: {describe_plan(plan)}; "
799
+ f"run `{domain.name} migrate` as the operator",
800
+ )
801
+ ctx.out.result(plan.as_dict(), "Nothing to migrate: every record is current")
802
+ return
803
+ done = migrator.run()
804
+ if done.backup is None:
805
+ ctx.out.result(done.as_dict(), "Nothing to migrate: every record is current")
806
+ return
807
+ ctx.out.result(
808
+ done.as_dict(),
809
+ f"Migrated {describe_plan(done.plan)}. Originals are in {domain.state_dir}/{done.backup}/",
810
+ )
811
+
812
+
813
+ def _cmd_hook_identity(ctx: Context) -> None:
814
+ # Hook output is Claude Code's format, not ours: print it as-is, or nothing.
815
+ response = run_hook(ctx.domain, sys.stdin.read())
816
+ if response:
817
+ sys.stdout.write(response + "\n")
818
+
819
+
820
+ def _cmd_hook_lane(ctx: Context) -> None:
821
+ response = run_hook(ctx.domain, sys.stdin.read(), lane_guard_hook)
822
+ if response:
823
+ sys.stdout.write(response + "\n")