@miadi/tide 0.6.6 → 0.6.7

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/README.md CHANGED
@@ -148,7 +148,7 @@ other pane. A block mark is always a comment. `looks_good` and `delete` need a q
148
148
  | `TIDE_TMUX_BIN` | `tmux` on `PATH` | `sendKeys` |
149
149
  | `TIDE_HERDR_BIN` | `herdr` on `PATH` | the herdr verbs |
150
150
  | `TIDE_ALLOW_NON_INTERACTIVE_RUN` | unset | `1` lets a reviewed service pass the terminal check |
151
- | `PLANNOTATOR_TMUX_REVIEW_SCRIPT` | `/opt/gaia/linux_migration/11-plannotator-tmux-review.sh` | the review script |
151
+ | `PLANNOTATOR_TMUX_REVIEW_SCRIPT` | `/usr/lib/miadi-tide/plannotator-tmux-review.sh`, else `/a/src/Miadi/packages/tide/scripts/plannotator-tmux-review.sh` | the review script |
152
152
  | `PLANNOTATOR_TUI_BIN` | `which plannotator-tui`, then `~/.cargo/bin/plannotator-tui` | the headless annotator |
153
153
  | `PLANNOTATOR_TMUX_REVIEW_DIR` | `${XDG_STATE_HOME:-~/.local/state}/plannotator-tmux-review` | review documents (web runs under `web/`) |
154
154
  | `PLANNOTATOR_STORE_DIR` | `~/.plannotator/clients/plannotator-tui/annotations` | plannotator's mark records |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/tide",
3
- "version": "0.6.6",
3
+ "version": "0.6.7",
4
4
  "description": "Typed client boundary for the ironsilk `tide` runtime. Daemon Unix-socket transport with CLI fallback.",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -12,7 +12,9 @@
12
12
  ".": "./src/index.ts"
13
13
  },
14
14
  "files": [
15
- "src"
15
+ "src",
16
+ "scripts/*.sh",
17
+ "scripts/*.py"
16
18
  ],
17
19
  "dependencies": {
18
20
  "@miadi/annotate-core": "^0.3.1",
@@ -25,6 +27,7 @@
25
27
  "operator-cockpit"
26
28
  ],
27
29
  "scripts": {
28
- "test": "d=$(mktemp -d \"${TMPDIR:-/tmp}/miadi-tide-test.XXXXXX\") && trap 'rm -rf \"$d\"' EXIT && ../../node_modules/.bin/tsc -p tsconfig.test.json --outDir \"$d\" && ln -s \"$PWD/node_modules\" \"$d/packages/tide/node_modules\" && node --test \"$d\"/packages/tide/test/*.test.js"
30
+ "test:session": "python3 test/agent-session.test.py",
31
+ "test": "python3 test/agent-session.test.py && d=$(mktemp -d \"${TMPDIR:-/tmp}/miadi-tide-test.XXXXXX\") && trap 'rm -rf \"$d\"' EXIT && ../../node_modules/.bin/tsc -p tsconfig.test.json --outDir \"$d\" && ln -s \"$PWD/node_modules\" \"$d/packages/tide/node_modules\" && node --test \"$d\"/packages/tide/test/*.test.js"
29
32
  }
