kijito-tools 0.2.1 → 0.2.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kijito-tools",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Installer for kijito-tools: copies the context-tracking, session catch-up, and self-clear scripts plus the Kijito skills into ~/.claude.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "commonjs",
@@ -54,7 +54,11 @@ kijito_stream_for_persona() {
54
54
  done
55
55
  [ -n "$km" ] && safe=$("$km" --safe-persona "$want" 2>/dev/null)
56
56
  if [ -n "$safe" ]; then
57
- for cand in "$HOME/.kijito-monitor/$safe.jsonl" "$HOME/.cache/kijito-inbox-monitor/events.$safe.ndjson"; do
57
+ # THREE layouts: the fleet's systemd units, the launchd plist, and the monitor's own shipped systemd
58
+ # template (~/.local/state, XDG state) - the last one was missing until row M313's follow-up, so a
59
+ # Linux user who installed the unit from the monitor repo had a stream nothing here would find.
60
+ for cand in "$HOME/.kijito-monitor/$safe.jsonl" "$HOME/.cache/kijito-inbox-monitor/events.$safe.ndjson" \
61
+ "$HOME/.local/state/kijito-inbox-monitor/events.$safe.ndjson"; do
58
62
  [ -e "$cand" ] && { printf '%s' "$cand"; return 0; }
59
63
  done
60
64
  fi
@@ -63,7 +67,8 @@ kijito_stream_for_persona() {
63
67
  import glob, json, os, sys
64
68
  want = os.environ["KJ_WANT"].casefold(); home = os.path.expanduser("~"); hits = []
65
69
  for pat in (os.path.join(home, ".kijito-monitor", "*.jsonl"),
66
- os.path.join(home, ".cache", "kijito-inbox-monitor", "events.*.ndjson")):
70
+ os.path.join(home, ".cache", "kijito-inbox-monitor", "events.*.ndjson"),
71
+ os.path.join(home, ".local", "state", "kijito-inbox-monitor", "events.*.ndjson")):
67
72
  for path in glob.glob(pat):
68
73
  try:
69
74
  with open(path, "rb") as fh:
@@ -100,7 +100,8 @@ want = os.environ["KJ_PERSONA"].casefold()
100
100
  home = os.path.expanduser("~")
101
101
  hits = []
102
102
  for pat in (os.path.join(home, ".kijito-monitor", "*.jsonl"),
103
- os.path.join(home, ".cache", "kijito-inbox-monitor", "events.*.ndjson")):
103
+ os.path.join(home, ".cache", "kijito-inbox-monitor", "events.*.ndjson"),
104
+ os.path.join(home, ".local", "state", "kijito-inbox-monitor", "events.*.ndjson")):
104
105
  for path in glob.glob(pat):
105
106
  try:
106
107
  with open(path, "rb") as fh:
@@ -174,6 +175,10 @@ fi
174
175
  # supervisor definition is the next-best evidence. uname is the last resort, not the first test.
175
176
  _mac_events="$HOME/.cache/kijito-inbox-monitor/events.${_safe}.ndjson"
176
177
  _lnx_events="$HOME/.kijito-monitor/${_safe}.jsonl"
178
+ # The monitor repo's OWN shipped systemd template writes here (XDG state). A third layout, and until row
179
+ # M313's follow-up this script did not know it: a user who installed the unit from the monitor README got
180
+ # "nothing is collecting your mail" while their producer was writing mail into this file.
181
+ _tpl_events="$HOME/.local/state/kijito-inbox-monitor/events.${_safe}.ndjson"
177
182
  if [ "$_rule" = by-content ] || [ "$_rule" = stale-stream ]; then
178
183
  # The producer's own output named this file. It outranks every derivation below, because it is the
179
184
  # only one of them that was written by the process we are asking about.
@@ -183,18 +188,21 @@ if [ "$_rule" = by-content ] || [ "$_rule" = stale-stream ]; then
183
188
  # an empty component that looks like a path and names nothing. The producer line says it is stale;
184
189
  # the arming block should still point at the file that will come back when it restarts.
185
190
  _events="$_found"
