Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .claude-config/backup/daily-sync.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@
# stranded the work in a stash when a run was killed between the two, and
# stash/pop dropped empty directories and reset file modes every day.
# - Project stage delegates to PROJECTS/sync-check.sh --auto: it walks every
# repo, fast-forwards / rebases the clean ones, and SKIPS dirty repos
# (never touches uncommitted work). Pull-only: it never pushes projects.
# main checkout, fast-forwards / rebases the clean ones, and SKIPS dirty
# repos (never touches uncommitted work). Pull-only: it never pushes
# projects. It leaves linked worktrees alone (a lane's private branch): a
# rebase there rewrote commit ids daily, which broke branch-gc's
# reflog-coverage proof and kept landed worktrees looking active.
# - Push gate: the backup sends the whole copy (memory, CONTEXT, notes) to
# origin, so it pushes only when bin/origin-private-check verifies origin
# private: exit 0 and its own "private" verdict line (gate_proved). A public
Expand Down
235 changes: 226 additions & 9 deletions .claude-config/bin/README.md

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions .claude-config/bin/asks
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,11 @@ def find_ref(docs, ref, thread_flag):
pool = [d for d in docs if d["thread"] == want or d["thread"].startswith(want) or short_id(d["thread"]) == want]
else:
raise AsksError("an ask is named N or THREAD#N, not '%s'" % ref)
# An exact id wins over ids it merely prefixes: without this a short thread id could
# never be named once a longer id shared its first eight characters.
exact = [d for d in pool if d["thread"] == want]
if exact:
pool = exact
if len(pool) > 1:
raise AsksError("'%s' matches %d threads; use more of the thread id" % (ref, len(pool)))
if not pool:
Expand Down
1,324 changes: 1,324 additions & 0 deletions .claude-config/bin/card

Large diffs are not rendered by default.

687 changes: 672 additions & 15 deletions .claude-config/bin/compact-cycle.sh

Large diffs are not rendered by default.

256 changes: 255 additions & 1 deletion .claude-config/bin/lib/t3_api_v2.py

Large diffs are not rendered by default.

482 changes: 482 additions & 0 deletions .claude-config/bin/lib/thread_messages.py

Large diffs are not rendered by default.

655 changes: 655 additions & 0 deletions .claude-config/bin/rest-stop

Large diffs are not rendered by default.

26 changes: 24 additions & 2 deletions .claude-config/bin/session-end
Original file line number Diff line number Diff line change
Expand Up @@ -1571,13 +1571,30 @@ def cmd_end(args, idn):
return print_report(rep, args.json)


def card_route(idn):
"""The rest-stop path when a pause takes the thread card route, else None. The same test
hooks/context-watch.sh compact_route() uses: a Claude session in a T3 thread (a Codex
session is not Claude here, and the card is Claude-only), the card on (CC_THREAD_CARD
not 0), and rest-stop installed beside this script."""
if idn["provider"] != "claude" or not idn["t3_thread_id"]:
return None
if os.environ.get("CC_THREAD_CARD", "1") == "0":
return None
return sibling("rest-stop")