30
33
  }
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env bash
2
+ # pane-write-guard.sh — refuse to write into a pane a human is already composing in.
3
+ #
4
+ # Earned 2026-08-14 (ep325): a coordinator sent notes into a lane while William was
5
+ # typing into it. His own two messages collided. He said, verbatim:
6
+ # "yeah, you shall look if I am not writing already before....!!!!!!!"
7
+ #
8
+ # Prose corrections for this shape failed three times in one day in this ecosystem,
9
+ # because prose is something a seat must recall at the right instant. This is the
10
+ # check instead.
11
+ #
12
+ # Usage:
13
+ # pane-write-guard.sh <tmux-target> # exit 0 = safe to write
14
+ # pane-write-guard.sh <tmux-target> --quiet # exit code only
15
+ # pane-write-guard.sh - < captured-pane.txt # read a capture from stdin (testing)
16
+ #
17
+ # Exit codes — branch on these, never on "it printed something":
18
+ # 0 clear — prompt is empty, nobody is composing
19
+ # 1 COMPOSING — text sits at the prompt. DO NOT WRITE, DO NOT PRESS ENTER.
20
+ # 2 BUSY — lane is mid-turn; its empty prompt means working, not free.
21
+ # 3 NO PANE — target does not exist.
22
+ #
23
+ # The distinction this exists to protect, and it is the whole point:
24
+ # Enter on a COMPLETE message its author asked you to deliver = delivery
25
+ # Enter on a sentence still being typed = corruption
26
+ # They are opposite acts and they look identical from the keyboard.
27
+ #
28
+ # HOW IT READS THE PANE, and why the obvious way is wrong. The Claude TUI draws its
29
+ # input box between TWO horizontal rules, with status furniture below the second:
30
+ #
31
+ # ────────────────────────────── session-name ── <- rule N-1
32
+ # ❯ the text a human is typing <- THE INPUT REGION
33
+ # ────────────────────────────────────────────── <- rule N
34
+ # ⏵⏵ bypass permissions on ... <- furniture
35
+ #
36
+ # The first version of this script captured everything after the LAST rule, which is
37
+ # only the furniture — so it reported "clear" on the very pane that produced it. That
38
+ # failure was reproduced against a fixture before this version was written, and both
39
+ # fixtures ship beside this file so the next change has to prove it too. An identifier
40
+ # that cannot distinguish is worse than none (MINO §9); the only way to know which you
41
+ # have is to measure two cases that must come out different.
42
+
43
+ set -uo pipefail
44
+
45
+ TARGET="${1:-}"
46
+ QUIET=0
47
+ [ "${2:-}" = "--quiet" ] && QUIET=1
48
+
49
+ if [ -z "$TARGET" ]; then
50
+ echo "usage: $(basename "$0") <tmux-target|-> [--quiet]" >&2
51
+ exit 3
52
+ fi
53
+
54
+ say() { [ "$QUIET" -eq 1 ] || echo "$@"; }
55
+
56
+ if [ "$TARGET" = "-" ]; then
57
+ PANE=$(cat)
58
+ else
59
+ PANE=$(tmux capture-pane -p -t "$TARGET" 2>/dev/null) || {
60
+ say "NO PANE $TARGET does not exist. Re-survey before dispatching."
61
+ exit 3
62
+ }
63
+ fi
64
+
65
+ # Extract the region BETWEEN the last two horizontal rules.
66
+ INPUT=$(printf '%s\n' "$PANE" | awk '
67
+ { line[NR] = $0; if ($0 ~ /[─━]{10,}/) rule[++r] = NR }
68
+ END {
69
+ if (r < 2) exit
70
+ for (i = rule[r-1] + 1; i < rule[r]; i++) print line[i]
71
+ }
72
+ ' \
73
+ | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' \
74
+ -e 's/^❯[[:space:]]*//' -e 's/^>[[:space:]]*//' \
75
+ -e 's/\xc2\xa0/ /g' \
76
+ | grep -viE 'bypass permissions|esc to interrupt|shift\+tab|for agents|^/rc$|ctrl\+' \
77
+ | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' \
78
+ | grep -v '^$')
79
+
80
+ if [ -n "$INPUT" ]; then
81
+ say "COMPOSING $TARGET has text at its prompt — someone is writing."
82
+ say " ┌─ what is sitting there:"
83
+ [ "$QUIET" -eq 1 ] || printf '%s\n' "$INPUT" | sed 's/^/ │ /' | head -8
84
+ say " └─ DO NOT write and DO NOT press Enter, unless its author asked you"
85
+ say " to deliver THAT message. Put findings in the episode vessel —"
86
+ say " a vessel file waits, a pane message interrupts."
87
+ exit 1
88
+ fi
89
+
90
+ # Mid-turn: "esc to interrupt" on the status line, or, when a narrow pane cuts that
91
+ # line to "· esc …", Claude's spinner: a glyph, then one verb ending in "…"
92
+ # ("✽ Cerebrating… (3s)"). An answered turn reads "✻ Cooked for 18s". Alternation,
93
+ # not a bracket, so the multibyte glyphs match in any locale. Earned 2026-10-21.
94
+ if printf '%s\n' "$PANE" | grep -qE 'esc to interrupt|^(·|✢|✳|✶|✻|✽|\*) [^ …]+…'; then
95
+ say "BUSY $TARGET is mid-turn. Its empty prompt means working, not free."
96
+ say " A brief sent now can be swallowed while 'agent send' still returns ok."
97
+ say " Read the pane back after sending, or wait."
98
+ exit 2
99
+ fi
100
+
101
+ say "clear $TARGET prompt is empty and the lane is not mid-turn."
102
+ exit 0
@@ -0,0 +1,112 @@
1
+ #!/usr/bin/env python3
2
+ """Exact terminal session selection for the tmux review loop. No cwd/mtime guesses."""
3
+ import argparse
4
+ from datetime import datetime
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import re
9
+ import socket
10
+ import sqlite3
11
+ import sys
12
+
13
+ UUID = re.compile(r"(?<![\w-])[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}(?![\w-])", re.I)
14
+ SHORT_ID = re.compile(r"(?<![\w-])([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{5,11})\.{3}(?!\w)", re.I)
15
+
16
+
17
+ def codex_id(title, home=None):
18
+ ids = set(UUID.findall(title))
19
+ home = home or Path(os.environ.get('CODEX_HOME', Path.home() / '.codex'))
20
+ for prefix in SHORT_ID.findall(title):
21
+ candidates = set()
22
+ for database in home.glob('state_*.sqlite'):
23
+ try:
24
+ connection = sqlite3.connect(database.as_uri() + '?mode=ro', uri=True, timeout=.2)
25
+ try:
26
+ candidates.update(row[0] for row in connection.execute('select id from threads where id like ?', (prefix + '%',)))
27
+ finally:
28
+ connection.close()
29
+ except sqlite3.Error:
30
+ continue
31
+ # Older versions may not have a state database. Native rollout names
32
+ # carry full IDs; never pick by cwd, creation time, or modification time.
33
+ for bucket in ('sessions', 'archived_sessions'):
34
+ for path in (home / bucket).rglob('rollout-*' + prefix + '*.jsonl'):
35
+ candidate = path.stem[-36:]
36
+ if UUID.fullmatch(candidate) and candidate.startswith(prefix):
37
+ candidates.add(candidate)
38
+ if len(candidates) != 1:
39
+ raise ValueError('abbreviated Codex title does not identify one native session; pass --session explicitly')
40
+ ids.update(candidates)
41
+ if len(ids) > 1:
42
+ raise ValueError("several thread IDs in the Codex terminal title; pass --session explicitly")
43
+ return next(iter(ids), None)
44
+
45
+
46
+ def started_at(pid, proc=Path('/proc')):
47
+ # comm can contain spaces and parentheses. Field 22 follows the final ')'.
48
+ ticks = int((proc / str(pid) / 'stat').read_text().rsplit(')', 1)[1].split()[19])
49
+ boot = next(int(line.split()[1]) for line in (proc / 'stat').read_text().splitlines()
50
+ if line.startswith('btime '))
51
+ return boot + ticks / os.sysconf('SC_CLK_TCK')
52
+
53
+
54
+ def captured_session(root, host, pid, pane_id, start):
55
+ latest = None
56
+ try:
57
+ with (root / 'data/terminal_bindings.jsonl').open() as stream:
58
+ for line in stream:
59
+ try:
60
+ record = json.loads(line)
61
+ if record.get('agent') != host or record.get('pid') != pid:
62
+ continue
63
+ if record.get('host') not in (socket.gethostname(), socket.gethostname().split('.')[0]):
64
+ continue
65
+ at = datetime.fromisoformat(record['at'].replace('Z', '+00:00')).timestamp()
66
+ if at < start:
67
+ continue # PIDs and tmux pane IDs are reused after exit/reboot.
68
+ tmux = record.get('tmux') or {}
69
+ if tmux.get('pane_id') != pane_id:
70
+ continue
71
+ latest = record
72
+ except (ValueError, TypeError, KeyError):
73
+ continue
74
+ except FileNotFoundError:
75
+ pass
76
+ if not latest or latest.get('event') == 'session.end':
77
+ raise ValueError(f"no current {host} capture binding for PID {pid}; enable its session-observability plugin")
78
+ transcript = Path(latest.get('transcript_path') or '')
79
+ if not transcript.is_file():
80
+ raise ValueError(f"the {host} capture binding names a missing transcript")
81
+ return {'session': str(transcript), 'session_id': latest['session_id']}
82
+
83
+
84
+ def main():
85
+ parser = argparse.ArgumentParser(description=__doc__)
86
+ parser.add_argument('--host', choices=['codex', 'pi'], required=True)
87
+ parser.add_argument('--pid', type=int, required=True)
88
+ parser.add_argument('--pane-id', required=True)
89
+ parser.add_argument('--title', default='')
90
+ args = parser.parse_args()
91
+ try:
92
+ agent_env = dict(item.decode().split('=', 1) for item in Path(f'/proc/{args.pid}/environ').read_bytes().split(b'\0') if b'=' in item)
93
+ except (OSError, UnicodeError):
94
+ agent_env = {}
95
+ if args.host == 'codex':
96
+ home = Path(agent_env['CODEX_HOME']) if agent_env.get('CODEX_HOME') else None
97
+ sid = codex_id(args.title, home)
98
+ # Older Codex processes can still be resolved by their open rollout descriptor.
99
+ print(json.dumps({'session_id': sid} if sid else {}))
100
+ return
101
+ env = {**os.environ, **agent_env}
102
+ default = '/src/_sessiondata' if Path('/src').exists() else str(Path.home() / '_sessiondata')
103
+ root = next((env[k] for k in ('MIADI_SESSION_DIR', 'MIADI_SESSIONDATA_ROOT', 'SESSION_DATA_ROOT') if env.get(k)), default)
104
+ print(json.dumps(captured_session(Path(root), args.host, args.pid, args.pane_id, started_at(args.pid))))
105
+
106
+
107
+ if __name__ == '__main__':
108
+ try:
109
+ main()
110
+ except (ValueError, OSError) as error:
111
+ print(f'agent session: {error}', file=sys.stderr)
112
+ sys.exit(1)
@@ -0,0 +1,383 @@
1
+ #!/usr/bin/env bash
2
+ # plannotator-tmux-review.sh — maintained in @miadi/tide (jgwill/Miadi#851)
3
+ #
4
+ # Close the plannotator review loop for a coding agent running in a PLAIN TMUX PANE.
5
+ #
6
+ # Inside herdr, `prefix+shift+o` opens the agent's last reply and `E` delivers the
7
+ # review straight back into its pane. Outside herdr there is no delivery: plain
8
+ # `plannotator-tui last` has no --deliver-to (that flag exists only under the `herdr`
9
+ # subcommands), so the review stops at the clipboard. This script supplies the missing
10
+ # leg for tmux.
11
+ #
12
+ # The TUI footer reads ` E send ` in both contexts, which is a trap here: outside herdr
13
+ # `E` copies to the clipboard and records target:"clipboard" in the annotation store.
14
+ # It never reaches the pane. Close the TUI with `q` — this script delivers after it exits.
15
+ #
16
+ # resolve the agent in a pane -> open its last reply -> annotate -> paste the
17
+ # review back into that pane
18
+ #
19
+ # Usage:
20
+ # plannotator-tmux-review <tmux-target> [options]
21
+ #
22
+ # <tmux-target> %64, session:win.pane, anything tmux accepts
23
+ # --agent-pid N skip auto-resolution, use this PID
24
+ # --session FILE skip PID resolution, read this transcript
25
+ # --pick N which recent reply (default 1, the latest)
26
+ # --host NAME claude|codex|pi|omp|copilot|droid|hermes|opencode
27
+ # --from-file FILE annotate this Markdown instead of an agent reply
28
+ # --no-tui do not open the TUI (annotations already made headlessly)
29
+ # --print print what would be delivered; deliver nothing
30
+ # --submit press Enter after pasting (default: paste only, you press it)
31
+ #
32
+ # Two things this refuses to do:
33
+ # - deliver into a pane whose human is mid-sentence (pane-write-guard.sh)
34
+ # - deliver a reply it cannot prove belongs to the target pane (see RESOLUTION below)
35
+ #
36
+ # NO ANNOTATION IS EVER LOST. Each run keeps its document in a durable vessel under
37
+ # $XDG_STATE_HOME/plannotator-tmux-review (override: $PLANNOTATOR_TMUX_REVIEW_DIR).
38
+ # If the run dies, or the pane was busy, re-deliver with:
39
+ # plannotator-tmux-review <target> --from-file <vessel>/reply.md --no-tui
40
+ #
41
+ # A vessel fetched from a pane also keeps source.json, the pane identity in the schema
42
+ # jgwill/Miadi tide writes for its web runs (packages/tide/src/annotate.ts SourceIdentity),
43
+ # so a reply reviewed with `tan` is a vessel tide can recognise and deliver. Plan:
44
+ # jgwill/gaia#87.
45
+ #
46
+ # A RUN SURVIVES EDITS TO THIS FILE: it re-execs a snapshot of itself, because bash reads
47
+ # a script by byte offset and an edit under a live run makes it resume mid-statement.
48
+ # Earned 2026-09-08, twice: `syntax error near unexpected token`, then `line 239: e:
49
+ # command not found` — both landing on a review that was already open in the TUI.
50
+ #
51
+ # RESOLUTION, and the trap it exists to catch. `plannotator-tui last --pid N` does NOT
52
+ # error when N is not an agent: it silently falls back to the transcript of whatever
53
+ # session invoked it. Measured 2026-09-05 — `--pid 1` and `--pid 999999` both returned
54
+ # the calling session's own last reply, and a tmux pane_pid is normally the SHELL, not
55
+ # the agent, so the obvious implementation delivers the wrong session's words. This
56
+ # script walks the pane's descendants for the agent process itself, carries the
57
+ # detected host and process cwd into plannotator-tui, then — when --pid turns out to
58
+ # have changed nothing — proves the folder it resolved from holds only that one live
59
+ # agent before it writes anything. Codex uses the TUI's native thread ID and Pi
60
+ # its capture binding. Claude uses ~/.claude/sessions/<pid>.json (see below).
61
+ #
62
+ # Install: apt install miadi-tide. Native annotator: runtime/plannotator-tui.
63
+ # Tracked: jgwill/Miadi#851. Original review loop: jgwill/gaia#80.
64
+
65
+ set -euo pipefail
66
+
67
+ # Run from a snapshot, so saving this file cannot land inside a review already in
68
+ # progress. bash reads a script by byte offset as it executes: an edit that changes the
69
+ # line count makes the live run resume in the middle of a statement, and the annotations
70
+ # sitting in its vessel never get delivered.
71
+ if [ -z "${PLANNOTATOR_TMUX_REVIEW_SNAPSHOT:-}" ]; then
72
+ _snap="$(mktemp -t plannotator-tmux-review.XXXXXX.sh)"
73
+ cat "$0" > "$_snap"
74
+ export PLANNOTATOR_TMUX_REVIEW_SNAPSHOT="$_snap"
75
+ export PLANNOTATOR_TMUX_REVIEW_SRC="$0"
76
+ set +e; bash "$_snap" "$@"; _rc=$?; set -e
77
+ rm -f "$_snap"
78
+ exit "$_rc"
79
+ fi
80
+ SELF="${PLANNOTATOR_TMUX_REVIEW_SRC:-$0}"
81
+
82
+ TARGET=""
83
+ AGENT_PID=""
84
+ SESSION=""
85
+ PICK="1"
86
+ HOST=""
87
+ FROM_FILE=""
88
+ OPEN_TUI=1
89
+ PRINT_ONLY=0
90
+ SUBMIT=0
91
+ # The guard: $PANE_WRITE_GUARD, else the copy beside this script (the miadi-tide
92
+ # package ships one, jgwill/miadi-orchestration-kit#55), else the skill's own.
93
+ # "This script" is $SELF: $0 is the /tmp snapshot the run executes from.
94
+ GUARD="${PANE_WRITE_GUARD:-}"
95
+ if [ -z "$GUARD" ]; then
96
+ GUARD="$(dirname "$(readlink -f "$SELF")")/pane-write-guard.sh"
97
+
98
+ fi
99
+ AGENT_NAMES='claude|codex|copilot|droid|hermes|opencode|omp|^pi$'
100
+
101
+ RED=$'\033[0;31m'; GREEN=$'\033[0;32m'; YELLOW=$'\033[1;33m'; BLUE=$'\033[0;34m'; NC=$'\033[0m'
102
+ info() { echo "${BLUE}==>${NC} $*" >&2; }
103
+ ok() { echo "${GREEN} ok${NC} $*" >&2; }
104
+ warn() { echo "${YELLOW} !${NC} $*" >&2; }
105
+ fail() { echo "${RED} xx${NC} $*" >&2; exit 1; }
106
+
107
+ while [ $# -gt 0 ]; do
108
+ case "$1" in
109
+ --agent-pid) AGENT_PID="${2:?--agent-pid needs a PID}"; shift ;;
110
+ --session) SESSION="${2:?--session needs a transcript path}"; shift ;;
111
+ --pick) PICK="${2:?--pick needs a number}"; shift ;;
112
+ --host) HOST="${2:?--host needs a name}"; shift ;;
113
+ --from-file) FROM_FILE="${2:?--from-file needs a path}"; shift ;;
114
+ --no-tui) OPEN_TUI=0 ;;
115
+ --print) PRINT_ONLY=1 ;;
116
+ --submit) SUBMIT=1 ;;
117
+ -h|--help) sed -n '2,44p' "$SELF"; exit 0 ;;
118
+ -*) fail "unknown option: $1" ;;
119
+ *) [ -z "$TARGET" ] || fail "more than one tmux target given"; TARGET="$1" ;;
120
+ esac
121
+ shift
122
+ done
123
+
124
+ [ -n "$TARGET" ] || fail "no tmux target. Usage: $(basename "$0") <tmux-target> [options]"
125
+ command -v tmux >/dev/null 2>&1 || fail "tmux not found"
126
+ command -v plannotator-tui >/dev/null 2>&1 || fail "plannotator-tui not found — install miadi-tide"
127
+
128
+ PANE_PID="$(tmux display-message -p -t "$TARGET" '#{pane_pid}' 2>/dev/null || true)"
129
+ [ -n "$PANE_PID" ] || fail "no such tmux pane: $TARGET"
130
+ PANE_ID="$(tmux display-message -p -t "$TARGET" '#{session_name}:#{window_index}.#{pane_index} (#{pane_id})')"
131
+ ok "target $PANE_ID, pane_pid $PANE_PID"
132
+
133
+ # The run vessel is DURABLE on purpose. plannotator keys annotations to the document's
134
+ # path, so a mktemp dir that the trap deletes takes the review with it: any failure
135
+ # between closing the TUI and pasting loses the work with no way to re-export it.
136
+ # Measured 2026-09-08 — a run died after eight annotations and they had to be recovered
137
+ # by hand out of ~/.plannotator. Re-deliver a stranded run with:
138
+ # plannotator-tmux-review <target> --from-file <vessel>/reply.md --no-tui
139
+ VESSEL="${PLANNOTATOR_TMUX_REVIEW_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/plannotator-tmux-review}"
140
+ TMP="$VESSEL/$(date +%y%m%d-%H%M%S)-$(printf '%s' "$TARGET" | tr -c 'A-Za-z0-9._-' '-' | cut -c1-48)"
141
+ mkdir -p "$TMP" || fail "cannot create run vessel $TMP"
142
+ DOC="$TMP/reply.md"
143
+ ok "run vessel $TMP"
144
+
145
+ # ------------------------------------------------------- resolve the agent --
146
+
147
+ descendants() {
148
+ # every PID below $1, breadth-first
149
+ local queue="$1" next pid
150
+ while [ -n "$queue" ]; do
151
+ next=""
152
+ for pid in $queue; do
153
+ local kids
154
+ kids="$(ps -eo pid=,ppid= | awk -v p="$pid" '$2==p {print $1}' | tr '\n' ' ')"
155
+ [ -n "$kids" ] && { echo $kids | tr ' ' '\n'; next="$next $kids"; }
156
+ done
157
+ queue="$next"
158
+ done
159
+ }
160
+
161
+ if [ -n "$FROM_FILE" ]; then
162
+ [ -f "$FROM_FILE" ] || fail "no such file: $FROM_FILE"
163
+ # annotate it where it lives — plannotator keys annotations to the file path,
164
+ # so a copy into $TMP would lose every mark on the next run
165
+ DOC="$(cd "$(dirname "$FROM_FILE")" && pwd)/$(basename "$FROM_FILE")"
166
+ ok "annotating $DOC (agent resolution skipped)"
167
+ else
168
+ LAST_ARGS=()
169
+ if [ -n "$SESSION" ]; then
170
+ [ -f "$SESSION" ] || fail "no such transcript: $SESSION"
171
+ LAST_ARGS=(--session "$SESSION")
172
+ ok "transcript given: $SESSION"
173
+ else
174
+ if [ -z "$AGENT_PID" ]; then
175
+ info "Resolving the agent in $TARGET"
176
+ FOUND="$(for p in $(descendants "$PANE_PID"); do
177
+ c="$(ps -o comm= -p "$p" 2>/dev/null || true)"
178
+ case "$c" in claude|codex|copilot|droid|hermes|opencode|omp|pi) echo "$p $c" ;; esac
179
+ done)"
180
+ # the pane's own process can be the agent when no shell sits between
181
+ PANE_COMM="$(ps -o comm= -p "$PANE_PID" 2>/dev/null || true)"
182
+ case "$PANE_COMM" in claude|codex|copilot|droid|hermes|opencode|omp|pi) FOUND="$PANE_PID $PANE_COMM
183
+ $FOUND" ;; esac
184
+ FOUND="$(echo "$FOUND" | sed '/^$/d')"
185
+ COUNT="$(echo "$FOUND" | sed '/^$/d' | wc -l)"
186
+ [ "$COUNT" -ge 1 ] || fail "no coding agent process under pane $TARGET (looked for: ${AGENT_NAMES//|/, })"
187
+ if [ "$COUNT" -gt 1 ]; then
188
+ warn "several agent processes under this pane:"
189
+ echo "$FOUND" | sed 's/^/ /' >&2
190
+ fail "pass --agent-pid N to say which"
191
+ fi
192
+ AGENT_PID="${FOUND%% *}"
193
+ ok "agent $AGENT_PID ($(ps -o comm= -p "$AGENT_PID"))"
194
+ fi
195
+
196
+ # || true: under pipefail a dead PID fails ps, and set -e would exit before the
197
+ # message below. Measured 2026-09-24: a stale --agent-pid exited 1 with no output.
198
+ AGENT_COMM="$(ps -o comm= -p "$AGENT_PID" 2>/dev/null | tr -d '[:space:]' || true)"
199
+ [ -n "$AGENT_COMM" ] || fail "agent PID $AGENT_PID does not exist"
200
+ if [ -z "$HOST" ]; then
201
+ case "$AGENT_COMM" in
202
+ claude|codex|copilot|droid|hermes|opencode|omp|pi) HOST="$AGENT_COMM" ;;
203
+ *) fail "cannot infer transcript host from process '$AGENT_COMM'; pass --host or --session" ;;
204
+ esac
205
+ fi
206
+ AGENT_CWD="$(readlink "/proc/$AGENT_PID/cwd" 2>/dev/null || true)"
207
+ [ -n "$AGENT_CWD" ] || fail "cannot read cwd for agent PID $AGENT_PID; pass --session explicitly"
208
+ ok "transcript host $HOST, cwd $AGENT_CWD"
209
+ LAST_ARGS=(--pid "$AGENT_PID")
210
+ # Codex 0.164's shared daemon owns the rollout; the TUI has no open transcript.
211
+ # Its native `thread-id` terminal-title item follows new/resumed/forked tasks.
212
+ # Pi's capture extension records its own PID and native session file. Use that
213
+ # binding rather than plannotator's newest-session-in-cwd fallback.
214
+ if [ "$HOST" = codex ] || [ "$HOST" = pi ]; then
215
+ RESOLVER="$(dirname "$(readlink -f "$SELF")")/plannotator-agent-session.py"
216
+ [ -f "$RESOLVER" ] || fail "missing exact session resolver: $RESOLVER"
217
+ BINDING=$(python3 "$RESOLVER" --host "$HOST" --pid "$AGENT_PID" \
218
+ --pane-id "$(tmux display-message -p -t "$TARGET" '#{pane_id}')" \
219
+ --title "$(tmux display-message -p -t "$TARGET" '#{pane_title}')") \
220
+ || fail "cannot resolve the selected $HOST session"
221
+ EXACT_PATH=$(jq -r '.session // empty' <<< "$BINDING")
222
+ EXACT_ID=$(jq -r '.session_id // empty' <<< "$BINDING")
223
+ if [ -n "$EXACT_PATH" ]; then
224
+ LAST_ARGS=(--session "$EXACT_PATH")
225
+ SESSION="$EXACT_PATH"
226
+ ok "transcript from $HOST capture binding: $EXACT_PATH"
227
+ elif [ -n "$EXACT_ID" ]; then
228
+ LAST_ARGS=(--session-id "$EXACT_ID")
229
+ # An exact native ID needs no neighbour-reply comparison below.
230
+ SESSION="thread:$EXACT_ID"
231
+ ok "Codex thread from terminal title: $EXACT_ID"
232
+ elif [ "$HOST" = codex ]; then
233
+ warn 'Codex daemon sessions need tui.terminal_title to include "thread-id" (configure through /title, move thread-id first, then save)'
234
+ fi
235
+ fi
236
+ # For Claude, use its native PID registry rather than directory recency. plannotator-tui 0.7.0 returns the newest-modified
237
+ # .jsonl in the folder whatever PID it is given, and every /exit appends cost-state to
238
+ # its own transcript. Measured 2026-09-14: after restarts around a tmux upgrade, the
239
+ # review opened a reply from 2026-09-12, and --pid <live agent> with its registry file
240
+ # present still returned it. Claude's session registry names the transcript: use it.
241
+ if [ "$HOST" = "claude" ]; then
242
+ command -v jq >/dev/null 2>&1 || fail "jq not found (needed to read the Claude session registry)"
243
+ CLAUDE_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
244
+ REG="$CLAUDE_DIR/sessions/$AGENT_PID.json"
245
+ [ -f "$REG" ] || fail "no Claude session registry for PID $AGENT_PID ($REG). Pass --session <transcript>."
246
+ REG_SID="$(jq -r '.sessionId // empty' "$REG")"
247
+ REG_CWD="$(jq -r '.cwd // empty' "$REG")"
248
+ [ -n "$REG_SID" ] && [ -n "$REG_CWD" ] || fail "$REG has no sessionId or cwd. Pass --session <transcript>."
249
+ SESSION="$CLAUDE_DIR/projects/$(printf '%s' "$REG_CWD" | sed 's/[^A-Za-z0-9]/-/g')/$REG_SID.jsonl"
250
+ [ -f "$SESSION" ] || fail "registry names session $REG_SID but $SESSION does not exist. Pass --session <transcript>."
251
+ LAST_ARGS=(--session "$SESSION")
252
+ ok "transcript from Claude registry: $SESSION"
253
+ fi
254
+ fi
255
+ [ -n "$HOST" ] && LAST_ARGS+=(--host "$HOST")
256
+
257
+ info "Reading the agent's reply (--pick $PICK)"
258
+ PLANNOTATOR_TUI_CWD="${AGENT_CWD:-$PWD}" \
259
+ plannotator-tui last "${LAST_ARGS[@]}" --print --pick "$PICK" > "$DOC" 2>"$TMP/err" \
260
+ || { cat "$TMP/err" >&2; fail "plannotator-tui last failed"; }
261
+ [ -s "$DOC" ] || { cat "$TMP/err" >&2; fail "no reply text came back"; }
262
+ grep -q 'no assistant messages' "$DOC" && { cat "$DOC" >&2; fail "that transcript has no assistant messages yet"; }
263
+
264
+ # --- proof: --pid told this agent apart from its neighbours ----------------
265
+ # The only way a resolved reply can be the wrong one is if plannotator answered with
266
+ # some OTHER live agent's transcript. So ask it about those agents directly: every
267
+ # live $HOST sharing this cwd gets the same query, and our reply has to differ from
268
+ # all of them. One agent in the folder means nothing to confuse it with, and the
269
+ # check costs nothing.
270
+ #
271
+ # Two earlier proofs were wrong and both refused correct work. Comparing against an
272
+ # impossible --pid misfires whenever the folder resolver happens to agree with the
273
+ # PID resolver, which is the normal case for the newest session in a folder. Matching
274
+ # the reply against the pane's screen cannot work at all: Claude Code draws on the
275
+ # alternate screen, so capture-pane returns one screenful and nothing when the human
276
+ # has scrolled up. Measured 2026-09-08: `--pid` correctly returned this very session's
277
+ # last reply for its own PID, on a transcript far older than the process, while a
278
+ # birth-time heuristic handed that same file to a different agent.
279
+ if [ -z "$SESSION" ]; then
280
+ NEIGHBOURS="$(for p in $(pgrep -x "$HOST" 2>/dev/null || true); do
281
+ [ "$p" = "$AGENT_PID" ] && continue
282
+ [ "$(readlink "/proc/$p/cwd" 2>/dev/null)" = "$AGENT_CWD" ] && echo "$p"
283
+ done || true)"
284
+ NEIGHBOURS="$(printf '%s' "$NEIGHBOURS" | sed '/^$/d')"
285
+ CLASH=""
286
+ for n in $NEIGHBOURS; do
287
+ PLANNOTATOR_TUI_CWD="$AGENT_CWD" \
288
+ plannotator-tui last --pid "$n" --host "$HOST" --print --pick "$PICK" \
289
+ > "$TMP/neighbour-$n.md" 2>/dev/null || true
290
+ [ -s "$TMP/neighbour-$n.md" ] || continue
291
+ cmp -s "$DOC" "$TMP/neighbour-$n.md" && CLASH="$CLASH $n"
292
+ done
293
+ if [ -n "$CLASH" ]; then
294
+ warn "this reply is identical to what PID(s)$CLASH return, in the same folder"
295
+ fail "refusing: cannot tell $AGENT_PID apart from$CLASH. Pass --session <transcript> explicitly."
296
+ fi
297
+ # printf '%s' would drop the final newline and make wc -l report one short
298
+ N="$(printf '%s\n' "$NEIGHBOURS" | sed '/^$/d' | wc -l)"
299
+ [ "$N" -gt 0 ] && ok "distinct from $N other live $HOST in $AGENT_CWD" || true
300
+ fi
301
+ ok "$(wc -l < "$DOC") lines of reply"
302
+
303
+ # Where this reply came from, in tide's SourceIdentity schema. tide overwrites it with
304
+ # its own when it drives this script, so the two clients agree on one shape.
305
+ if command -v jq >/dev/null 2>&1; then
306
+ IFS=$'\t' read -r S_PANE S_SESS S_WIN S_IDX S_PPID < <(tmux display-message -p -t "$TARGET" \
307
+ '#{pane_id} #{session_name} #{window_index} #{pane_index} #{pane_pid}')
308
+ jq -n --arg target "$TARGET" --arg pane_id "$S_PANE" --arg session_name "$S_SESS" \
309
+ --arg window_index "$S_WIN" --arg pane_index "$S_IDX" --arg pane_pid "$S_PPID" \
310
+ --arg agent_pid "${AGENT_PID:-}" --arg host "${HOST:-}" --arg cwd "${AGENT_CWD:-}" \
311
+ --arg fetched_at "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)" \
312
+ '{target:$target, pane_id:$pane_id, session_name:$session_name, window_index:$window_index,
313
+ pane_index:$pane_index, pane_pid:$pane_pid,
314
+ agent_pid:($agent_pid|select(.!="")//null), host:($host|select(.!="")//null),
315
+ cwd:($cwd|select(.!="")//null), fetched_at:$fetched_at, via:"tan"}' \
316
+ > "$TMP/source.json" && ok "source.json: $S_PANE ($S_SESS:$S_WIN.$S_IDX)"
317
+ else
318
+ warn "jq not found: no source.json, so tide cannot tell which pane this reply came from"
319
+ fi
320
+ fi
321
+
322
+ # ------------------------------------------------------------- annotate it --
323
+
324
+ if [ "$OPEN_TUI" = 1 ]; then
325
+ info "Opening plannotator-tui — mark blocks, then q. Delivery happens on exit."
326
+ plannotator-tui "$DOC" || true
327
+ else
328
+ ok "TUI skipped (--no-tui)"
329
+ fi
330
+
331
+ REVIEW="$TMP/review.md"
332
+ plannotator-tui --export "$DOC" > "$REVIEW" 2>/dev/null || true
333
+ if [ ! -s "$REVIEW" ] || ! grep -q '^## Annotation' "$REVIEW"; then
334
+ warn "no annotations on that document — nothing to deliver"
335
+ warn "the document is kept at $DOC if you meant to annotate it"
336
+ exit 0
337
+ fi
338
+ COUNT_A="$(grep -c '^## Annotation' "$REVIEW")"
339
+ ok "$COUNT_A annotation(s) to deliver"
340
+
341
+ if [ "$PRINT_ONLY" = 1 ]; then
342
+ info "--print: delivering nothing"
343
+ cat "$REVIEW"
344
+ exit 0
345
+ fi
346
+
347
+ # -------------------------------------------------------------- deliver it --
348
+
349
+ if [ -x "$GUARD" ]; then
350
+ set +e
351
+ "$GUARD" "$TARGET" --quiet
352
+ G=$?
353
+ set -e
354
+ case "$G" in
355
+ 0) ok "pane-write-guard: clear" ;;
356
+ 1) HELD="COMPOSING" ;;
357
+ 2) HELD="BUSY mid-turn" ;;
358
+ 3) HELD="gone" ;;
359
+ *) HELD="unreadable (guard returned $G)" ;;
360
+ esac
361
+ if [ -n "${HELD:-}" ]; then
362
+ warn "pane-write-guard: $TARGET is $HELD. Not writing."
363
+ warn "Your $COUNT_A annotation(s) are safe. Re-deliver when the pane is clear:"
364
+ echo " $SELF $TARGET --from-file $DOC --no-tui$( [ "$SUBMIT" = 1 ] && echo " --submit" )" >&2
365
+ exit 1
366
+ fi
367
+ else
368
+ warn "pane-write-guard.sh not found at $GUARD — delivering unguarded"
369
+ fi
370
+
371
+ tmux load-buffer -b plannotator-review "$REVIEW"
372
+ tmux paste-buffer -b plannotator-review -t "$TARGET" -p -d
373
+ ok "pasted $COUNT_A annotation(s) into $PANE_ID"
374
+
375
+ if [ "$SUBMIT" = 1 ]; then
376
+ tmux send-keys -t "$TARGET" Enter
377
+ ok "submitted"
378
+ else
379
+ echo >&2
380
+ echo "${YELLOW}Not pressing Enter.${NC} The review sits at the prompt in $PANE_ID." >&2
381
+ echo "Send it yourself, or re-run with --submit." >&2
382
+ echo "If it is lost, the annotated document is kept at $DOC" >&2
383
+ fi
package/src/annotate.ts CHANGED
@@ -2,7 +2,8 @@
2
2
  // review into its tmux pane — the web leg of the plannotator review loop.