186
- case "$_events" in *.jsonl) _sup="systemd" ;; *) _sup="launchd" ;; esac
191
+ case "$_events" in *.jsonl|*/.local/state/*) _sup="systemd" ;; *) _sup="launchd" ;; esac
187
192
  elif [ -n "$_safe" ] && [ -e "$_lnx_events" ]; then _events="$_lnx_events"; _sup="systemd"
188
193
  elif [ -n "$_safe" ] && [ -e "$_mac_events" ]; then _events="$_mac_events"; _sup="launchd"
194
+ elif [ -n "$_safe" ] && [ -e "$_tpl_events" ]; then _events="$_tpl_events"; _sup="systemd"
189
195
  elif [ -d "$HOME/.kijito-monitor" ]; then _events="$_lnx_events"; _sup="systemd"
196
+ elif [ -d "$HOME/.local/state/kijito-inbox-monitor" ]; then _events="$_tpl_events"; _sup="systemd"
190
197
  elif [ -d "$HOME/.cache/kijito-inbox-monitor" ]; then _events="$_mac_events"; _sup="launchd"
191
198
  elif [ -f "$HOME/Library/LaunchAgents/com.kijito.inbox-monitor.plist" ]; then _events="$_mac_events"; _sup="launchd"
192
199
  elif [ "$(uname -s 2>/dev/null)" = "Darwin" ]; then _events="$_mac_events"; _sup="launchd"
193
200
  else _events="$_lnx_events"; _sup="systemd"; fi
194
201
  # The generic (no-marker) branch cannot name a file, so it shows the directory shape instead.
195
- case "$_sup" in
196
- launchd) _events_tmpl="\$HOME/.cache/kijito-inbox-monitor/events.<persona>.ndjson" ;;
197
- *) _events_tmpl="\$HOME/.kijito-monitor/<persona>.jsonl" ;;
202
+ case "$_sup:$_events" in
203
+ launchd:*) _events_tmpl="\$HOME/.cache/kijito-inbox-monitor/events.<persona>.ndjson" ;;
204
+ *:*/.local/state/*) _events_tmpl="\$HOME/.local/state/kijito-inbox-monitor/events.<persona>.ndjson" ;;
205
+ *) _events_tmpl="\$HOME/.kijito-monitor/<persona>.jsonl" ;;
198
206
  esac
199
207
 
200
208
  # Producer health, PER PERSONA — because "a producer is running" and "YOUR mail is being collected"
@@ -14,7 +14,7 @@
14
14
  },
15
15
  "artifacts": {
16
16
  "wakeCoreSha256": "5f7b57f71fd7ae96b303195c3671af0d410668b95f6a397c97cbec275992e412",
17
- "workflowSha256": "e411fddb3bd37d4fcf364917572f3c9d132223aa9e1dc0d522efbcae0c8fa73e",
17
+ "workflowSha256": "ec6a65c095e7011c3100c2a804e23c1dee1a63cfba0fb79f1b872aee91dd3b2d",
18
18
  "planSha256": "d9d666b86ac06414f6e6a13a3e3e2115983a1dad44fcfded7eccc51b191fb451",
19
19
  "wakeHelperSha256": "838f6b4462ba037a23a14b6fdb8dc34ee8b8f4a7df258b428832bc092fac3ea4",
20
20
  "wsUdsSha256": "4da13eef89b572fb735e756cb06846a021919dec7f91c6d07989377944cc776c",
@@ -3,6 +3,25 @@
3
3
  All notable changes to kijito-inbox-monitor are documented in this file.
4
4
  The format is based on Keep a Changelog, and this project follows Semantic Versioning.
5
5
 
6
+ ## [0.5.4] - 2026-09-24
7
+
8
+ ### Fixed
9
+ - **The systemd unit no longer decides file names.** `kijito-inbox-monitor@.service.template` spelled
10
+ systemd's `%i` into `--state-file`, `--events-file` and `--token-file`. `%i` is the ESCAPED instance
11
+ name, so for any persona that is not already lowercase ASCII (`Loom`, `name (purpose)`, `Ωmega`) the unit
12
+ named its files differently from the producer and from the launchd plist, and passed the escaped
13
+ string as the persona itself. The unit now passes `--persona %I` (unescaped) and the producer fills in
14
+ every path from `{persona}` with the same rule `--safe-persona` prints. For names that are already
15
+ lowercase ASCII the paths are byte-identical to before, so upgrading moves nothing.
16
+
17
+ ### Added
18
+ - `--state-file-template` and `--token-file-template`, the `{persona}` counterparts of `--state-file` and
19
+ `--token-file`.
20
+ - `scripts/migrate-systemd-unit.sh` migrates a deployed unit: dry run by default, `--apply` to act,
21
+ idempotent, keeps the old unit file, refuses to rewrite until the installed producer supports the new
22
+ flags, and for an instance whose files do move keeps the old event path working (hard link) so a
23
+ running `tail -F` consumer is not cut off.
24
+
6
25
  ## [0.5.3] - 2026-09-24
7
26
 
8
27
  ### Changed
@@ -86,3 +86,13 @@ From here on **never hand-edit `providers/monitor`**:
86
86
  fails on any difference. It runs in the test workflow, in both publish workflows before the package is
87
87
  built, and in npm `prepublishOnly`, so a drifted copy cannot be published.
88
88
  - To move to a new upstream release: `scripts/import-monitor.sh <sha-or-tag>`.
89
+
90
+ ## Re-import 2026-09-24 (row M313) — v0.5.4
91
+
92
+ | role | SHA | tree |
93
+ |---|---|---|
94
+ | imported (tag `v0.5.4`) | see `providers/monitor/UPSTREAM` (`scripts/import-monitor.sh v0.5.4`) | idem |
95
+
96
+ v0.5.4: the shipped systemd unit passes `--persona %I` and the producer names every file
97
+ (`--state-file-template`, `--token-file-template`, `--events-file-template`), plus
98
+ `scripts/migrate-systemd-unit.sh` for deployed units.
@@ -545,6 +545,9 @@ four sat above it. Only the newest page's count answers the question "is there u
545
545
  | `--events-file PATH` | Write NDJSON events to an owned, size-rotated file (survives rotation) instead of stdout. Consumers `tail -F` it. |
546
546
  | `--events-file-template PATH` | Per-persona owned, rotated files, e.g. `events.{persona}.ndjson`; each session consumes its own. Must contain `{persona}`. Mutually exclusive with `--events-file`. |
547
547
  | `--state-file PATH` | Persist and resume cursor/liveness; single-writer locked. Persona targets derive one file per persona. Recommended under a supervisor. |
548
+ | `--state-file-template PATH` | Like `--state-file`, with `{persona}` filled in by the producer (the component `--safe-persona` prints). Use it in a supervisor unit so the unit never spells a persona into a path. |
549
+ | `--token-file-template PATH` | Like `--token-file`, with `{persona}` filled in by the producer for the one `--persona` target. |
550
+ | `--safe-persona NAME` | Print the filename component the producer uses for NAME, then exit. Anything that needs to name a persona's files should ask this rather than re-implement the rule. |
548
551
  | `--wait N` | Long-poll hold (s) requested from the server so new mail wakes the watcher near-instantly at ~the same request rate (default 50; `0` disables). Falls back to interval polling against a server that doesn't support it, and auto-upgrades when it does. |
549
552
  | `--poll-seconds N` | Interval between polls when long-poll is off/unsupported (default 60). |
550
553
  | `--alert-after N` | Consecutive failures before an `alert` (default 3, min 1). A single transient failure is normal. |
@@ -1,25 +1,26 @@
1
1
  # The upstream release providers/monitor is a byte-exact copy of (row M314).
2
2
  # Written by scripts/import-monitor.sh; verified by tests/vendored_monitor_test.sh. Never hand-edit.
3
3
  repo=KijitoAI/kijito-inbox-monitor
4
- sha=803c53da623fa2d9bd97f5a9e75f01a78571ea2e
5
- tree=0c8d80201933589363305f9e2753e7d717f348d8
6
- tag=v0.5.3
4
+ sha=1bdc0ced989bf9c10d4a62fa4140b1cf97b7fa2e
5
+ tree=732bef3a3b72279fb4d1111314a6eb7ecb266097
6
+ tag=v0.5.4
7
7
  file=100644 8d88ccb0fd09b9144505f985b4f882db278fac1f .github/workflows/publish-npm.yml
8
8
  file=100644 19ce3471a2cffa689be9d261049c1e74e3e7a25e .github/workflows/publish-pypi.yml
9
9
  file=100644 4534290a5dd36d18d07a782b784b6b0ad5ee38fc .gitignore
10
- file=100644 5f0a605641efd19a9afa8d0cb0d8bed3f908e232 CHANGELOG.md
10
+ file=100644 6191d5c9b75c3d5198168a6422c854cd56e0426e CHANGELOG.md
11
11
  file=100644 d645695673349e3947e8e5ae42332d0ac3164cd7 LICENSE
12
12
  file=100644 f6b0e5634f3fd4156c1c000efb31578bfb068cf3 NOTICE
13
- file=100644 48038bef573e123fe4657be8a5fdb3e0293b192a README.md
13
+ file=100644 86f816d7ac9ef4a5a7242376d642f59be8554e2b README.md
14
14
  file=100644 72f0c148f1e721ac1bb4a38e5cae690355774314 RELEASING.md
15
15
  file=100755 fca1203267cb726736b0c8f239e2d74c40a7a895 arm-hive-monitor.sh
16
16
  file=100755 bbe3f07de13dab8a8a7a4798481156ae4a46ab8f bin/cli.js
17
17
  file=100644 23e088613c314bf86b384640639b545de60ea9d0 com.kijito.inbox-monitor.plist.template
18
18
  file=100644 0ec3f23c29bb26d2890b9083d1014840a48cd2c3 docs/DESIGN.md
19
- file=100644 e6d72708b425b6dfaf02e126aaac7633d3584847 kijito-inbox-monitor@.service.template
20
- file=100644 9a1114ef2ab83cbe3b30bfa50833f3e280e2d91d kijito_inbox_monitor.py
21
- file=100644 a20200e3aeef01e7a19ce8833f1eea743b53949c package.json
22
- file=100644 1af00c40f8351d0a12b8563e7c7e865c6be0299d pyproject.toml
19
+ file=100644 4f5e53a8633e60e6c57c451e28546f8af8783fe8 kijito-inbox-monitor@.service.template
20
+ file=100644 8ad5159d6659a05c33756abc901f7cf4dcd5c9c7 kijito_inbox_monitor.py
21
+ file=100644 4f1d402533247b1453d3b670c9dc746d3941a576 package.json
22
+ file=100644 bc6f7c99e94c83fc89c5ceb1b1c2bfebf203e015 pyproject.toml
23
+ file=100755 b34a5c775385ecfaefd4b374c1fc1aa082a85d14 scripts/migrate-systemd-unit.sh
23
24
  file=100755 22acef6d6875395a81c701eb535030d0a78b0df1 scripts/mutation-check.py
24
25
  file=100755 acba6196213736922fc4f7135749386d85d172a6 scripts/prepublish-gate.sh
25
- file=100644 d54d220ab8b228e557b64cc1497509c46c70a5ee test_kijito_monitor.py
26
+ file=100644 f7272d96cd1b3b0235aa79debbb6568a67063d6e test_kijito_monitor.py
@@ -10,12 +10,15 @@
10
10
  # ~/.config/systemd/user/kijito-inbox-monitor@.service
11
11
  # systemctl --user daemon-reload
12
12
  # run: systemctl --user enable --now kijito-inbox-monitor@YOURPERSONA
13
+ # (a persona with spaces, parentheses or non-ASCII: escape it for systemd -
14
+ # systemctl --user enable --now "kijito-inbox-monitor@$(systemd-escape 'Name (dev)').service")
13
15
  # check: systemctl --user status kijito-inbox-monitor@YOURPERSONA
14
16
  # logs: journalctl --user -u kijito-inbox-monitor@YOURPERSONA -f
15
17
  #
16
- # BEFORE IT WILL START, create the token file for that persona (0600):
17
- # install -m600 /dev/null ~/.config/kijito-inbox-monitor/token.YOURPERSONA
18
- # printf '%s' "$YOUR_KIJITO_API_TOKEN" > ~/.config/kijito-inbox-monitor/token.YOURPERSONA
18
+ # BEFORE IT WILL START, create the token file for that persona (0600). Its name uses the
19
+ # producer's filename component for the persona, which you get from the producer itself:
20
+ # f=~/.config/kijito-inbox-monitor/token.$(kijito-inbox-monitor --safe-persona YOURPERSONA)
21
+ # install -m600 /dev/null "$f"; printf '%s' "$YOUR_KIJITO_API_TOKEN" > "$f"
19
22
  # A missing token is FATAL and says so - the producer will not start half-configured.
20
23
  #
21
24
  # ⚠️ THIS CAPTURES; IT DOES NOT WAKE. The unit appends one JSON event per new message
@@ -41,7 +44,7 @@
41
44
  # different claims, and so are an ENABLED unit and a unit that survives your logout.
42
45
 
43
46
  [Unit]
44
- Description=Kijito inbox monitor (persona: %i)
47
+ Description=Kijito inbox monitor (persona: %I)
45
48
  Documentation=https://github.com/KijitoAI/kijito-inbox-monitor
46
49
  # Start after the network is genuinely up, not merely configured: the producer's first
47
50
  # act is an HTTPS poll, and a DNS failure at boot is an avoidable alert.
@@ -60,13 +63,19 @@ Type=simple
60
63
  # that skip is at least ANNOUNCED as a `baseline_skipped` diagnostic instead of
61
64
  # happening in silence - but announced-and-skipped is still skipped.)
62
65
  # ⇒ state lives under ~/.local/state (XDG_STATE_HOME: persists between restarts).
66
+ # ⛔ THE UNIT NEVER SPELLS A PERSONA INTO A PATH (row M313). It passes the persona (%I, the
67
+ # UNESCAPED instance name - %i is systemd's escaped form, so 'Name (dev)' would arrive as
68
+ # 'Name\x20\x28dev\x29' and watch a persona that does not exist), and every file name is
69
+ # filled in by the producer from `{persona}` using the SAME rule `--safe-persona` prints and
70
+ # the launchd plist uses. For a name that is already a safe component (lowercase ASCII),
71
+ # the paths are byte-identical to the older %i form, so upgrading moves nothing.
63
72
  ExecStart=%h/.local/bin/kijito-inbox-monitor \
64
- --persona %i \
65
- --token-file %h/.config/kijito-inbox-monitor/token.%i \
73
+ --persona %I \
74
+ --token-file-template %h/.config/kijito-inbox-monitor/token.{persona} \
66
75
  --poll-seconds 30 \
67
76
  --wait 60 \
68
- --state-file %h/.local/state/kijito-inbox-monitor/%i.state \
69
- --events-file %h/.local/state/kijito-inbox-monitor/events.%i.ndjson \
77
+ --state-file-template %h/.local/state/kijito-inbox-monitor/{persona}.state \
78
+ --events-file-template %h/.local/state/kijito-inbox-monitor/events.{persona}.ndjson \
70
79
  --no-content \
71
80
  --heartbeat 900
72
81
 
@@ -33,7 +33,7 @@ try:
33
33
  except ImportError: # pragma: no cover - Windows
34
34
  fcntl = None
35
35
 
36
- __version__ = "0.5.3"
36
+ __version__ = "0.5.4"
37
37
  SOURCE = "kijito-inbox"
38
38
  # A named User-Agent is REQUIRED: api.kijito.ai is fronted by a WAF that 403s the default Python-urllib UA.
39
39
  USER_AGENT = "kijito-inbox-monitor/%s" % __version__
@@ -1841,6 +1841,17 @@ def make_opener_for(url):
1841
1841
  return build_opener(pinned)
1842
1842
 
1843
1843
 
1844
+ def _persona_path(template, persona):
1845
+ """Fill a `{persona}` path template with the producer's OWN filename component for PERSONA (row M313).
1846
+
1847
+ Every per-persona path a supervisor needs - events, state, token - goes through here, so the unit file
1848
+ (systemd `%i`, a plist, a shell script) never spells a filename itself. `%i` is systemd's ESCAPED
1849
+ instance name and passes a persona's raw case through, so a unit that interpolated it disagreed with
1850
+ the producer for any name that is not already a safe component ('Loom', 'name (purpose)', 'Ωmega').
1851
+ """
1852
+ return template.replace("{persona}", _state_safe_persona(persona))
1853
+
1854
+
1844
1855
  def _state_path_for_persona(base_path, persona):
1845
1856
  if not base_path or not persona:
1846
1857
  return base_path
@@ -1991,7 +2002,8 @@ class WatchTarget:
1991
2002
  cp = urllib.parse.urlsplit(url)
1992
2003
  self.unread_persona = dict(urllib.parse.parse_qsl(cp.query)).get("persona") or persona
1993
2004
 
1994
- state_path = _state_path_for_persona(args.state_file, persona)
2005
+ state_path = (_persona_path(args.state_file_template, persona) if args.state_file_template
2006
+ else _state_path_for_persona(args.state_file, persona))
1995
2007
  if state_path:
1996
2008
  self.state_file = StateFile(state_path, self.identity)
1997
2009
  if not args.self_test:
@@ -3606,6 +3618,11 @@ def build_parser():
3606
3618
  p.add_argument("--state-file",
3607
3619
  help="Persist+resume cursor/FSM; single-writer locked. Kijito persona targets derive one "
3608
3620
  "file per persona from this base path. Recommended w/ a supervisor.")
3621
+ p.add_argument("--state-file-template",
3622
+ help="Per-persona state file named by the PRODUCER, e.g. ~/.local/state/kijito-inbox-monitor/"
3623
+ "{persona}.state; '{persona}' is replaced by the same filename component --safe-persona "
3624
+ "prints. Use it in a supervisor unit instead of spelling the persona into --state-file "
3625
+ "(row M313). Mutually exclusive with --state-file.")
3609
3626
  p.add_argument("--heartbeat", type=int, help="Emit a heartbeat event every N seconds (external dead-man's-switch).")
3610
3627
  p.add_argument("--activity-file",
3611
3628
  help="Publish who AUTHORED mail most recently, as JSON, refreshed each tick. Lets a "
@@ -3632,6 +3649,10 @@ def build_parser():
3632
3649
  "(reported verbatim, so a reader can judge magnitude). Default 1.")
3633
3650
  p.add_argument("--auth-header", help="Header NAME for the token (default Authorization: Bearer).")
3634
3651
  p.add_argument("--token-file", help="File holding the auth token (wins over $KIJITOMON_TOKEN).")
3652
+ p.add_argument("--token-file-template",
3653
+ help="Like --token-file, with '{persona}' replaced by the producer's filename component for the "
3654
+ "ONE --persona target (row M313), e.g. ~/.config/kijito-inbox-monitor/token.{persona}. "
3655
+ "Mutually exclusive with --token-file.")
3635
3656
  p.add_argument("--no-fast-path", action="store_true",
3636
3657
  help="Disable the /api/notify/pending unread pre-check; always full-poll the inbox list.")
3637
3658
  p.add_argument("--resync-every", type=int, default=10,
@@ -3673,6 +3694,19 @@ def validate_args(args):
3673
3694
  raise FatalConfig("--events-file-template must contain the '{persona}' placeholder")
3674
3695
  if (args.events_file or args.events_file_template) and args.emit != "stdout-jsonl":
3675
3696
  sys.stderr.write("kijito-inbox-monitor: WARNING --events-file/-template ignored (emit mode is %s)\n" % args.emit)
3697
+ # Row M313: the persona-named paths come from the producer's rule, never from the supervisor.
3698
+ if args.state_file and args.state_file_template:
3699
+ raise FatalConfig("--state-file and --state-file-template are mutually exclusive")
3700
+ if args.state_file_template and "{persona}" not in args.state_file_template:
3701
+ raise FatalConfig("--state-file-template must contain the '{persona}' placeholder")
3702
+ if args.token_file and args.token_file_template:
3703
+ raise FatalConfig("--token-file and --token-file-template are mutually exclusive")
3704
+ if args.token_file_template:
3705
+ if "{persona}" not in args.token_file_template:
3706
+ raise FatalConfig("--token-file-template must contain the '{persona}' placeholder")
3707
+ if len(args.persona or []) != 1 or args.personas or args.all_personas:
3708
+ raise FatalConfig("--token-file-template needs exactly one --persona target (one token file per unit)")
3709
+ args.token_file = _persona_path(args.token_file_template, args.persona[0])
3676
3710
  if args.seed_at is not None:
3677
3711
  single = len(args.persona or []) == 1 and not args.personas and not args.all_personas
3678
3712
  if not single:
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kijito-inbox-monitor",
3
- "version": "0.5.3",
3
+ "version": "0.5.4",
4
4
  "description": "Pointer to the Python package kijito-inbox-monitor. A zero-dependency watcher that wakes a running agent when new Kijito inbox mail arrives. Install the real tool with pipx/uv/pip.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "commonjs",
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "kijito-inbox-monitor"
10
- version = "0.5.3"
10
+ version = "0.5.4"
11
11
  description = "Zero-dependency watcher that wakes a running agent when new Kijito inbox mail arrives."
12
12
  readme = "README.md"
13
13
  requires-python = ">=3.9"
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env bash
2
+ # Migrate a DEPLOYED kijito-inbox-monitor systemd user unit to producer-derived file names (row M313).
3
+ #
4
+ # scripts/migrate-systemd-unit.sh # DRY RUN: says what it would change, changes nothing
5
+ # scripts/migrate-systemd-unit.sh --apply # do it
6
+ # options: --unit NAME (default kijito-inbox-monitor) --bin PATH (default ~/.local/bin/kijito-inbox-monitor)
7
+ # --unit-dir DIR (default ~/.config/systemd/user)
8
+ #
9
+ # WHAT CHANGES. Older units spelled the persona into paths with systemd's `%i` - the ESCAPED instance name -
10
+ # so the unit, not the producer, decided file names, and a persona like 'Loom' or 'name (purpose)' got a
11
+ # different file than the producer (and the launchd plist) would give it. The rewritten unit passes
12
+ # `--persona %I` and turns every `--state-file/--events-file/--token-file ...%i...` into the matching
13
+ # `-template ...{persona}...` flag, so the producer names every file with the rule `--safe-persona` prints.
14
+ #
15
+ # WHAT MOVES. For a persona that is already a safe component (lowercase ASCII - every persona on a normal
16
+ # fleet) the new paths are BYTE-IDENTICAL to the old ones: nothing moves and no consumer has to re-arm.
17
+ # Only an instance whose old and new paths differ is touched, and then (instance stopped first):
18
+ # state copied to the new name (the old file is kept) - the cursor survives
19
+ # token copied to the new name, mode kept (the old file is kept)
20
+ # events HARD-LINKED under the new name - the old name is never removed, so a consumer running
21
+ # `tail -F <old path>` notices nothing and keeps receiving every event the producer now appends
22
+ # under the new name (same file). It stays that way until the producer next ROTATES the stream
23
+ # (default 5 MB), after which only the new name moves on: re-arm consumers on the new path.
24
+ # (Measured, GNU tail 9.4: a SYMLINK at the old path is refused as "untailable", and a rename
25
+ # followed by a relink makes tail re-read the whole file - a replay of every old event.)
26
+ #
27
+ # SAFE TO RE-RUN. A unit with no `%i` left in ExecStart is reported as already migrated; files are only
28
+ # copied/moved when the new one does not exist yet. The old unit file is kept as <unit>.pre-m313.<time>.
29
+ # REFUSES to rewrite the unit while the installed producer lacks --state-file-template (it would not start).
30
+ # ANNOUNCE TO YOUR FLEET BEFORE --apply on a shared seat: instances restart, for a few seconds each.
31
+ set -eu
32
+ UNIT=kijito-inbox-monitor
33
+ BIN="$HOME/.local/bin/kijito-inbox-monitor"
34
+ UNIT_DIR="$HOME/.config/systemd/user"
35
+ APPLY=0
36
+ while [ $# -gt 0 ]; do
37
+ case "$1" in
38
+ --apply) APPLY=1; shift ;;
39
+ --unit) UNIT=$2; shift 2 ;;
40
+ --bin) BIN=$2; shift 2 ;;
41
+ --unit-dir) UNIT_DIR=$2; shift 2 ;;
42
+ -h|--help) sed -n '2,30p' "$0"; exit 0 ;;
43
+ *) echo "unknown option: $1" >&2; exit 2 ;;
44
+ esac
45
+ done
46
+ FILE="$UNIT_DIR/$UNIT@.service"
47
+ [ -f "$FILE" ] || { echo "no unit file at $FILE - nothing to migrate"; exit 0; }
48
+ say() { printf '%s\n' "$*"; }
49
+ [ "$APPLY" = 1 ] && say "== APPLY: $FILE ==" || say "== DRY RUN (pass --apply to act): $FILE =="
50
+
51
+ # The rewrite, as a pure text transform of the unit file (also used to compute the new paths).
52
+ rewrite() {
53
+ sed -E \
54
+ -e '/^ExecStart=/,/[^\\]$/ s/--persona %i/--persona %I/' \
55
+ -e '/^ExecStart=/,/[^\\]$/ s/--(state-file|events-file|token-file)([ =])([^ ]*)%i([^ ]*)/--\1-template\2\3{persona}\4/g' \
56
+ -e 's/^(Description=.*)%i/\1%I/' "$1"
57
+ }
58
+ exec_line() { tr -d '\r' < "$1" | sed -e ':a' -e '/\\$/N; s/\\\n//; ta' | grep '^ExecStart='; }
59
+ flag_value() { printf '%s\n' "$1" | tr ' ' '\n' | awk -v f="$2" 'p{print; exit} $0==f{p=1}'; }
60
+
61
+ old_exec=$(exec_line "$FILE")
62
+ case "$old_exec" in
63
+ *%i*) ;;
64
+ *) say "already migrated: ExecStart spells no %i (the producer names every file)"; exit 0 ;;
65
+ esac
66
+ tmp_unit=$(mktemp); trap 'rm -f "$tmp_unit"' EXIT
67
+ rewrite "$FILE" > "$tmp_unit"
68
+ new_exec=$(exec_line "$tmp_unit")
69
+ case "$new_exec" in *%i*) say "REFUSING: could not rewrite every %i in ExecStart:"; say " $new_exec"; exit 1 ;; esac
70
+ say "ExecStart now: ${old_exec#ExecStart=}"
71
+ say "ExecStart after: ${new_exec#ExecStart=}"
72
+
73
+ have_flags=0
74
+ "$BIN" --help 2>/dev/null | grep -q -- '--state-file-template' && have_flags=1
75
+ if [ "$have_flags" = 0 ]; then
76
+ say "REFUSING to rewrite: $BIN does not support --state-file-template (needs kijito-inbox-monitor >= 0.5.4)."
77
+ say "Upgrade the producer first, then re-run. (For persona names that are already lowercase ASCII the"
78
+ say "old unit is correct as it is: this migration changes no file for them.)"
79
+ [ "$APPLY" = 1 ] && exit 1
80
+ fi
81
+
82
+ H=$HOME
83
+ changed=(); to_start=()
84
+ # Every instance: loaded ones, plus enabled ones that are not loaded right now (a stopped template
85
+ # instance drops out of list-units, and its files must migrate too).
86
+ instances=$( { systemctl --user list-units --all --plain --no-legend "$UNIT@*.service" 2>/dev/null | awk '{print $1}'
87
+ for w in "$UNIT_DIR"/*.wants/"$UNIT"@*.service; do [ -e "$w" ] || [ -L "$w" ] && basename "$w"; done
88
+ } | sort -u)
89
+ while IFS= read -r inst; do
90
+ [ -n "$inst" ] || continue
91
+ esc=${inst#"$UNIT@"}; esc=${esc%.service}
92
+ raw=$(systemd-escape --unescape -- "$esc")
93
+ if [ "$have_flags" = 1 ]; then
94
+ safe=$("$BIN" --safe-persona "$raw")
95
+ else
96
+ # Without an upgraded producer there is no --safe-persona to ask, and this script must not guess the
97
+ # rule (row M290). A name that is already lowercase [a-z0-9._-] is its own component; say so for it,
98
+ # and say plainly that anything else cannot be judged yet.
99
+ case "$raw" in
100
+ *[!a-z0-9._-]*) say " $raw: cannot tell yet which files would move - needs the upgraded producer's --safe-persona"; continue ;;
101
+ esac
102
+ safe=$raw
103
+ fi
104
+ moves=""
105
+ for f in --state-file --events-file --token-file; do
106
+ o=$(flag_value "${old_exec#ExecStart=}" "$f"); [ -n "$o" ] || continue
107
+ case "$o" in *%i*) ;; *) continue ;; esac
108
+ # Parameter expansion, NOT sed: an escaped instance name carries backslashes ('name\x20\x28dev\x29')
109
+ # and GNU sed would decode them in a replacement - the old path would then name a file that never
110
+ # existed. (Caught by this script's own test against real systemd.)
111
+ op=${o//%h/$H}; op=${op//%i/$esc}
112
+ np=${o//%h/$H}; np=${np//%i/$safe}
113
+ [ "$op" = "$np" ] || moves="$moves$f|$op|$np"$'\n'
114
+ done
115
+ if [ -z "$moves" ]; then
116
+ say " $raw: paths unchanged (already a safe component) - nothing moves, consumers need not re-arm"
117
+ continue
118
+ fi
119
+ changed+=("$inst")
120
+ while IFS='|' read -r f op np; do
121
+ [ -n "$f" ] && say " $raw: ${f#--} $op -> $np"
122
+ done <<EOF
123
+ $moves
124
+ EOF
125
+ [ "$APPLY" = 1 ] && [ "$have_flags" = 1 ] || continue
126
+ was_active=0; systemctl --user is-active --quiet "$inst" && was_active=1
127
+ systemctl --user stop "$inst"
128
+ while IFS='|' read -r f op np; do
129
+ [ -n "$f" ] && [ -e "$op" ] || continue
130
+ [ -e "$np" ] && { say " ${f#--}: $np already exists - left as is"; continue; }
131
+ mkdir -p "$(dirname "$np")"
132
+ case "$f" in
133
+ --events-file) ln "$op" "$np" && say " events: $np hard-linked to the live stream; $op still works until the next rotation" ;;
134
+ *) cp -p "$op" "$np" && say " ${f#--} copied (old file kept)" ;;
135
+ esac
136
+ done <<EOF
137
+ $moves
138
+ EOF
139
+ [ "$was_active" = 1 ] && to_start+=("$inst")
140
+ done <<EOF
141
+ $instances
142
+ EOF
143
+
144
+ [ "$APPLY" = 1 ] || { say "(dry run: nothing changed)"; exit 0; }
145
+ cp -p "$FILE" "$FILE.pre-m313.$(date +%Y%m%dT%H%M%S)"
146
+ cp "$tmp_unit" "$FILE"
147
+ systemctl --user daemon-reload
148
+ # The instances this script stopped are started again BY NAME (they are no longer listed once stopped);
149
+ # every other running instance is restarted so it picks up the rewritten ExecStart (same paths).
150
+ for inst in "${to_start[@]+"${to_start[@]}"}"; do systemctl --user start "$inst"; done
151
+ while IFS= read -r inst; do
152
+ [ -n "$inst" ] || continue
153
+ case " ${to_start[*]+"${to_start[*]}"} " in *" $inst "*) continue ;; esac
154
+ systemctl --user is-active --quiet "$inst" && systemctl --user restart "$inst"
155
+ done <<EOF
156
+ $instances
157
+ EOF
158
+ say "migrated: unit rewritten (old copy kept next to it); ${#changed[@]} instance(s) had files moved"
@@ -1,6 +1,7 @@
1
1
  import io
2
2
  import json
3
3
  import os
4
+ import re
4
5
  import subprocess
5
6
  import sys
6
7
  import tempfile
@@ -1715,6 +1716,7 @@ class BoundedWindowEndToEndTest(unittest.TestCase):
1715
1716
  class FullArgs:
1716
1717
  persona = personas = None
1717
1718
  all_personas = False
1719
+ state_file_template = None
1718
1720
  alert_after = 3
1719
1721
  poll_seconds = 60
1720
1722
  heartbeat = 0
@@ -5850,3 +5852,146 @@ class OpaqueOutputEnforcementTest(unittest.TestCase):
5850
5852
  def test_systemd_template_enforces_no_content(self):
5851
5853
  with open(os.path.join(self._HERE, "kijito-inbox-monitor@.service.template"), encoding="utf-8") as fh:
5852
5854
  self.assertIn("--no-content", fh.read())
5855
+
5856
+
5857
+ class SupervisorPersonaPathParityTest(unittest.TestCase):
5858
+ """Row M313. The systemd unit used to interpolate `%i` - systemd's ESCAPED instance name - into
5859
+ --state-file / --events-file / --token-file, so the UNIT decided the file names and disagreed with the
5860
+ producer (and with the launchd plist) for any persona that is not already a safe component. Now the
5861
+ unit passes the persona (%I, unescaped) and the producer fills every `{persona}` path from its own
5862
+ rule. These tests expand BOTH shipped templates the way their supervisors do and require every
5863
+ persona-named file to carry exactly the component `--safe-persona` prints."""
5864
+
5865
+ NAMES = ["argus", "Loom", "name (purpose)", "\u03a9mega", "two words", "Claude-chat"]
5866
+ HOME = "/HOMEDIR"
5867
+ _HERE = os.path.dirname(os.path.abspath(__file__))
5868
+
5869
+ def _systemd_argv_home(self, persona, home):
5870
+ saved, self.HOME = self.HOME, home
5871
+ try:
5872
+ return self._systemd_argv(persona)
5873
+ finally:
5874
+ self.HOME = saved
5875
+
5876
+ def _systemd_argv(self, persona):
5877
+ with open(os.path.join(self._HERE, "kijito-inbox-monitor@.service.template"), encoding="utf-8") as fh:
5878
+ text = fh.read().replace("\\\n", " ")
5879
+ line = next(l for l in text.splitlines() if l.startswith("ExecStart="))
5880
+ self.assertNotIn("%i", line, "the unit must not spell the escaped instance name into ExecStart")
5881
+ # systemd's own expansion: %h = home, %I = the UNESCAPED instance name (measured on systemd 255:
5882
+ # an instance escaped by systemd-escape expands %i to 'Name\\x20...' and %I to 'Name ...').
5883
+ # It is ONE argv word even with spaces in it - systemd splits the line before substituting.
5884
+ words = line[len("ExecStart="):].split()
5885
+ return [w.replace("%h", self.HOME).replace("%I", persona) for w in words][1:]
5886
+
5887
+ def _launchd_events_template(self):
5888
+ with open(os.path.join(self._HERE, "com.kijito.inbox-monitor.plist.template"), encoding="utf-8") as fh:
5889
+ strings = re.findall(r"<string>([^<]*)</string>", fh.read())
5890
+ return strings[strings.index("--events-file-template") + 1].replace("__HOME__", self.HOME)
5891
+
5892
+ def test_every_persona_named_file_uses_the_producers_component_on_both_supervisors(self):
5893
+ for name in self.NAMES:
5894
+ with self.subTest(persona=name):
5895
+ safe = km._state_safe_persona(name)
5896
+ args = km.build_parser().parse_args(self._systemd_argv(name))
5897
+ km.validate_args(args)
5898
+ self.assertEqual(args.persona, [name], "the unit must hand the producer the REAL persona")
5899
+ events = km._persona_path(args.events_file_template, name)
5900
+ state = km._persona_path(args.state_file_template, name)
5901
+ self.assertEqual(os.path.basename(events), "events.%s.ndjson" % safe)
5902
+ self.assertEqual(os.path.basename(state), "%s.state" % safe)
5903
+ self.assertEqual(os.path.basename(args.token_file), "token.%s" % safe)
5904
+ launchd = km._persona_path(self._launchd_events_template(), name)
5905
+ self.assertEqual(os.path.basename(events), os.path.basename(launchd),
5906
+ "launchd and systemd must name a persona's event stream identically")
5907
+
5908
+ def test_upgrading_a_safe_named_unit_moves_nothing(self):
5909
+ # Every persona on a real fleet today is lowercase ASCII; for those the new unit resolves to the
5910
+ # SAME paths the %i form did, so an upgrade needs no migration and no consumer re-arm.
5911
+ args = km.build_parser().parse_args(self._systemd_argv("argus"))
5912
+ km.validate_args(args)
5913
+ base = self.HOME + "/.local/state/kijito-inbox-monitor/"
5914
+ self.assertEqual(km._persona_path(args.events_file_template, "argus"), base + "events.argus.ndjson")
5915
+ self.assertEqual(km._persona_path(args.state_file_template, "argus"), base + "argus.state")
5916
+ self.assertEqual(args.token_file, self.HOME + "/.config/kijito-inbox-monitor/token.argus")
5917
+
5918
+ def test_the_state_file_template_reaches_the_watch_target(self):
5919
+ d = tempfile.mkdtemp()
5920
+
5921
+ class A(BoundedWindowEndToEndTest.FullArgs):
5922
+ state_file = None
5923
+ state_file_template = os.path.join(d, "{persona}.state")
5924
+ seed_at = None
5925
+ t = km.WatchTarget("Loom", "http://x/api/inbox?persona=Loom", None, {}, A(),
5926
+ BoundedWindowEndToEndTest.RecordingEmitter())
5927
+ self.addCleanup(t.state_file.unlock)
5928
+ self.assertEqual(t.state_file.path, os.path.join(d, "loom.state"))
5929
+
5930
+ def test_template_flags_are_validated(self):
5931
+ def err(argv):
5932
+ try:
5933
+ km.validate_args(km.build_parser().parse_args(argv))
5934
+ except km.FatalConfig as e:
5935
+ return str(e)
5936
+ return None
5937
+ self.assertIn("mutually exclusive", err(["--persona", "a", "--state-file", "x", "--state-file-template", "{persona}"]))
5938
+ self.assertIn("placeholder", err(["--persona", "a", "--state-file-template", "x.state"]))
5939
+ self.assertIn("mutually exclusive", err(["--persona", "a", "--token-file", "x", "--token-file-template", "t.{persona}"]))
5940
+ self.assertIn("placeholder", err(["--persona", "a", "--token-file-template", "tok"]))
5941
+ self.assertIn("exactly one --persona", err(["--persona", "a", "--persona", "b", "--token-file-template", "t.{persona}"]))
5942
+ self.assertIsNone(err(["--persona", "A b", "--token-file-template", "/t.{persona}"]))
5943
+
5944
+
5945
+ class SystemdUnitMigrationRewriteTest(unittest.TestCase):
5946
+ """Row M313: scripts/migrate-systemd-unit.sh rewrites a DEPLOYED pre-M313 unit into the producer-named
5947
+ form. Its end-to-end behaviour (files moved, stopped instances restarted, an old-path `tail -F` kept
5948
+ alive) was proven against real systemd when it was written; this pins the REWRITE, which is the part
5949
+ that must stay right on every machine, by running the script's dry run on the pre-M313 unit text."""
5950
+
5951
+ OLD = ("[Unit]\nDescription=Kijito inbox monitor (persona: %i)\n[Service]\n"
5952
+ "ExecStart=%h/.local/bin/kijito-inbox-monitor \\\n --persona %i \\\n"
5953
+ " --token-file %h/.config/kijito-inbox-monitor/token.%i \\\n --poll-seconds 30 \\\n"
5954
+ " --state-file %h/.local/state/kijito-inbox-monitor/%i.state \\\n"
5955
+ " --events-file %h/.local/state/kijito-inbox-monitor/events.%i.ndjson \\\n --heartbeat 900\n")
5956
+
5957
+ def _run(self, unit_text):
5958
+ d = tempfile.mkdtemp()
5959
+ with open(os.path.join(d, "kjt-m313-rewrite-test@.service"), "w") as fh:
5960
+ fh.write(unit_text)
5961
+ here = os.path.dirname(os.path.abspath(__file__))
5962
+ return subprocess.run(["bash", os.path.join(here, "scripts", "migrate-systemd-unit.sh"),
5963
+ "--unit", "kjt-m313-rewrite-test", "--unit-dir", d, "--bin", "/nonexistent"],
5964
+ capture_output=True, text=True)
5965
+
5966
+ def test_every_percent_i_path_becomes_a_producer_template(self):
5967
+ r = self._run(self.OLD)
5968
+ after = next(l for l in r.stdout.splitlines() if l.startswith("ExecStart after:"))
5969
+ self.assertNotIn("%i", after)
5970
+ self.assertIn("--persona %I", after)
5971
+ for flag, path in (("--token-file-template", "token.{persona}"),
5972
+ ("--state-file-template", "{persona}.state"),
5973
+ ("--events-file-template", "events.{persona}.ndjson")):
5974
+ self.assertRegex(after, re.escape(flag) + r" \S*" + re.escape(path))
5975
+ self.assertIn("--poll-seconds 30", after) # everything else untouched
5976
+ self.assertIn("REFUSING to rewrite", r.stdout) # /nonexistent lacks the new flags
5977
+ self.assertEqual(r.returncode, 0, "a dry run never fails")
5978
+
5979
+ def test_the_rewritten_unit_resolves_to_the_same_paths_the_shipped_template_does(self):
5980
+ r = self._run(self.OLD)
5981
+ after = next(l for l in r.stdout.splitlines() if l.startswith("ExecStart after:"))
5982
+ argv = [w.replace("%h", "/h").replace("%I", "Loom") for w in after.split()[3:]]
5983
+ args = km.build_parser().parse_args(argv)
5984
+ km.validate_args(args)
5985
+ shipped = km.build_parser().parse_args(SupervisorPersonaPathParityTest()._systemd_argv_home("Loom", "/h"))
5986
+ km.validate_args(shipped)
5987
+ self.assertEqual(args.token_file, shipped.token_file)
5988
+ self.assertEqual(args.state_file_template, shipped.state_file_template)
5989
+ self.assertEqual(args.events_file_template, shipped.events_file_template)
5990
+
5991
+ def test_an_already_migrated_unit_is_left_alone(self):
5992
+ # The shipped template IS the migrated form, so running the script on it must be a no-op report.
5993
+ here = os.path.dirname(os.path.abspath(__file__))
5994
+ with open(os.path.join(here, "kijito-inbox-monitor@.service.template"), encoding="utf-8") as fh:
5995
+ r = self._run(fh.read())
5996
+ self.assertIn("already migrated", r.stdout)
5997
+ self.assertNotIn("ExecStart after:", r.stdout)