def remainder(rep, mode, idn, tx, pool):
out = rep.remainder
rs = card_route(idn) if mode == "pause" else None
out.append("What only you can do now:")
out.append(" - Save the lessons worth keeping: one fact per file in the memory pool%s. A thread with none saves none."
% (" (%s)" % pool if pool else ""))
out.append(" - Put knowledge where the next person will look, and fix any document this thread made untrue.")
out.append(" - Write the resume note at the top of the anchor or baton: %s." % ", ".join(RESUME_FIELDS))
if rs:
out.append(" - Keep the thread card current (mission, finish line, backlog, holds); `%s prep` writes the "
"baton draft from it." % rs)
else:
out.append(" - Write the resume note at the top of the anchor or baton: %s." % ", ".join(RESUME_FIELDS))
lint = [s for s in rep.steps if s["step"] == "lint" and s["status"] == "findings"]
if lint:
out.append(" - Lint reported %d FAIL line(s) above: fix the ones on files this thread changed, "
Expand All @@ -1599,7 +1616,12 @@ def remainder(rep, mode, idn, tx, pool):
out.extend(rows or [" (no entry modified or touched in this window)"])
out.append(" Correct an entry this thread proved wrong, merge duplicates it touched, move a lesson that belongs in a repo's docs. session-end changed no entry.")
tid = idn["t3_thread_id"]
if mode == "pause":
if mode == "pause" and rs:
out.append("Pause: run %s prep, do what it prints, then %s arm --confirm-arming \"...\" "
"(it starts the compactor itself)" % (rs, rs))
out.append(" A question to the owner goes into the asks register first (%s add \"<one-line ask>\"); "
"rest-stop arm refuses while a T3 question card is pending." % (sibling("asks") or "asks"))
elif mode == "pause":
cc = sibling("compact-cycle.sh")
if tid and cc:
out.append("Pause: compact with %s --target %s" % (cc, tid))
Expand Down
145 changes: 126 additions & 19 deletions .claude-config/bin/t3-api.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
# has no pane to type into. T3 exposes an authenticated orchestration API; this
# helper is the client for it. compact-cycle.sh calls it to wait for idle, request
# native compaction, verify it and send the resume; context-watch.sh maps its
# session to the thread's baton through thread-for-session. It is also usable on
# its own for read-only inspection (snapshot / thread / active-turn).
# session to the thread's baton through thread-for-session; bin/card reads the
# owner's messages through thread-messages and history. It is also usable on its
# own for read-only inspection (snapshot / thread / thread-messages / history /
# active-turn).
#
# SUPPORT: Linux only (settle-when-idle detaches with setsid, and the suites run in
# bin/sandbox-run). It needs python3, curl, a T3 Code server on this box, and the
Expand Down Expand Up @@ -147,8 +149,34 @@
# thread <id> [turnLimit] V1: GET /api/orchestration/threads/<id>?turnLimit=N. V2: GET
# /api/orchestration/threads/<quoted id>/bounded plus the shell
# for run state, V1-shaped; turnLimit is ignored (the server
# bounds the answer; paged history is not fetched, no caller
# needs more than the latest run).
# bounds the answer to the latest messages, page.hasMoreHistory
# says older ones exist; `history` below reads those).
# thread-messages <id> The messages and page of `thread` without its run state. V2:
# /bounded alone, as {thread: {id, messages[] with turnId},
# page, snapshotSequence}; the shell is not read (it is the whole
# thread list, 29 MB and 8 to 9 s on a busy host on 2026-12-02, which
# made `thread` take 8 s). V1: exactly `thread <id>`. Exit 5 for an
# unknown thread. The thread card reads the owner's messages with it.
# history <id> [--until <ISO time>] [--max-pages N]
# V2 only (exit 8 on V1). The thread's older messages, which
# `thread` leaves out: reads /bounded for page.historyCursor, then
# GET /api/orchestration/threads/<quoted id>/history?cursor=<c>
# &view=conversation, following nextCursor while hasMoreHistory is
# true. Stops at the first of: the start of the thread; --until
# given and this thread's oldest item read (of any type) at or
# before that time; --max-pages pages read (default 40, at most
# 9999). The cursor is percent-encoded in lib/t3_api_v2.py, never
# pasted raw; GET only. Prints one JSON object: {threadId,
# messages: [{id (the messageId), role "user", text, createdAt (the
# item's startedAt), createdBy, creationSource, runId}], reachedStart,
# earliestAt (the oldest item's time, or null), pages, stopped
# (start, until, max-pages, or no-history when /bounded already
# holds the whole thread), otherThreadItems}. messages are the
# thread's user_message items from the pages only (not /bounded),
# oldest first, every origin (who counts as the owner is the
# caller's rule); an item whose item.threadId is another thread is
# counted in otherThreadItems and left out. /bounded and the pages
# do not overlap (read live 2026-12-02). A detached page exits 6.
# thread-for-session <sid> map a Claude or Codex session id -> T3 thread id (exit 5 if
# none or ambiguous). V1: the SQLite provider_session_runtime
# table. V2: statev2.sqlite
Expand All @@ -174,9 +202,11 @@
# text starting with '/' (unless exactly '/compact'), or a thread
# that /bounded shows archived or deleted; exit 5 for an unknown
# thread. Prints the server's {"sequence":N}: accepted, not done.
# compact <id> dispatch exact /compact; print its messageId. V2: the same
# compact <id> [--arm-record FILE]
# dispatch exact /compact; print its messageId. V2: the same
# message.dispatch as send, as its own queued run (steering it
# into an active run is refused by the server).
# into an active run is refused by the server). With an arm record,
# recheck the thread before dispatch. Exit 9 plus a reason if superseded.
# compact-status <id> <mid> print pending|completed|failed, matching that request. V2 reads
# /bounded: completed only when the run whose userMessageId is
# <mid> completed AND a turn item of type compaction with status
Expand Down Expand Up @@ -357,7 +387,7 @@
# answer: not JSON, HTML, or not the shape this client expects (one line to stderr) |
# 7 dispatch or archive refused on a protocol-2 server | 8 the server reports an
# orchestration protocol this client does not speak, or one a V2-only subcommand
# (server-busy, queued-cancel) cannot use | 9 refused by guard, the thread is
# (server-busy, queued-cancel, history) cannot use | 9 refused by guard, the thread is
# not idle (settle; the V1 code, kept) | 10 refused by guard, a write this client never
# sends (an archived or deleted thread, an empty text, a text starting with '/', a cancel
# of a queued message that is not a harness send) |
Expand Down Expand Up @@ -556,15 +586,26 @@ v2_dispatch() {
python3 -I "$WSLIB" call "$base" "$TOKEN_FILE" orchestration.dispatchCommand "$1"
}

# v2_message <thread-id> <text>: the guarded message.dispatch behind send and compact. The
# text guard runs before any read; the archived guard reads /bounded.
# check_compact_arm <thread-read> <thread-id> <arm-record>: exit 9 with a
# stand-down reason on stdout when the last read shows a change since arming.
check_compact_arm() {
local why
why="$(python3 -I "$LIB" compact-arm-check "$1" "$2" "$3" "$T3_PROTO")" || return $?
if [ -n "$why" ]; then printf '%s\n' "$why"; return 9; fi
}

# v2_message <thread-id> <text> [arm-record]: the guarded message.dispatch behind send and
# compact. The text guard runs before any read; the archived guard reads /bounded.
v2_message() {
local id="$1" tf="$_TMPDIR/message.txt" bf="$_TMPDIR/bounded.json" pf="$_TMPDIR/command.json"
local id="$1" arm="${3:-}" tf="$_TMPDIR/message.txt" bf="$_TMPDIR/bounded.json" pf="$_TMPDIR/command.json"
printf '%s' "$2" > "$tf"
python3 -I "$LIB" text-guard "$tf" || return $?
v2_bounded "$id" "$bf" || return $?
python3 -I "$LIB" target-check "$bf" "$id" || return $?
python3 -I "$LIB" command message "$id" "$tf" > "$pf" || return $?
# Use the /bounded read already made here, after the worker prepared its
# trailer. A V2 message otherwise queues behind a turn that started meanwhile.
if [ -n "$arm" ]; then check_compact_arm "$bf" "$id" "$arm" || return $?; fi
v2_dispatch "$pf"
}

Expand Down Expand Up @@ -620,6 +661,56 @@ cmd_thread() {
printf '%s\n' "$b"
}

# thread-messages <id>: `thread` without the shell read (SUBCOMMANDS).
cmd_thread_messages() {
local id="$1" bf="$_TMPDIR/bounded.json" rc
if [ "$T3_PROTO" != 2 ]; then cmd_thread "$id"; return $?; fi
v2_bounded "$id" "$bf" quiet; rc=$?
if [ "$rc" -eq 5 ]; then echo "t3-api: thread $id not found on the server (GET /bounded answered 404)" >&2; return 5; fi
[ "$rc" -eq 0 ] || return "$rc"
python3 -I "$LIB" bounded-messages "$bf" "$id"
}

# history <id> [--until T] [--max-pages N]: the paged older history (SUBCOMMANDS). Each
# page lands in its own file under the private _TMPDIR; lib/t3_api_v2.py decides the next
# step and percent-encodes the cursor, and the cursor is checked against the encoded
# alphabet before it goes into the path, so nothing from the server is ever evaluated.
cmd_history() {
local id="$1" until="" maxp=40 n=0 stopped="" step cur q dir="$_TMPDIR/history" rc
shift
while [ $# -gt 0 ]; do
case "$1" in
--until) [ $# -ge 2 ] || die_usage "history: --until needs an ISO time"; until="$2"; shift 2 ;;
--max-pages) { [ $# -ge 2 ] && [[ "$2" =~ ^[1-9][0-9]{0,3}$ ]]; } || die_usage "history: --max-pages needs a whole number from 1 to 9999"
maxp="$2"; shift 2 ;;
*) die_usage "history <thread-id> [--until <ISO time>] [--max-pages N]" ;;
esac
done
if [ "$T3_PROTO" != 2 ]; then
echo "t3-api: history needs orchestration protocol 2 (the /history route); this server speaks protocol $T3_PROTO" >&2
return 8
fi
mkdir -p "$dir" || return 4
q="$(python3 -I "$LIB" quote "$id")" || return 4
v2_bounded "$id" "$dir/bounded.json" || return $?
step="$(python3 -I "$LIB" history-step "$dir/bounded.json" "$id" "$until" bounded)" || return $?
while :; do
case "$step" in
start) if [ "$n" -eq 0 ]; then stopped=no-history; else stopped=start; fi; break ;;
until) stopped=until; break ;;
"more "*) cur="${step#more }" ;;
*) echo "t3-api: history: unexpected step '$step'" >&2; return 6 ;;
esac
[[ "$cur" =~ ^[A-Za-z0-9%._~-]+$ ]] || { echo "t3-api: history: the encoded cursor has characters outside the encoded alphabet" >&2; return 6; }
if [ "$n" -ge "$maxp" ]; then stopped=max-pages; break; fi
n=$((n + 1))
http_to "$dir/page-$n.json" GET "/api/orchestration/threads/$q/history?cursor=$cur&view=conversation"; rc=$?
[ "$rc" -eq 0 ] || return "$rc"
step="$(python3 -I "$LIB" history-step "$dir/page-$n.json" "$id" "$until" page)" || return $?
done
python3 -I "$LIB" history-messages "$dir" "$id" "$n" "$stopped"
}