3
3
  //
4
4
  // This module owns NO resolution and NO delivery logic of its own. Both belong
5
- // to the review script (jgwill/gaia#80; installed by miadi-tide in /usr/lib/miadi-tide),
5
+ // to this package's scripts/plannotator-tmux-review.sh (installed by miadi-tide
6
+ // in /usr/lib/miadi-tide),
6
7
  // which already proves the reply belongs to the pane, keeps every run in a
7
8
  // durable vessel, refuses to paste while a human is typing, and pastes with
8
9
  // bracketed paste so a multi-line review does not submit itself line by line.
@@ -55,8 +56,8 @@ const pExecFile = promisify(execFile)
55
56
 
56
57
  /** The copy the miadi-tide package installs, beside its pane-write guard. */
57
58
  export const PACKAGED_REVIEW_SCRIPT = "/usr/lib/miadi-tide/plannotator-tmux-review.sh"
58
- /** The source checkout on gaia, used when the package is not installed. */
59
- export const DEFAULT_REVIEW_SCRIPT = "/opt/gaia/linux_migration/11-plannotator-tmux-review.sh"
59
+ /** The canonical source checkout, used when miadi-tide is not installed. */
60
+ export const DEFAULT_REVIEW_SCRIPT = "/a/src/Miadi/packages/tide/scripts/plannotator-tmux-review.sh"
60
61
  export const REVIEW_SCRIPT_ENV = "PLANNOTATOR_TMUX_REVIEW_SCRIPT"
61
62
  /** The script's own override for where run vessels live. Same name, same meaning. */
62
63
  export const VESSEL_ROOT_ENV = "PLANNOTATOR_TMUX_REVIEW_DIR"
@@ -153,7 +154,7 @@ export interface DeliverResult extends DeliverOutcome {
153
154
  log: string[]
154
155
  }
155
156
 
156
- /** `$PLANNOTATOR_TMUX_REVIEW_SCRIPT` → the miadi-tide package's copy → gaia's checkout. */
157
+ /** `$PLANNOTATOR_TMUX_REVIEW_SCRIPT` → miadi-tide's installed copy → this package's source. */
157
158
  export function resolveReviewScript(
158
159
  env: NodeJS.ProcessEnv = process.env,
159
160
  exists: (p: string) => boolean = existsSync,