# Provider session id -> T3 thread id. The read-only SQLite runtime table stores
# Claude IDs in resume_cursor_json.resume and Codex IDs in .threadId. Match the
# provider as well as the field, and refuse ambiguous mappings. On V2 the lookup is
Expand Down Expand Up @@ -689,7 +780,7 @@ PY
}

cmd_start() {
local id="$1" text="$2" message_id="${3:-}"
local id="$1" text="$2" message_id="${3:-}" arm="${4:-}"
# runtimeMode = the thread's current session.runtimeMode from the snapshot, else
# full-access. Skipped in dry mode so a dry send issues zero requests.
local rmode="full-access"
Expand Down Expand Up @@ -731,6 +822,11 @@ cmd = {
print(json.dumps(cmd))
PY
)"
if [ -n "$arm" ]; then
local thread_file="$_TMPDIR/arm-thread.json"
cmd_thread "$id" > "$thread_file" || return $?
check_compact_arm "$thread_file" "$id" "$arm" || return $?
fi
http POST /api/orchestration/dispatch "$body"
}

Expand All @@ -741,17 +837,24 @@ cmd_send() {
}

cmd_compact() {
local mid response
local id="$1" arm="${3:-}" mid response rc
if [ "$T3_PROTO" = 2 ]; then
response="$(v2_message "$id" "/compact" "$arm")"; rc=$?
else
mid="$(python3 -c 'import uuid; print(uuid.uuid4())')" || return 4
response="$(cmd_start "$id" "/compact" "$mid" "$arm")"; rc=$?
fi
if [ "$rc" -ne 0 ]; then
[ "$rc" -ne 9 ] || printf '%s\n' "$response"
return "$rc"
fi
if [ "${OPS_T3_DRY:-0}" = "1" ]; then printf '%s\n' "$response"; return 0; fi
if [ "$T3_PROTO" = 2 ]; then
response="$(v2_message "$1" "/compact")" || return $?
if [ "${OPS_T3_DRY:-0}" = "1" ]; then printf '%s\n' "$response"; return 0; fi
# The messageId is the one compact-status matches; it was minted into the command.
python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1]))["messageId"])' "$_TMPDIR/command.json" || return 4
return 0
else
printf '%s\n' "$mid"
fi
mid="$(python3 -c 'import uuid; print(uuid.uuid4())')" || return 4
response="$(cmd_start "$1" "/compact" "$mid")" || return $?
if [ "${OPS_T3_DRY:-0}" = "1" ]; then printf '%s\n' "$response"; else printf '%s\n' "$mid"; fi
}

cmd_compact_status() {
Expand Down Expand Up @@ -1169,9 +1272,13 @@ case "$sub" in
base) cmd_base ;;
snapshot) need_protocol; cmd_snapshot ;;
thread) [ $# -ge 1 ] || die_usage "thread <thread-id> [turnLimit]"; need_protocol; cmd_thread "$@" ;;
thread-messages) { [ $# -eq 1 ] && [ -n "$1" ]; } || die_usage "thread-messages <thread-id>"; need_protocol; cmd_thread_messages "$1" ;;
history) { [ $# -ge 1 ] && [ -n "$1" ]; } || die_usage "history <thread-id> [--until <ISO time>] [--max-pages N]"; need_protocol; cmd_history "$@" ;;
thread-for-session) [ $# -eq 1 ] || die_usage "thread-for-session <provider-session-id>"; need_protocol; cmd_thread_for_session "$1" ;;
active-turn) [ $# -eq 1 ] || die_usage "active-turn <thread-id>"; need_protocol; cmd_active_turn "$1" ;;
compact) [ $# -eq 1 ] || die_usage "compact <thread-id>"; need_protocol; cmd_compact "$1" ;;
compact) { [ $# -eq 1 ] || { [ $# -eq 3 ] && [ "$2" = --arm-record ] && [ -n "$3" ]; }; } \
|| die_usage "compact <thread-id> [--arm-record FILE]"
need_protocol; cmd_compact "$@" ;;
compact-status) [ $# -eq 2 ] || die_usage "compact-status <thread-id> <message-id>"; need_protocol; cmd_compact_status "$1" "$2" ;;
send) [ $# -ge 2 ] || die_usage "send <thread-id> <text...>"; need_protocol; cmd_send "$@" ;;
stop) [ $# -eq 1 ] || die_usage "stop <thread-id>"; need_protocol; cmd_stop "$1" ;;
Expand Down
11 changes: 11 additions & 0 deletions .claude-config/bin/tests/asks-test.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,17 @@ def test_resolve_by_number_by_ref_and_not_found(self):
self.assertEqual(self.run_asks("resolve", "not-a-ref").returncode, 2)
self.assertIn("already resolved", self.ok("resolve", "1").stdout)

def test_a_thread_id_that_prefixes_another_resolves_by_its_exact_id(self):
# Seen live: thread "b3224d7b" and thread "b3224d7b-0924-..." both held asks, and
# neither "b3224d7b#1" nor "--thread b3224d7b 1" could name the short one.
self.ok("add", "short", thread="cccccccc")
self.ok("add", "long", thread="cccccccc-1111-2222-3333-444444444444")
self.ok("resolve", "cccccccc#1", "--note", "by ref")
self.assertEqual([i["text"] for i in self.listed("--all")], ["long"])
self.ok("add", "short again", thread="cccccccc")
self.ok("resolve", "2", "--thread", "cccccccc")
self.assertEqual([i["text"] for i in self.listed("--all")], ["long"])

def test_resolved_asks_are_pruned_after_fourteen_days(self):
self.ok("add", "old")
self.ok("add", "kept")
Expand Down
Loading