From fad90c92ed7755739fa2f8c964069276d9dea90e Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:44:28 +0530 Subject: [PATCH] docs(kin): rewrite the docs for no workers and no GitHub App; add the host cleanup script Kin no longer has workers or its own GitHub App, so the specs, host README, user guide and update script described machinery that is gone. Rewrites (never appends) the approvals, lead and triggers specs, DESIGN 9, PLAN W1-1, KT and the host README; update.sh stops restarting workers; retire-workers.sh removes what kin-worker.sh installed and lists the App's leftovers. The superseded lines described the workers, the GitHub App, request_action, owner merges and the App webhook, all removed in #424 and #428. Supersedes: #44 Supersedes: #45 Supersedes: #46 Supersedes: #69 Supersedes: #135 Supersedes: #183 Supersedes: #294 Supersedes: #301 Co-Authored-By: Claude Opus 5.5 --- docs/kin/DESIGN.md | 58 ++--- docs/kin/KT.md | 50 ++-- docs/kin/PLAN.md | 28 +-- docs/kin/specs/approvals.md | 358 ++++++++-------------------- docs/kin/specs/lead.md | 218 ++++++----------- docs/kin/specs/mobile.md | 2 +- docs/kin/specs/triggers.md | 272 +++++++-------------- docs/operations/kin-memory-purge.md | 2 +- docs/user/kin.md | 9 +- ops/kin/host/README.md | 188 ++------------- ops/kin/host/retire-workers.sh | 122 ++++++++++ ops/kin/host/update.sh | 20 +- ops/kin/memory-repo/README.md | 2 +- 13 files changed, 479 insertions(+), 850 deletions(-) create mode 100755 ops/kin/host/retire-workers.sh diff --git a/docs/kin/DESIGN.md b/docs/kin/DESIGN.md index 946d64cde3ad8..1ff1d39717bbb 100644 --- a/docs/kin/DESIGN.md +++ b/docs/kin/DESIGN.md @@ -31,7 +31,6 @@ Non-goals: | Need | T3 piece | | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Hand work to Claude Code or Codex in a worktree | `delegate_task` | -| Reacting to GitHub | `schedule_task` with a `webhook` trigger: signature check, dedupe, body filters, a relay that holds requests for up to 24 h while offline | | Routines and watchdogs | `fixed_time` and `interval` triggers | | Deferrals | `once` trigger (`runAt`), thread snooze (`snoozedUntil`) | | PR follow-up | `watch_pull_request`, linked PRs on threads | @@ -141,14 +140,14 @@ recheck: still open, nobody else on it The router owns one agenda across teams. It wakes the right lead, spreads big starts out by priority and plan headroom, and flags conflicts between teams before they land. -| Kind | Trigger | -| ------------------------------------------------------------------ | --------------------------------------------- | -| Routines (morning brief, evening summary, weekly memory pass) | `fixed_time` | -| GitHub events | `webhook` | -| Deferrals and reminders | `once` | -| Conditions ("when #212 merges") | `webhook` + filters | -| Watchdogs (stale review, promise past its date, objective at risk) | `interval` sweep comparing memory with GitHub | -| Follow-ups | A deferral created automatically by a ping | +| Kind | Trigger | +| ------------------------------------------------------------------ | ---------------------------------------------- | +| Routines (morning brief, evening summary, weekly memory pass) | `fixed_time` | +| GitHub events | The owner's watch: a poll of his watched repos | +| Deferrals and reminders | `once` | +| Conditions ("when #212 merges") | The watch + filters | +| Watchdogs (stale review, promise past its date, objective at risk) | `interval` sweep comparing memory with GitHub | +| Follow-ups | A deferral created automatically by a ping | Pinging people: at most one ping per person per item per day, then escalate to the owner. Batch each person's pings into one message, respect quiet hours, and always include a concrete next step. @@ -177,21 +176,23 @@ A click posts a structured message, which the lead acts on under its permissions ### 9.1 Action classes -| Class | Examples | Who can trigger it | -| ---------- | ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | -| Read | Answer a question, summarise a PR | Any member | -| Talk | Comment, ping, post a widget | Any member, through the lead | -| Work | Start a worker, push a branch, open a draft PR | Members within what the chat allows; the owner always | -| Privileged | Merge, deploy, release, delete a branch, change permissions or `rules.md`, spend money, use a secret | **Owner only, with a signed approval** | +| Class | Examples | Who can trigger it | +| ---------- | -------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | +| Read | Answer a question, summarise a PR | Any member | +| Talk | Comment, ping, post a widget | Any member, through the lead | +| Work | Start a worker, push a branch, open a draft PR | Members within what the chat allows; the owner always | +| Privileged | Change a lead's level, permissions or `rules.md`; later deploy, release, spend money, use a secret | **Owner only, with a signed approval** | -Privileged actions are **not tools any agent has**. The agent's only tool is `request_action({kind, target})`. It creates a pending action that the **action executor**, a server service, carries out after a valid approval. +Privileged actions are **not tools any agent has**, and no agent can request one. The owner asks from his own session; that creates a pending action, which the **action executor**, a server service, carries out after a valid approval. + +Merging is not a Kin action. When a PR is approved and green, the lead tells the owner, and he merges it on GitHub. ### 9.2 Approvals are signed and bound to one action -- The owner's approval is a **grant** for one action: repo, PR number, **head SHA**, base branch and merge method. It is single-use and expires after 15 minutes. +- The owner's approval is a **grant** for one action: its server-chosen target and a nonce the server rotates when that target's facts change. It is single-use and expires after 15 minutes. - It is signed by the owner's device key: a DPoP-style key in the Secure Enclave or Keystore, unlocked by Face ID or a fingerprint for privileged actions. -- At run time the executor checks the signature, that the signer has the owner role, and that **the PR head still matches the SHA.** A new commit after approval voids the grant. -- Approval cards for privileged actions are **native cards drawn from the server's pending action**: repo, PR, SHA, diff size, checks. Never agent HTML, so an agent can't draw a button that does something other than what it says. +- At run time the executor checks the signature, that the signer still has the owner role, and that the grant matches the action as it stands. +- Approval cards for privileged actions are **native cards drawn from the server's pending action**. Never agent HTML, so an agent can't draw a button that does something other than what it says. ### 9.3 Group members can't approve for you @@ -206,14 +207,13 @@ Treat everything not written by the owner as untrusted data: messages from membe - **Provenance ceiling:** each task records who started it. Work started by Priya's message runs with Priya's permissions at most, and the ceiling carries into the task's workers. An injected instruction can only reach what its author could reach. - **Briefs quote, they don't obey:** member text reaches agents inside clearly marked quoted blocks, labelled with the author's role. - **No changes to the rules from chat:** permissions, `rules.md` and delegations change only through owner-signed actions. A member writing "remember: Priya can approve merges" is stored as a claim from Priya, never as a rule. -- **Workers touching untrusted input run cut down:** no secrets, network limited to an allowlist (GitHub and model APIs), fine-grained tokens. -- **Watch for suspicious requests:** when a privileged request follows a non-owner message, the approval card says so ("Asked for after Priya's message"), so the owner sees it coming. +- **Turns that touch untrusted input run cut down:** a shared turn, or one that has read outside text, gets no shell and so no GitHub login; each Kin tool call is still checked against who started the turn. ### 9.5 Credentials -- Agents never hold the owner's GitHub token. Agents act as a **GitHub App** (the bot): it comments, pushes to non-protected branches, and opens PRs. It has no merge permission on protected branches. -- The executor holds the owner's merge credential in the OS keychain, and uses it only to carry out a signed grant. -- **GitHub stays the last line of defence:** branch rulesets on `main` require one approving review from a code owner (the owner) and block the bot from approving its own PRs. Even a fully compromised Kin can't merge without the owner's real approval on GitHub. +- Kin has no GitHub identity of its own. The owner connects his own GitHub login from the phone (Settings → Connections → GitHub). An owner-only turn that has read nothing from outside gets a shell with `gh` under that login; Kin's GitHub tools and its watch use it too. Signing out stops all of it. +- What an agent posts on GitHub goes out under the owner's name, so `gh` in its shell signs it with the agent's name. +- **Kin never merges code.** What reaches a code repo's default branch is the owner's own merge, under whatever branch protection he sets on GitHub. The one exception is Kin's memory repo: Kin lands its own memory PRs with his login once `memory-check` passes, and only on paths `CODEOWNERS` leaves to Kin. ### 9.6 Delegation @@ -262,7 +262,7 @@ Owner-only approval has a gap: when the owner is on a flight and production is d - **The owner names them,** one or two people, with an owner-signed entry like any delegation (section 9.6). It's listed in settings as "Next of kin" and can be revoked in one tap. Nobody can name themselves, and a chat message can't name anyone. - **It only starts after a wait.** A privileged request has to go unanswered for a set time (2 hours by default), or the owner has to have marked themselves away. The owner is warned first: "No answer on the rollback. Asking Priya in 30 minutes." Any answer from the owner cancels the handover. - **The scope is small.** By default the next of kin can only undo things: revert a merge, roll back a deploy, pause routines and deferrals. They can't change permissions or `rules.md`, spend money, use secrets, or name another next of kin. The owner can widen it per repo, for example to merge PRs labelled `hotfix`. -- **The next of kin approves on their own device,** with the same signed, single-use grant as the owner (section 9.2). On GitHub they have to be a code owner too, or the branch ruleset still blocks the merge. +- **The next of kin approves on their own device,** with the same signed, single-use grant as the owner (section 9.2). - **The owner sees everything** when they're back: one summary in their direct chat listing each action, who approved it, and an undo button where undo is possible. - **Kin never acts alone.** If nobody answers, the request waits. A next of kin is a person, never an agent. @@ -308,7 +308,7 @@ A partner, such as a consultant, sets up and runs Kin for a client that can't do ## 11. Phases (each one works on its own) -1. **Direct chat:** chat contracts and service; mobile chat list and direct chat; task, approval and deferral cards; the lead and its memory; morning and evening routines; GitHub webhooks; deferrals on `once`; the action executor, signed grants, the GitHub App, and branch rulesets. The lead works on `GLDRoger/t3code`, with memory in `GLDRoger/kin-memory`. +1. **Direct chat:** chat contracts and service; mobile chat list and direct chat; task, approval and deferral cards; the lead and its memory; morning and evening routines; GitHub events; deferrals on `once`; the action executor and signed grants. The lead works on `GLDRoger/t3code`, with memory in `GLDRoger/kin-memory`. 2. **First group:** lead + QA; roles and provenance ceilings; floor manager; decision cards and polls; generated widgets; notification actions beyond deferrals (phase 1 already has deferral and Review actions). 3. **Teams and router:** more teams; the router and its agenda; cross-team requests; live widgets, Live Activities, pinned dashboards; delegations and next of kin (section 9.9). 4. **Front doors:** an MCP hub so ChatGPT, Grok and Claude.ai reach the same leads and widgets, with the same section 9 rules. @@ -324,10 +324,10 @@ A partner, such as a consultant, sets up and runs Kin for a client that can't do Fix in code: -1. **One lead writing at a time** (phase 1). Two events at once would start two lead sessions writing memory together. One queue per organization; events arriving within a short window merge into one wake-up, so 20 webhook events from one push cost one session. +1. **One lead writing at a time** (phase 1). Two events at once would start two lead sessions writing memory together. One queue per organization; events arriving within a short window merge into one wake-up, so 20 GitHub events from one push cost one session. 2. **Cost of each wake-up** (phase 1). Choose the lead's model, cache the fixed part of its prompt (rules, `INDEX.md`), and set a daily budget. When it runs low: the owner's messages first, then due deferrals, then chasing, with dreaming last. 3. **A stop button** (phase 1). One switch, in settings and on the lock screen, that pauses every lead, routine and worker in an organization at once. -4. **Actions that run twice** (phase 1). Each pending action has an id and the executor refuses to run it twice: a restart in the middle of a merge, a replayed webhook, a deferral that fires twice. +4. **Actions that run twice** (phase 1). Each pending action has an id and the executor refuses to run it twice: a restart in the middle of a run, a deferral that fires twice. 5. **"Nothing is deleted" vs. secrets and erasure** (phase 1). Scan for secrets before each memory commit, and keep an owner-signed purge that rewrites history for one item and is recorded in the audit log. 6. **What a lead may do on its own** (phase 1). Settled on 10 Nov 2026: no ladder. A lead works fully in chats its owner placed it in, and every privileged action is signed (section 10). 7. **Upstream API drift** (phase 1). A small contract test for each T3 piece Kin depends on (`delegate_task`, triggers, `McpAppWebView`, managed policy), run after every upstream sync next to the branding drift check. @@ -347,7 +347,7 @@ None of these are planned. They're written down so they shape today's choices wi **Secrets gateway (the strongest one, and possibly earlier than the rest).** The Kin host holds the organization's secrets, and nobody else ever does, agents included. An agent or person asks for access with a purpose: "OpenAI, for the docs search project". Once the request is approved (by the owner, or automatically by organization policy), Kin issues a **gateway token** scoped to that project and purpose, with an expiry and a spending cap. Calls made with the token go through the Mac mini, which adds the real key, forwards the request and logs it. Revoking the token takes one tap and never means rotating the real key. -- It reuses section 9: the request is a `request_action`, the approval is a grant, and every use goes in the audit log. +- It reuses section 9: the request is a pending action, the approval is a grant, and every use goes in the audit log. - It also fixes a phase 1 problem: today agents inherit the machine's credentials (see the lead and approvals specs). With the gateway, workers get tokens instead of keys. - It works for HTTP APIs whose SDKs accept a different base URL, such as OpenAI, Anthropic and most model APIs. Database passwords and SSH keys need short-lived credentials instead, which is a different problem. - Use proven parts instead of building them: an LLM proxy with virtual keys and per-key budgets, and an open-source secrets manager for storage. Check the current options before choosing. diff --git a/docs/kin/KT.md b/docs/kin/KT.md index f44fe48570c9d..e1937b2fddd55 100644 --- a/docs/kin/KT.md +++ b/docs/kin/KT.md @@ -14,34 +14,34 @@ In one line: Kin is a messaging app, built on [T3 Code](https://github.com/pingd All Kin work is on branch `kin` of `GLDRoger/t3code`, a public fork. `main` mirrors upstream; never commit to it. [KIN.md](../../KIN.md) has the branch, sync and branding rules. -| Where | What | -| ---------------------------------- | ---------------------------------------------------------------------------------------- | -| `apps/server/src/kin/chat/` | Chats, messages, members, identity, the live hub, task cards, chat RPCs | -| `apps/server/src/kin/floor/` | Who may speak: `FloorManager` (pure rules) and `KinFloor` (runs and grants in SQLite) | -| `apps/server/src/kin/lead/` | The event queue, wake-up runner, prompt, permissions, budget, stop switch, workers, CLI | -| `apps/server/src/kin/reply/` | The reply bridge (lead text → chat messages) and presence ("thinking", "working") | -| `apps/server/src/kin/memory/` | Memory reads, the git writer, change cards and memory PRs | -| `apps/server/src/kin/dreaming/` | The nightly dream | -| `apps/server/src/kin/triggers/` | Time triggers, deferrals, routines, watchdogs, pings, GitHub webhooks, the trigger inbox | -| `apps/server/src/kin/approvals/` | `request_action`, pending actions, approver keys, grant checks, the executor, audit | -| `apps/server/src/kin/github/` | The GitHub App, rulesets and the owner's merge client | -| `apps/server/src/kin/push/` | Kin's own APNs sender | -| `apps/server/src/kin/persistence/` | Kin's migration track (`kin_sql_migrations`, K001 onward) | -| `apps/server/src/kin/mcp/` | The `/kin/mcp` endpoint that only registered agent threads get | -| `packages/contracts/src/kin*.ts` | Schemas shared by server and clients | -| `packages/client-runtime/src/kin/` | Client logic shared by web and mobile | -| `apps/mobile/src/features/chats/` | The mobile app's Kin screens | -| `apps/web/src/kin/` | The web and desktop Kin screens | -| `ops/kin/host/` | Host install, update, backup and restore | +| Where | What | +| ---------------------------------- | --------------------------------------------------------------------------------------- | +| `apps/server/src/kin/chat/` | Chats, messages, members, identity, the live hub, task cards, chat RPCs | +| `apps/server/src/kin/floor/` | Who may speak: `FloorManager` (pure rules) and `KinFloor` (runs and grants in SQLite) | +| `apps/server/src/kin/lead/` | The event queue, wake-up runner, prompt, permissions, budget, stop switch, workers, CLI | +| `apps/server/src/kin/reply/` | The reply bridge (lead text → chat messages) and presence ("thinking", "working") | +| `apps/server/src/kin/memory/` | Memory reads, the git writer, change cards and memory PRs | +| `apps/server/src/kin/dreaming/` | The nightly dream | +| `apps/server/src/kin/triggers/` | Time triggers, deferrals, routines, watchdogs, pings, GitHub readers, the trigger inbox | +| `apps/server/src/kin/approvals/` | Pending actions, approver keys, grant checks, the executor, audit | +| `apps/server/src/kin/github/` | The owner's GitHub watch, its triggers, signed replies and `kin_github_*` tools | +| `apps/server/src/kin/push/` | Kin's own APNs sender | +| `apps/server/src/kin/persistence/` | Kin's migration track (`kin_sql_migrations`, K001 onward) | +| `apps/server/src/kin/mcp/` | The `/kin/mcp` endpoint that only registered agent threads get | +| `packages/contracts/src/kin*.ts` | Schemas shared by server and clients | +| `packages/client-runtime/src/kin/` | Client logic shared by web and mobile | +| `apps/mobile/src/features/chats/` | The mobile app's Kin screens | +| `apps/web/src/kin/` | The web and desktop Kin screens | +| `ops/kin/host/` | Host install, update, backup and restore | Kin code lives in its own files. Upstream files get a hook of a line or two at most, so upstream merges stay easy. ## How a message flows 1. **Chat.** A client calls `kin.messages.send`. `KinChatService` checks membership, stores the message with the next sequence number, and calls `KinFloor.open`, which opens a floor run and grants a turn. In a direct chat that is the lead; in a group it is the mentioned agent, and with no mention it will be the group's lead (W3-1). After commit, `KinChatHub` publishes the message to every member's stream. -2. **Queue.** `ChatWake` turns the message into a `chat.message` event in `KinEventQueue` (`kin_events`) and shows the lead's working line ("Catching up", or "Finishing something else" behind a running wake-up) at once. Triggers, worker reports and approval results become events the same way. Code sets each event's priority; an owner message is P0. +2. **Queue.** `ChatWake` turns the message into a `chat.message` event in `KinEventQueue` (`kin_events`) and shows the lead's working line ("Catching up", or "Finishing something else" behind a running wake-up) at once. Triggers, finished tasks and approval results become events the same way. Code sets each event's priority; an owner message is P0. 3. **Wake-up.** `WakeupRunner` waits briefly for a burst to finish, then claims a batch of events for one lead and one chat. It checks the stop switch and budget, prepares a read-only memory checkout, builds the prompt (`LeadPrompt`) and runs the lead as a T3 thread. A message that arrives during a wake-up is steered into it. -4. **Lead.** The lead runs on Claude with no shell. It acts only through Kin's MCP tools: memory, deferrals, workers, cards, `request_action`. Its plain text is its reply. +4. **Lead.** The lead acts through Kin's MCP tools: memory, deferrals, cards, Work. In a turn only the owner reads that has read nothing from outside, it also gets a shell (with the owner's GitHub login) and T3's `delegate_task`. Its plain text is its reply. 5. **Reply bridge.** `KinReplyBridge` reads the lead's text as it streams and posts it through `LevelGate`, so membership, the floor and permissions apply. 6. **Clients.** Members' streams deliver the reply, and `KinPushSender` pushes it to phones that aren't showing the chat. @@ -53,17 +53,17 @@ Memory is plain Markdown files with front matter in a private git repo per organ ## Dreams -Once a night per organization, `DreamRunner` collects the day's originals (journal, chat messages, worker reports, GitHub events) and runs an isolated lead session in dream mode on a scratch checkout. It merges duplicates, supersedes stale items and lists contradictions, which a second turn on the same model turns into a resolution or a question for the owner. Code checks every change (schema, sources, no deletions, secret scan) before the result goes to a `dream/` branch for the owner to approve. The morning routine uses it for the brief. See the [triggers spec, "Dreaming pipeline"](specs/triggers.md#dreaming-pipeline-one-per-org-per-night). +Once a night per organization, `DreamRunner` collects the day's originals (journal, chat messages, finished tasks, GitHub events) and runs an isolated lead session in dream mode on a scratch checkout. It merges duplicates, supersedes stale items and lists contradictions, which a second turn on the same model turns into a resolution or a question for the owner. Code checks every change (schema, sources, no deletions, secret scan) before the result goes to a `dream/` branch for the owner to approve. The morning routine uses it for the brief. See the [triggers spec, "Dreaming pipeline"](specs/triggers.md#dreaming-pipeline-one-per-org-per-night). ## Triggers -Everything that wakes a lead without a chat message goes through one inbox (`kin_trigger_inbox`) into the event queue. Time triggers (deferrals, morning and evening routines, watchdogs that chase stale items) run on T3's scheduler in the owner's time zone. GitHub webhooks arrive verified and deduplicated by delivery id. A deferral is a memory item with a due time and an `on_due` of remind, start, ask or chase; the lead creates one with `kin_defer`. See the [triggers spec](specs/triggers.md). +Everything that wakes a lead without a chat message goes through one inbox (`kin_trigger_inbox`) into the event queue. Time triggers (deferrals, morning and evening routines, watchdogs that chase stale items) run on T3's scheduler in the owner's time zone. GitHub activity comes from the owner's watch, which polls his watched repos with his own login and wakes a lead on a `/kin` call or a review request. A deferral is a memory item with a due time and an `on_due` of remind, start, ask or chase; the lead creates one with `kin_defer`. See the [triggers spec](specs/triggers.md). ## Approvals -Authority never passes through a model. A lead can only propose a privileged action (merge, enrol a key) with `request_action`, which stores a pending action bound to an exact target, such as a PR at a pinned head SHA. The owner's phone shows an approval card and signs a single-use grant with a hardware key behind Face ID. `ActionExecutor` checks the grant and runs the action with an executor-held credential, then writes a hash-chained audit row. Chat text, including "approved", never counts. See the [approvals spec](specs/approvals.md). +Authority never passes through a model. No agent can request a privileged action. The owner asks from his own session (raising a lead's level), which stores a pending action bound to an exact target. The owner's phone shows an approval card and signs a single-use grant with a hardware key behind Face ID. `ActionExecutor` checks the grant and runs the action, then writes a hash-chained audit row. Kin never merges: the lead says when a PR is ready and the owner merges it. Chat text, including "approved", never counts. See the [approvals spec](specs/approvals.md). -A lead just works in chats its owner placed it in (its DM, the owner's groups): posts, workers, draft PRs. There is no ladder and the owner never sees a level. An internal gate (`KinLevels`) refuses the lead in any other chat, so members can't widen what it does; only an owner-signed `set_level` changes it. See [DESIGN.md section 10](DESIGN.md#10-permissions) and the [lead spec, "Permissions"](specs/lead.md#permissions-design-10). +A lead just works in chats its owner placed it in (its DM, the owner's groups): posts, delegated tasks, PRs. There is no ladder and the owner never sees a level. An internal gate (`KinLevels`) refuses the lead in any other chat, so members can't widen what it does; only an owner-signed `set_level` changes it. See [DESIGN.md section 10](DESIGN.md#10-permissions) and the [lead spec, "Permissions"](specs/lead.md#permissions-design-10). ## Running Kin locally diff --git a/docs/kin/PLAN.md b/docs/kin/PLAN.md index 9e3056bfc72ff..1b2e5bb4d7465 100644 --- a/docs/kin/PLAN.md +++ b/docs/kin/PLAN.md @@ -33,12 +33,12 @@ The road from today's Kin to [VISION.md](VISION.md), in waves. The task ids (CHA Start W1-2 after W0-3, since both edit `apps/mobile/src/features/chats/**`. W1-1 and W1-3 both edit `docs/kin/specs/lead.md`, and W1-3 lands second. -| Task | Goal | Acceptance | -| --------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| W1-1 ★ Worker isolation | A worker can't read Kin's state, the memory key or the executor's credentials | The GitHub App key and the owner's merge credential are unreadable from a worker's shell (transcript); holds for workers of several leads at once; the `workerLaunchReady` seam is deleted | -| W1-2 ★ Phone approvals | Enrol a key, see an approval card, sign with Face ID | Works for `merge_pull_request`, `set_level` and key enrolment. The card names who asked when the request came from below the owner | -| W1-3 ★ Many leads | A lead per domain | A second and third lead can be created from the CLI and from an owner-only RPC through one service method that takes the creating person and their ceiling; a non-owner session is refused. Each lead has a domain and a charter only the owner can change. A lead works at L2 in its owner's DM. Group rules load only for group wake-ups. Routines, budget notices and dreams name the right lead; budget stays one daily figure per org, with use shown per lead | -| W1-4 Delegation end to end (gate) | The whole loop works on the host and the phone | From the iPhone: ask Tech lead for a small change; a worker starts; the task card updates in place; the report wakes the lead; a draft PR exists; the approval card arrives; Face ID; merged at the pinned SHA; audit row present. A push after approval voids it | +| Task | Goal | Acceptance | +| --------------------------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| W1-1 ★ Who gets a shell | Only a turn the owner alone reads gets a shell, as the owner on GitHub | A shared turn, a turn that read outside text, and a task delegated from either get no shell (tests); Kin workers, the worker environment and the GitHub App are deleted, with nothing left on the host (`retire-workers.sh`) | +| W1-2 ★ Phone approvals | Enrol a key, see an approval card, sign with Face ID | Works for `set_level` and key enrolment. The card names who asked when the request came from below the owner | +| W1-3 ★ Many leads | A lead per domain | A second and third lead can be created from the CLI and from an owner-only RPC through one service method that takes the creating person and their ceiling; a non-owner session is refused. Each lead has a domain and a charter only the owner can change. A lead works at L2 in its owner's DM. Group rules load only for group wake-ups. Routines, budget notices and dreams name the right lead; budget stays one daily figure per org, with use shown per lead | +| W1-4 Delegation end to end (gate) | The whole loop works on the host and the phone | From the iPhone: ask Tech lead for a small change; a delegated task starts; the task card updates in place; its end wakes the lead; a PR exists; the lead says when it is approved and green; the owner merges it | ## Wave 2: a company of leads, one list, one switcher @@ -79,7 +79,7 @@ W5-1 lands a contract-only PR first. Then W5-1, W5-2 and W5-3 run together, then | W5-6 ★ Member-created leads | A member creates their own lead | A member creates a lead through the form (name, domain, charter, model) on the main host. Its authority is capped at the creating member's, never the group's (test) | | W5-5 First teammate, live (gate) | Two real people, two phones, one week | The teammate joins by invite, shares a group with the owner and two leads, and asks a lead for a change the owner approves. The hostile-member checklist passes from the teammate's device | -**Before W5-5:** decide who pays for a teammate's requests and for member-created leads, and confirm the separate executor user from W1-1. +**Before W5-5:** decide who pays for a teammate's requests and for member-created leads,. ### ▶ Milestone: usable daily by the owner and the first teammate @@ -89,12 +89,12 @@ Measured over one week at the end of wave 5: both people use Kin every working d Server work in separate folders, so any task can move into an idle server slot from wave 3 on. -| Task | Goal | Acceptance | -| ------------------------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| W6-1 GitHub awareness | PR and CI events reach the right chat, without noise | An event goes to the lead whose projects include the repo; a failed CI run on a watched PR is one useful message; routine pushes are silent; under 10 notices a day | -| W6-2 Dreams and briefs for many leads | A week of dreams and briefs worth reading | Seven nightly dreams in a row complete on the host. Each lead with something to say sends one morning message; the chief of staff sends one digest across leads | -| W6-3 Chief of staff as router | "Tell whoever handles this" works | The chief of staff hands a message to the right lead word for word, keeping author and provenance. One agenda across leads flags two leads planning the same thing | -| W6-4 Voice and images | Talk to Kin; send a screenshot | Works in DMs and groups | +| Task | Goal | Acceptance | +| ------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| W6-1 GitHub awareness | PR and CI events reach the right chat, without noise | A `/kin` call or a review request on a watched repo wakes the right lead; a failed CI run on a watched PR is one useful message; routine pushes are silent; under 10 notices a day | +| W6-2 Dreams and briefs for many leads | A week of dreams and briefs worth reading | Seven nightly dreams in a row complete on the host. Each lead with something to say sends one morning message; the chief of staff sends one digest across leads | +| W6-3 Chief of staff as router | "Tell whoever handles this" works | The chief of staff hands a message to the right lead word for word, keeping author and provenance. One agenda across leads flags two leads planning the same thing | +| W6-4 Voice and images | Talk to Kin; send a screenshot | Works in DMs and groups | ## Wave 7: team depth @@ -131,6 +131,6 @@ Kin is done when all of these hold for four straight weeks: ## Waiting on the owner -- **The GitHub App:** creating and installing it needs the owner's GitHub sign-in. Blocks the merge in W1-4 and all of W6-1. +- **GitHub on the host:** the owner connects his GitHub from the phone (Settings → Connections → GitHub). Needed for W1-4 and W6-1. - **One paid eval run,** now with group cases. - **Teammate cost:** decided before W5-5. diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index c8fc1ba52c70e..3c94ad09129a1 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -1,27 +1,28 @@ # Spec: approvals, grants and the action executor -Owner of: `KinPendingAction`, `request_action`, `KinGrant`, `KinApproverKey`, the action executor, `KinAuditEntry`, the GitHub App and branch rulesets. +Owner of: `KinPendingAction`, `KinGrant`, `KinApproverKey`, the action executor and `KinAuditEntry`. Covers DESIGN.md section 9.1–9.7 and 10 (phase 1), 9.6 and 9.9 (phase 3), 9.8 (phase 5), and section 12 code gap 4 (actions that run twice). ## Goal -An agent can only propose a privileged action. Code carries it out only after a valid, owner-signed grant bound to that exact action, at most once. Nothing typed in a chat, drawn by an agent, or sent by a member's client can become the owner's approval. GitHub's own rules still block a merge if every part of Kin is compromised. +An agent can only propose a privileged action. Code carries it out only after a valid, owner-signed grant bound to that exact action, at most once. Nothing typed in a chat, drawn by an agent, or sent by a member's client can become the owner's approval. + +Kin doesn't merge code. Agents work on GitHub with the owner's own `gh` login from an owner-only turn's shell (lead spec); when a PR is approved and green, the lead tells the owner, and he merges it himself. ## What exists in T3 -| Piece | Path | What it gives us | What it doesn't | -| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| DPoP proof verification | `packages/shared/src/dpop.ts` (`verifyDpopProof`, `computeDpopJwkThumbprint`), `apps/server/src/auth/dpop.ts` (`verifyRequestDpopProof`) | ES256 over P-256 with `@noble/curves`, RFC 7638-style thumbprint, ±300 s clock window (`DPOP_MAX_CLOCK_SKEW_SECONDS`), replay markers keyed by `thumbprint:jti` via `ServerSecretStore.create` (fails if the marker exists) | Binds a key to an HTTP request, not to an action. The key comes from the proof header itself. | -| Session binding | `apps/server/src/auth/SessionStore.ts` (`SessionClaims.jkt`), `EnvironmentAuth.ts` (rejects a DPoP-bound token without a matching proof) | A session can be bound to one device key | Sessions carry `scopes`, not a person or a role. `sub` is a label such as `"browser"`. | -| RPC scopes | `apps/server/src/auth/RpcAuthorization.ts` (`RPC_REQUIRED_SCOPES` `satisfies Record`), scopes in `packages/contracts/src/auth.ts` | Every WS RPC must declare a scope, or typecheck fails | Scopes are per device session, not per person. No role concept. | -| Session list and revoke | `apps/server/src/auth/http.ts` (`revokeClient`, `revokeOtherClients`, need `access:write`) | The owner can revoke device sessions | Nothing about signing keys. | -| Mobile device key | `apps/mobile/src/features/cloud/dpop.ts` (`loadOrCreateDpopProofKeyPair`) | A P-256 key for the managed relay | **Software key.** Generated in JS with `@noble/curves`, private JWK stored with `expo-secure-store` under `t3code.cloud.dpop-proof-key`, no biometric gate, used only for the managed relay. | -| Secret files | `apps/server/src/auth/ServerSecretStore.ts` (`get`, `set`, `create`, `getOrCreateRandom`, `remove`) | Atomic create-if-absent | Files under `secretsDir`, not the OS keychain. | -| OS keychain | `@napi-rs/keyring` ^1.3.0, already in `apps/server/package.json` but unused by server code; the desktop's `ChromiumKeys.ts` loads it lazily (`AsyncEntry`). Kin wraps it in `apps/server/src/kin/github/Keychain.ts` | Read and write OS keychain items from the server | — | -| GitHub merge | `packages/source-control-github/src/server/GitHubPullRequestApi.ts` (`runAction` → GraphQL `MergePullRequest`), reached through `PullRequestService.runAction` with `PullRequestActionInput` (`packages/contracts/src/pullRequest.ts`) | Merge with method `merge`/`squash`/`rebase` | **Doesn't pin the head.** `expectedHeadOid` is sent only when the merge body is rewritten. Merge-queue repos switch to auto-merge. The credential is whatever `GitHubRequestPolicy.credential` picks: a Settings token, T3's own GitHub App sign-in (user-to-server), `GH_TOKEN`, or `gh`. | -| Agent tools | `apps/server/src/mcp/McpHttpServer.ts` (`layerTools`, `toolkitRegistration`), `McpInvocationContext.ts` (`McpThreadCaller`, `McpClientCaller`) | MCP tools for threads, with the calling thread id | `layerTools` is advertised to every thread, and `AgentContextBudget.test.ts` measures it. | -| Persistence | `apps/server/src/persistence/Migrations.ts` (Effect `Migrator.fromRecord`, table `effect_sql_migrations`, numbered files up to `080_`) | SQLite with migrations | Upstream numbering; Kin can't add numbered files without merge conflicts. | -| Canonical JSON | `packages/shared/src/relaySigning.ts` (`stableStringify`, code-unit key order) | Stable bytes to sign | — | +| Piece | Path | What it gives us | What it doesn't | +| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| DPoP proof verification | `packages/shared/src/dpop.ts` (`verifyDpopProof`, `computeDpopJwkThumbprint`), `apps/server/src/auth/dpop.ts` (`verifyRequestDpopProof`) | ES256 over P-256 with `@noble/curves`, RFC 7638-style thumbprint, ±300 s clock window (`DPOP_MAX_CLOCK_SKEW_SECONDS`), replay markers keyed by `thumbprint:jti` via `ServerSecretStore.create` (fails if the marker exists) | Binds a key to an HTTP request, not to an action. The key comes from the proof header itself. | +| Session binding | `apps/server/src/auth/SessionStore.ts` (`SessionClaims.jkt`), `EnvironmentAuth.ts` (rejects a DPoP-bound token without a matching proof) | A session can be bound to one device key | Sessions carry `scopes`, not a person or a role. `sub` is a label such as `"browser"`. | +| RPC scopes | `apps/server/src/auth/RpcAuthorization.ts` (`RPC_REQUIRED_SCOPES` `satisfies Record`), scopes in `packages/contracts/src/auth.ts` | Every WS RPC must declare a scope, or typecheck fails | Scopes are per device session, not per person. No role concept. | +| Session list and revoke | `apps/server/src/auth/http.ts` (`revokeClient`, `revokeOtherClients`, need `access:write`) | The owner can revoke device sessions | Nothing about signing keys. | +| Mobile device key | `apps/mobile/src/features/cloud/dpop.ts` (`loadOrCreateDpopProofKeyPair`) | A P-256 key for the managed relay | **Software key.** Generated in JS with `@noble/curves`, private JWK stored with `expo-secure-store` under `t3code.cloud.dpop-proof-key`, no biometric gate, used only for the managed relay. | +| Secret files | `apps/server/src/auth/ServerSecretStore.ts` (`get`, `set`, `create`, `getOrCreateRandom`, `remove`) | Atomic create-if-absent | Files under `secretsDir`, not the OS keychain. | +| OS keychain | `@napi-rs/keyring` ^1.3.0, in `apps/server/package.json`; the desktop's `ChromiumKeys.ts` loads it lazily (`AsyncEntry`). Kin doesn't use it | Read and write OS keychain items from the server | — | +| Agent tools | `apps/server/src/mcp/McpHttpServer.ts` (`layerTools`, `toolkitRegistration`), `McpInvocationContext.ts` (`McpThreadCaller`, `McpClientCaller`) | MCP tools for threads, with the calling thread id | `layerTools` is advertised to every thread, and `AgentContextBudget.test.ts` measures it. | +| Persistence | `apps/server/src/persistence/Migrations.ts` (Effect `Migrator.fromRecord`, table `effect_sql_migrations`, numbered files up to `080_`) | SQLite with migrations | Upstream numbering; Kin can't add numbered files without merge conflicts. | +| Canonical JSON | `packages/shared/src/relaySigning.ts` (`stableStringify`, code-unit key order) | Stable bytes to sign | — | No module in `apps/mobile/package.json` creates Secure Enclave or Keystore keys, and `expo-local-authentication` isn't a dependency. Local native modules live in `apps/mobile/modules/` (for example `t3-native-controls` with `expo-module.config.json`) and are autolinked from that folder. @@ -34,14 +35,14 @@ No module in `apps/mobile/package.json` creates Secure Enclave or Keystore keys, export const KinActionClass = Schema.Literals(["read", "talk", "work", "privileged"]); export const KinActionKind = Schema.Literals([ - // phase 1, executed here + // retired with the GitHub App: no handler, so an approved one is voided "merge_pull_request", "delete_branch", - // phase 1, executed by other specs' handlers through the registry (section 6) + // executed through the registry (section 6); only set_level has a handler today "set_level", // lead spec: what a lead may do, per lead and chat "change_rules", // lead spec: rules.md, bound to the new file's hash "memory_purge", // triggers spec: history rewrite for one item - "register_approver_key", // this spec: a second device + "register_approver_key", // replaced by registerKey (section 4); voided if approved // later "deploy", "release", @@ -53,25 +54,13 @@ export const KinActionKind = Schema.Literals([ ]); ``` -`classOf(kind)` returns `privileged` for every kind above. Read, Talk and Work stay with the lead spec's level checks (`delegate_task`, posting, pushing a branch); `request_action` handles only privileged kinds. `ceilingAllows(provenance, class, level)` (section 8) is exported for the lead spec to use on Work. +`classOf(kind)` returns `privileged` for every kind above. Read, Talk and Work stay with the lead spec's level checks (`delegate_task`, posting, pushing a branch). `ceilingAllows(provenance, class, level)` (section 8) is exported for the lead spec to use on Work. -### 2. `request_action`: the agent's only privileged tool +### 2. Who can ask -```ts -request_action({ - kind: KinActionKind, - target: KinActionTarget, // tagged by kind, below - reason: string, // ≤ 500 chars, shown quoted on the card, never trusted - sourceEventId: KinEventId, // the event in the current wake-up that led here -}) -> { actionId, state: "awaiting_approval" | , waitingOn: "owner" } -``` +No agent tool creates a pending action. The only requester is the owner, through owner-only RPCs: `kin.levels.raise` creates `set_level` under the reserved requester `kin-promotion`, and `KinPendingActions.create` refuses `set_level` from any other requester. The server fills the target's facts itself; the client names the lead, chat and level, never a digest or nonce. -- Served on the Kin-only `/kin/mcp` endpoint (chat spec, CHAT-7) by its own toolkit in `apps/server/src/kin/approvals/mcp.ts`, next to the chat toolkit. It is not added to upstream `layerTools`, so ordinary T3 threads never see it and `AgentContextBudget.test.ts` doesn't change. A lead's thread lists the chat tools plus exactly one approvals tool, `request_action`. -- The tool is listed only for registered Kin agent threads, so `McpClientCaller` (outside OAuth clients), subagents and worker or ordinary threads never reach the handler. The handler takes the caller only from `KinIdentity.resolveAgent` and refuses with `not_a_lead` unless that agent has the `lead` role and a `kin_leads` row and is in a running wake-up. -- The server, not the agent, fills everything else: `orgId` from the caller, `provenance` from the claimed events of the caller's running wake-up (`sourceEventId` must be one of them, else `invalid_state`), and the PR's head SHA, base, title, diff size and checks from GitHub. The agent names a PR; it can't name a SHA, and undeclared input fields are dropped. -- The named repo must match one of the lead's worker projects' repositories, case-insensitively, and is stored in that project's spelling, so `ACME/app` and `acme/app` are one action. T3's GitHub credential can read more than the lead's repos, so this is the boundary. An unlisted repo and a missing PR get the same `not_found`, so the tool can't probe for private repos. -- `request_action` accepts a kind only when it can resolve that kind's target itself. Today that is `merge_pull_request` alone; every other kind fails `unsupported_kind` (after the owner-only check in section 8), even where the executor has a handler (`delete_branch`, `register_approver_key`), until the server can resolve its target. -- It returns immediately. It never waits for the approval and never returns a token. +An agent that needs something only the owner can do says so in chat or asks with `kin_ask`. Its answer is a tap, never an approval. Targets: @@ -145,16 +134,16 @@ export const KinPendingAction = Schema.Struct({ Transitions (every one is a compare-and-set `UPDATE … WHERE id = ? AND state = ? AND revision = ?`; zero rows changed means someone else won and the caller stops): -| From | To | When | -| ------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| — | `awaiting_approval` | `request_action` inserts; card posted | -| `awaiting_approval` | `awaiting_approval` (revision+1, new nonce) | PR head or base changes (webhook from triggers spec, or re-read at card open) | -| `awaiting_approval` | `approved` | A grant passes every check in section 5; grant row inserted in the same transaction | -| `awaiting_approval` | `rejected` / `cancelled` / `expired` | Owner taps Reject; lead withdraws; `expiresAt` passes | -| `approved` | `executing` | Executor claims it (single claim, section 6) | -| `approved` | `voided` | Grant lapses before claim (the stop switch, a failing credential check or an unconfigured host holds it until then), key revoked, approver no longer owner, no handler | -| `executing` | `succeeded` / `failed` | GitHub answers; a precheck, credential or stop-switch failure after the claim is `failed` | -| `executing` | `succeeded` / `interrupted` | Restart finds it mid-flight; reconciliation decides (section 6) | +| From | To | When | +| ------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| — | `awaiting_approval` | An owner-only RPC inserts (section 2); card posted | +| `awaiting_approval` | `awaiting_approval` (revision+1, new nonce) | The target's live facts change when the card opens (check 9) | +| `awaiting_approval` | `approved` | A grant passes every check in section 5; grant row inserted in the same transaction | +| `awaiting_approval` | `rejected` / `cancelled` / `expired` | Owner taps Reject; lead withdraws; `expiresAt` passes | +| `approved` | `executing` | Executor claims it (single claim, section 6) | +| `approved` | `voided` | Grant lapses before claim (the stop switch or an unconfigured host holds it until then), key revoked, approver no longer owner, no handler | +| `executing` | `succeeded` / `failed` | The handler answers; a precheck or stop-switch failure after the claim is `failed` | +| `executing` | `succeeded` / `interrupted` | Restart finds it mid-flight; reconciliation decides (section 6) | Storage (new, SQLite, Kin's own migration track in `apps/server/src/kin/persistence/` (`KinMigrations.ts`, one `migrations/K00N_*.ts` file per change) with its own `Migrator` table `kin_sql_migrations`; owned with the chat spec so all Kin tables share one runner): @@ -271,7 +260,7 @@ export const KinGrantPayload = Schema.Struct({ **The card is drawn from the payload it signs.** `kin.approvals.challenge(actionId)` returns the unsigned payload (minus `jti`, `iat`, `exp`, which the device adds). The app parses it and renders repo, PR, SHA, base, method, diff size and checks from those fields and `resolved`, then signs the same bytes. There is no second copy of the facts that could drift from what is signed. `challenge` takes no org: the server looks the action up in the caller's own orgs and refuses anyone who isn't an approver (`not_owner`). For `merge_pull_request` and `delete_branch` it re-reads GitHub first and, if the head or base changed (what check 9 compares), rotates the nonce before answering. Other live facts, such as checks and diff size, are returned fresh without a rotation, so a check finishing never voids a grant check 9 would accept. `approver.kid` is the person's active key registered from this session, else their most recently confirmed one. -**The device checks what it signs.** The approval key module parses the signing input natively before it asks for a biometric, and refuses it unless: both parts are canonical `stableStringify` JSON (no whitespace, sorted keys, so no duplicate keys); the header has exactly `alg: "ES256"`, `typ: "kin-grant+jws"` and a `kid`; the payload has only the fields above, with `v: 1`, `decision: "approve"`, a `kind` the module has a prompt for, the matching `target` tag, `approver.kid` equal to the header `kid` byte for byte, `exp − iat ≤ 900` and `|deviceNow − iat| ≤ 300`. The prompt text comes from fixed per-kind templates in the module, such as `Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into "main" by squashing`, with every hash in full (the agent writes commits and content, so it could grind a value that matches a shortened hash), wrapped rather than cut. Shown values are refused, never cleaned, unless they are ASCII from a per-field allowlist (branches and paths: letters, digits, `. _ - / +`; lead and chat ids: letters, digits, `. _ -`), and a prompt over 200 characters is refused rather than cut. A kind with no template can't be signed until the module adds one. The server's checks below still apply in full. +**The device checks what it signs.** The approval key module parses the signing input natively before it asks for a biometric, and refuses it unless: both parts are canonical `stableStringify` JSON (no whitespace, sorted keys, so no duplicate keys); the header has exactly `alg: "ES256"`, `typ: "kin-grant+jws"` and a `kid`; the payload has only the fields above, with `v: 1`, `decision: "approve"`, a `kind` the module has a prompt for, the matching `target` tag, `approver.kid` equal to the header `kid` byte for byte, `exp − iat ≤ 900` and `|deviceNow − iat| ≤ 300`. The prompt text comes from fixed per-kind templates in the module, such as `Set agent "agt_…" to L2 in all chats`, with every hash in full (the agent writes commits and content, so it could grind a value that matches a shortened hash), wrapped rather than cut. Shown values are refused, never cleaned, unless they are ASCII from a per-field allowlist (branches and paths: letters, digits, `. _ - / +`; lead and chat ids: letters, digits, `. _ -`), and a prompt over 200 characters is refused rather than cut. A kind with no template can't be signed until the module adds one. The server's checks below still apply in full. `kin.approvals.submitGrant({compact})` checks, in this order, and stops at the first failure with a typed reason: @@ -283,7 +272,7 @@ export const KinGrantPayload = Schema.Struct({ 6. Pending action exists in the org, is `awaiting_approval`, and `revision` and `nonce` match → `stale` (the card refreshes), or `replayed` when the org already holds this `jti` or this approver's grant for the action. An accepted grant sent again fails here, before check 10, because its action is no longer `awaiting_approval`. 7. `kind`, `target`, `targetDigest`, `headSha`, `base`, `mergeMethod` equal the server's record → `target_mismatch`. 8. `now` is a finite number, `|now − iat| ≤ 300`, `iat < exp`, `exp − iat ≤ 900` and `now < exp` → `time_window`. -9. Re-read the PR from GitHub with the bot token; head and base still match → `head_moved` (rotate nonce, refresh card). Only `merge_pull_request` and `delete_branch` (head only) have GitHub state to re-read. If GitHub can't be read, the grant fails `unavailable`. +9. Kinds that pin a pull request's head re-read it and refuse a moved head or base with `head_moved` (rotate nonce, refresh card), or `unavailable` when it can't be read. Those kinds are retired, so no grant reaches this read today; other kinds skip it. 10. In one transaction: insert `kin_grants` (`jti` UNIQUE, `(action_id, approver)` UNIQUE) and CAS the action to `approved` while both the action and the grant are unexpired and the signing key is still `active`, attested and from an unrevoked session → `replayed` when that org already holds the `jti` or this approver's grant for the action, `revoked_key` when the key was revoked after check 2 (say, during check 9's read), `stale` otherwise. The grant's life ends at `min(exp, acceptedAt + 15 min)`. It is consumed when the executor claims the action, which needs the signing key to pass check 10's key test again, since a session revocation voids the action only on the next key read. It can't be used for anything else: the binding is to `actionId`, `nonce` and `targetDigest`, all server-chosen. @@ -309,38 +298,30 @@ interface KinActionHandler { KinExecError >; } -// c.grant: the stored KinGrant; c.payload: the signed KinGrantPayload, decoded from c.grant.compact; -// c.pass: a CredentialHygienePass from just before run, which OwnerMergeClient needs. +// c.grant: the stored KinGrant; c.payload: the signed KinGrantPayload, decoded from c.grant.compact. ``` -A `run` that can't tell whether its side effect landed (no answer, a 5xx, an unreadable 200, a defect) fails `unknown_outcome`; the executor then reconciles and never calls `run` again. Owner writes give up after 30 seconds, which counts as no answer. +A `run` that can't tell whether its side effect landed (no answer, a 5xx, an unreadable 200, a defect) fails `unknown_outcome`; the executor then reconciles and never calls `run` again. -Handlers register through `KinActionHandlers` (a Context service, built from one list in `approvals/layer.ts`). This spec ships `merge_pull_request` and `delete_branch`; the lead spec registers `set_level` and `change_rules`; the triggers spec registers `memory_purge`. `set_level` writes nothing to GitHub, so it skips the credential hygiene check (section 12). An approved action whose kind has no handler is voided (`unsupported_kind`) without a claim. On a host without the GitHub App and scope configured, `merge_pull_request` and `delete_branch` have no handler but are held instead, so their grants lapse like any other held grant. Each held action gets one audit entry per hold reason (`execution_held` with `held: not_configured`, `held: paused` and so on, or `credential_check_failed`), and when the sweep voids one whose grant lapsed while held, the owner's notice names the reason. The executor, its ledger and its handlers stay out of `approvals/layer.ts`'s output: context lookups go by key string, and that output reaches every service holding `kin.services`. +Handlers register through `KinActionHandlers` (a Context service, built from one list in `approvals/layer.ts`). The only handler is the lead spec's `set_level`. An approved action whose kind has no handler is voided (`unsupported_kind`) without a claim, which is what happens to a merge or branch deletion approved before the GitHub App was retired. Each held action gets one audit entry per hold reason (`execution_held` with `held: not_configured`, `held: paused` and so on), and when the sweep voids one whose grant lapsed while held, the owner's notice names the reason. The executor, its ledger and its handlers stay out of `approvals/layer.ts`'s output: context lookups go by key string, and that output reaches every service holding `kin.services`. Run order for an `approved` action: 1. Stop switch (lead spec) off → else stay `approved` until the grant lapses, then the sweep voids it. -2. Approver still owner (`KinOrgRoles`), and for GitHub kinds (section 12) `CredentialHygiene.requirePassing` passes → else stay `approved` (one `credential_check_failed` entry per action and failure set) until the grant lapses. Checking before the claim keeps a misconfigured host from spending the grant. +2. Approver still owner (`KinOrgRoles`) → else stay `approved` until the grant lapses. 3. Before the claim, the stored grant must verify again: its signature against its key's public JWK, that key's seal (check 2), and its payload binding this action's org, id, revision, `jti`, approver and facts (check 7) → else `voided: grant_unverified`. A grant row or an `approved` state written straight into SQLite stops here. 4. **Claim:** `INSERT INTO kin_executions(action_id, …)` and CAS `approved → executing` in one transaction. The insert also requires the grant unconsumed and alive, the signing key usable, and the org not paused. A failed insert means it already ran, is running or may not run: refuse. -5. A fresh hygiene pass for the kinds step 2 checks, and the signing key and the approver's owner role checked again, then `precheck` with the bot's read-only `server` token (each read gives up after 15 seconds, which ends the action `failed`): PR open, `head.sha == grant.headSha`, `base.ref == grant.base`, and no `merge_queue` rule on the base (`GET /repos/{o}/{r}/rules/branches/{base}`; phase 1 refuses merge queues: `merge_queue_unsupported`). Whether the repo allows the method is left to GitHub, whose 405 ends the action `failed: not_mergeable`. Any failure from here on is `failed`: the grant is spent. -6. The stop switch again, and `kin_executions.write_started_at` recorded, immediately before the side effect. Nothing else sits between the live read and the write. -7. `run` with the owner's merge credential: `PUT /repos/{owner}/{repo}/pulls/{n}/merge` with `{sha: grant.headSha, merge_method}`. The `sha` field makes GitHub refuse with 409 if the head moved after step 5 (`failed: head_moved`). The executor calls REST directly through `apps/server/src/kin/github/OwnerMergeClient.ts`, **not** `PullRequestService.runAction`, because that path doesn't pin the head and picks its own credential. With `deleteBranchAfter`, a same-repo head branch still at the merged SHA is then deleted, unless it is the default branch, has ruleset rules (`GET rules/branches/{head}` returns any), or is the base of another open PR. A kept or failed delete doesn't change the outcome (a read GitHub doesn't answer keeps the branch; a delete with no clear answer may have landed, and the notice says so); the reason is appended to `execution_finished`'s `result` and to the owner's notice. The phone's prompt can't name the head branch: the signed payload has no head ref, and adding one would change the grant's bytes. -8. Record outcome (`kin_executions`, `execution_finished` with the grant's `jti`, key thumbprint and the key's `deviceLabel`), and post the result as a system notice to the requesting lead's owner chat. - -`delete_branch` runs the same steps. Its precheck refuses the default branch and a branch whose head isn't the approved SHA; `DELETE /git/refs/heads/{ref}` takes no expected SHA, so a push between the precheck and the delete is deleted with the branch. - -**Crash in the middle.** On startup the executor scans `executing` rows. For each it calls `reconcile`: for a merge, `GET /pulls/{n}`; `merged == true` and `merge_commit_sha` present → `succeeded` (`execution_reconciled`); not merged → `interrupted`, but only once the write is 2 minutes old (`write_started_at`), since GitHub can answer 502 on a merge that lands seconds later (until then it stays `executing`); no `write_started_at` means nothing was sent → `failed: not_started`, with no read; GitHub unreachable → retry every 30 s, state unchanged. A branch deletion is done when the ref is gone. `interrupted` is terminal: the grant is spent, and the owner's notice says to approve a new request. One grant, one attempt, always. (A card that creates the new pending action in one tap is mobile work, not built yet.) - -**Owner's merge credential.** A fine-grained personal access token from the owner, limited to the Kin repos, with **Contents: Read and write** and **Metadata: Read** only. GitHub's permission table puts `PUT /pulls/{n}/merge` and `DELETE /git/refs/{ref}` under Contents: write, and `POST /pulls/{n}/reviews` under Pull requests: write, so this token **can merge and delete branches but can't approve a PR**. It lives in the OS keychain via `@napi-rs/keyring` (`AsyncEntry("kin-owner-merge", "")`), is read per execution, and is never logged, put in an environment variable, or passed to a child process. Expiry is set to 90 days; a card warns 7 days before. +5. The signing key and the approver's owner role checked again, then `precheck`. Any failure from here on is `failed`: the grant is spent. +6. The stop switch again, and `kin_executions.write_started_at` recorded, immediately before the side effect. +7. `run`. +8. Record outcome (`kin_executions`, `execution_finished` with the grant's `jti`, key thumbprint and the key's `deviceLabel`), and post the result as a system notice to the owner's chat. -Setup is `node scripts/kin-github-app.ts --merge-token --kin-org ` on the Kin host, with hidden input. `OwnerMergeClient.save` refuses anything but a fine-grained token (`github_pat_`), calls `GET /user` with it, and reads the expiry from GitHub's `github-authentication-token-expiration` response header rather than trusting the owner. A token with no expiry, an expiry already past, or one more than 90 days out (one day of slack) is refused, as is one whose login isn't `KIN_GITHUB_OWNER_LOGIN`. `save` then probes the token's permissions (section 10, "Probing the owner merge token") and stores nothing if any probe fails. The keychain item holds `{token, login, expiresAt, savedAt}`; `login` is how the hygiene check (section 12) recognises the owner. `OwnerMergeClient.token` takes the `CredentialHygienePass` that only `CredentialHygiene.requirePassing` returns, so the executor can't read the token without a passing check. The pass's constructor needs a module-private symbol, and `token` refuses a pass whose check is more than 60 seconds old (`OwnerMergePassStaleError`, before any request, so the action ends `failed`), so the executor checks right before each merge. +**Crash in the middle.** On startup the executor scans `executing` rows and calls each one's `reconcile`: done → `succeeded` (`execution_reconciled`); not done → `interrupted`; no `write_started_at` means nothing was sent → `failed: not_started`. `interrupted` is terminal: the grant is spent, and the owner's notice says to ask again. One grant, one attempt, always. ### 7. Idempotency (gap 4) -- `idempotencyKey = sha256(stableStringify({orgId, kind, target, source}))` where `source` is the lead's triggering event id (`KinEvent.id`, lead spec): a webhook delivery id, a deferral id plus its due time, or a chat message id. -- A second `request_action` with the same key returns the existing action instead of creating one: a replayed webhook, a deferral that fires twice, or a lead that retries after a timeout all land on the same row. -- A new commit on the PR doesn't change the key. It rotates the nonce on the same action. +- `idempotencyKey = sha256(stableStringify({orgId, kind, target, source}))` where `source` names what asked: for an owner request, the request's own id. +- A second request with the same key returns the existing action instead of creating one, so a retried request lands on the same row. - Execution: the `kin_executions` primary key makes a second run impossible, whatever restarts or duplicate fibers do. - Grants: `jti` UNIQUE and one grant per approver per action. @@ -360,12 +341,11 @@ export const KinProvenance = Schema.Struct({ }); ``` -- The lead spec computes it from the `KinEvent` and passes it down to workers; the ceiling is the lowest role in the chain. Webhook content (PR bodies, comments) counts as `none`. +- The lead spec computes it from the `KinEvent`; the ceiling is the lowest role in the chain. GitHub content (PR bodies, comments) counts as `none`. - **Work** runs only if the ceiling and the chat's level allow it (`ceilingAllows`). -- **Privileged** is proposed under any ceiling but runs only with the owner's grant, which is the owner's own authority for that one action. `request_action` stores `ceilingBelowOwner` from the whole batch, not the cited event: the lead can cite the owner's message while a PR comment in the same batch drove the request. When it is set, the card warns above the buttons that the request didn't come from the owner alone. `afterNonOwnerMessage` only supplies the name ("Asked for after Priya's message"); without one the card names the source kind, such as a GitHub event. -- A lead can never request `set_level`, whoever drove the wake-up: `request_action` refuses it (`unsupported_kind`) before provenance is read. Raises reach the owner only through the owner-only `kin.levels.raise`, which creates the action under the reserved requester `kin-promotion`; `KinPendingActions.create` refuses `set_level` from any other requester. -- `change_rules`, `register_approver_key`, and (later) `set_delegation` and `set_next_of_kin` are refused at `request_action` (`not_owner`) unless every event in the wake-up's chain is the owner's, which implies `startedByRole == "owner"`. The lead picks `sourceEventId`, so checking only the cited event would let it cite an owner's message while acting on a member's in the same batch. A member can't even get those cards in front of the owner. -- Roles come from stored rows, never event text: a chat message's stored `author_role` (human, posted), or for other human events the actor's current chat membership. Only the lead's own owner counts as `owner`; another human holding an owner row counts as `member`. Agent, system, schedule and webhook events count as `none`. `afterNonOwnerMessage` names the first non-owner human message in the batch. +- **Privileged** runs only with the owner's grant, which is the owner's own authority for that one action. Today every request comes from the owner's session (section 2), so its provenance is the owner's. `ceilingBelowOwner` and `afterNonOwnerMessage` stay in the schema so the card can warn, above the buttons, if a kind an agent proposes ever returns. +- `set_level`, `change_rules`, `register_approver_key`, and (later) `set_delegation` and `set_next_of_kin` must never be requestable from an agent's turn unless every event in the wake-up's chain is the owner's. Checking only a cited event isn't enough: a lead can cite an owner's message while acting on a member's in the same batch. +- Roles come from stored rows, never event text: a chat message's stored `author_role` (human, posted), or for other human events the actor's current chat membership. Only the lead's own owner counts as `owner`; another human holding an owner row counts as `member`. Agent, system, schedule and GitHub events count as `none`. `afterNonOwnerMessage` names the first non-owner human message in the batch. ### 9. Approval cards @@ -373,113 +353,17 @@ export const KinProvenance = Schema.Struct({ - Apps render the card natively from `kin.approvals.get(actionId)`. The server projects per viewer: - **Owner:** full facts, `canApprove: true`, shown in **Waiting on you** and the direct chat. - **Anyone else:** `{repo, number, title, state, waitingOn: "Nishchay"}`, `canApprove: false`, no challenge. `kin.approvals.challenge` and `submitGrant` refuse non-owners with `not_owner` anyway. -- The card shows repo, PR number and title, the full head SHA (wrapped, not cut), base ← head, method, `+additions −deletions` and file count, required checks with status, the agent's reason as a quote, and the provenance warning. +- The card shows the target (for `set_level`, the lead, the chat or all chats, and the level), the reason as a quote, and the provenance warning. - Approve: the approval key module shows the grant's own text, written natively from the signed payload (section 5): `Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into "main" by squashing` → biometric → sign → submit. Android shows it in the `BiometricPrompt`. Face ID mostly ignores the prompt's reason text, so on Face ID iPhones the module first shows it in a native confirmation sheet, in its own window above the app's. The sheet ends any picture in picture the app's web views start, before it shows and while it is up. Coverage is checked on every frame while the sheet is up. Approve stays disabled, and ignores taps, until every frame for 0.7 s has found the sheet key and uncovered; any frame that isn't clear restarts the delay, as do the sheet appearing, becoming key again, and the keyboard showing or hiding. Once enabled, the first frame that isn't clear disables Approve and arming starts over. So a tap aimed at something JS drew, or the second tap of a double tap, can't land on it. A tap that arrives while something covers the sheet signs nothing (`E_OBSCURED`). Touch ID shows it in the system prompt. Notification and lock-screen actions open the app to this card; nothing is signed in the background, and the module signs one grant at a time. - Desktop and web show the card read-only with "Approve on your phone" in phase 1. -### 10. GitHub: the bot App, the owner's review, rulesets - -**Kin GitHub App** (new, created with the manifest flow by `scripts/kin-github-app.ts`), installed on selected repos only. - -| Permission | Level | Why | -| --------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------- | -| Metadata | Read | Required | -| Contents | Read and write | Kin's server-side pushes for workers (`server` holder only; rulesets protect the default branch) | -| Pull requests | Read and write | Open draft PRs, comment, read reviews | -| Issues | Read and write | Comment on and link issues | -| Checks | Read | Show checks on cards | -| Commit statuses | Read | Same | -| Actions | Read | CI run state | -| Workflows | **None** | GitHub then rejects pushes that change `.github/workflows`, so a worker can't add a workflow that reads repo secrets | -| Administration, Secrets, Environments, Deployments, Members, Webhooks | **None** | | - -Webhook events (consumed by the triggers spec's App webhook source, which filters to exactly these): `pull_request`, `pull_request_review`, `pull_request_review_comment`, `issue_comment`, `issues`, `check_suite`, `workflow_run`, `push`. Approvals reads check runs and statuses over REST at verify time, so it needs no `check_run` or `status` events. The App's private key is in the OS keychain (`AsyncEntry("kin-github-app", "")`, a JSON item with the PEM, webhook secret and client secret); the server finds it through `KIN_GITHUB_APP_ID`. Installation tokens last one hour; each worker gets one minted with `POST /app/installations/{id}/access_tokens` narrowed by `repositories` and `permissions` (no agent token carries `contents: write`). `KinGitHubApp.installationToken` takes exactly one repository from `KIN_GITHUB_REPOS`, a non-empty subset of the table at or below its levels, and the `holder` (`lead`, `worker` or `server`). It refuses anything else before calling GitHub, including `contents: write` for any holder but `server` (open question 7). A `server` token stays in Kin's own process, for its own pushes and the triggers spec's read-only deferral and watchdog reads, and is never handed to an agent. That refusal only holds if `holder` is true: callers hard-code it and never take it, or anything that picks it, from model input. It also refuses when `GET /repos/{o}/{r}/installation` reports `repository_selection: "all"`. If GitHub's answer is wider than asked (more repositories, or a permission not requested or at a higher rank, beyond the `metadata: read` it always adds), or doesn't decode, it revokes the token with `DELETE /installation/token` and fails. A failed revoke is logged without the token; the token still expires within the hour. - -`KinGitHubScope` (`apps/server/src/kin/github/KinGitHubScope.ts`) holds the scope the checks compare against: `KIN_GITHUB_OWNER_LOGIN` (the owner's personal login), `KIN_GITHUB_BOT_LOGIN` (the only login the Kin host may use, section 12) and `KIN_GITHUB_REPOS` (comma-separated `owner/name`). - -`scripts/kin-github-app.ts` runs on the Kin host as the server's OS user, so the secrets land in that user's keychain. With no flags it serves the manifest form on `127.0.0.1:47821` (forward it over SSH) and completes `POST /app-manifests/{code}/conversions` from the redirect, checking `state` and that the `Host` header is `127.0.0.1:` or `localhost:`. It checks that a Secret Service answers before serving the form (open question 6), because the conversion answer is the only copy of the private key. It stores the secrets only when the new App's permissions match the table and its owner is `--org` or `KIN_GITHUB_OWNER_LOGIN`; otherwise it stores nothing and says to delete the App. Any local process can reach the loopback port and read `state` from the form, so another local user could send a callback for an App they created; the owner and permission checks refuse that App. It prints only the App id, slug and install URL. `--webhook-url` subscribes the App webhook to the events above; without it the App has no webhook, which matches the triggers spec's per-repo hooks. `--check` diffs the App's permissions and every installation's accepted permissions against the table, which is one constant (`KIN_GITHUB_APP_PERMISSIONS` in `apps/server/src/kin/github/KinGitHubPermissions.ts`). It also fails an installation on all repositories, and reads every page of installations. The command itself is `apps/server/src/kin/github/appSetup.ts`: the composite `scripts` TypeScript project can't include server files (TS6307), so the script loads it by URL. - -**Probing the owner merge token.** GitHub has no API that lists a fine-grained token's permissions, so `OwnerMergeClient.save` asks GitHub with the token itself. For each repository in `KIN_GITHUB_REPOS`: - -| Probe | Must answer | Refusal | Shows GitHub refuses the token | -| ------------------------------------------------------------------------------------------------------- | ----------------------- | --------------------------------- | ------------------------------ | -| `GET /repos/{o}/{r}` | 200, `permissions.push` | `repo_unreachable`, `cannot_push` | (it can reach and push) | -| `GET /repos/{o}/{r}/actions/permissions` | denied | `too_broad` | Administration | -| `GET /repos/{o}/{r}/hooks` | denied | `too_broad` | Webhooks | -| `GET /repos/{o}/{r}/actions/secrets` | denied | `too_broad` | Secrets | -| `POST /repos/{o}/{r}/pulls/{probe PR}/reviews` with `{event: "KIN_PERMISSION_PROBE", commit_id: "0…0"}` | denied | `too_broad` | Pull requests: write | -| `GET /orgs/{org}/rulesets`, once per organization that owns a repo (`owner.type === "Organization"`) | denied | `too_broad` | Organization administration | - -"Denied" is GitHub's missing-permission answer and nothing else: HTTP 403, no `retry-after`, `x-ratelimit-remaining` not `"0"`, and the body's `message` exactly `Resource not accessible by personal access token`. A 429 or a rate-limit 403 refuses with `rate_limited` ("try again later"), never a pass. A 404 refuses with `probe_inconclusive`: the token may lack access to the repo, or the probe PR doesn't exist. The probe PR is #1 unless `--merge-token --probe-pr ` names one that exists in every Kin repo. Any other answer, a 5xx or a 403 with another message included, is `too_broad`. The review body is invalid, so a token that can review gets 422 and no review is made. Then `GET /user/repos?per_page=100` must list only scoped repositories (`other_repos`), which catches "All repositories" and extra selected ones. - -So a stored token is proven to push to the Kin repos and to be refused administration (repository and organization), webhooks, secrets and reviews there. It is not proven to lack anything else. These can't be probed without side effects or a resource to aim at, and stay residual risks: Workflows (pushing `.github/workflows` changes), Actions write (re-running or cancelling runs), Environments, any other repository permission not in the table, account-level permissions, and read access to every public repository, which every fine-grained token has. The setup text tells the owner to grant only Contents and Metadata; the probes catch the permissions that would let the token review or change the rules. - -These probes assume GitHub checks a fine-grained token's permission before it looks up the resource or validates the body (403 before 404 or 422), that `permissions` on `GET /repos` reflects the token rather than only the owner's role, and that `/user/repos` lists only the repositories the token was granted. None is documented. Confirm them on a scratch repo (test 23) before relying on them: a Contents + Metadata token must pass `--merge-token`, and tokens that add Administration read, Webhooks read, Secrets read, organization Administration read or Pull requests write, or use "All repositories", must each be refused. - -**The owner's GitHub review comes from the phone.** The ruleset needs a code-owner approval that the server can't produce, since the merge token above can't review. When the owner taps Approve, the phone, after the same biometric prompt, calls `POST /repos/{o}/{r}/pulls/{n}/reviews` with `{event: "APPROVE", commit_id: headSha}` directly to GitHub, using a user-to-server token for the Kin App held only on the phone (`expo-secure-store` with `requireAuthentication: true`, obtained once by device flow). Then it submits the grant. The server never sees this token. If the phone has no token, the card offers "Approve on GitHub" and waits for the `pull_request_review` webhook before enabling the Kin approval. - -**Ruleset on each Kin repo** (`scripts/kin-rulesets.ts` applies it with `POST /repos/{o}/{r}/rulesets` and checks for drift; the desired rulesets are one definition, `kinRulesets` in `apps/server/src/kin/github/KinRulesets.ts`): - -```json -{ - "name": "kin-main", - "target": "branch", - "enforcement": "active", - "bypass_actors": [], - "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } }, - "rules": [ - { "type": "deletion" }, - { "type": "non_fast_forward" }, - { - "type": "pull_request", - "parameters": { - "required_approving_review_count": 1, - "require_code_owner_review": true, - "dismiss_stale_reviews_on_push": true, - "require_last_push_approval": true, - "required_review_thread_resolution": true, - "allowed_merge_methods": ["squash", "merge"] - } - }, - { - "type": "required_status_checks", - "parameters": { - "strict_required_status_checks_policy": true, - "do_not_enforce_on_create": false, - "required_status_checks": [{ "context": "", "integration_id": 15368 }] - } - } - ] -} -``` - -- `bypass_actors` is empty, including repository admins. Otherwise the owner's merge token could skip review. `--check` also requires `current_user_can_bypass: "never"`, and counts a ruleset whose bypass actors it can't see as drift. -- `integration_id` 15368 is the GitHub Actions App (`GET /apps/github-actions`), so a commit status posted with any token that has commit-status access can't stand in for CI. -- `require_last_push_approval` is on. `dismiss_stale_reviews_on_push` only dismisses an approval when a push changes the diff, so a bot push that adds a commit and a second that reverts it would keep the owner's approval, and with merge commits allowed the unreviewed commit would land in history. Last-push approval makes any bot push after the review need a new one. It would deadlock a sync branch the owner pushed last, so the sync flow below ends with a bot push. `merge` is allowed for those syncs; the executor squashes bot PRs. -- `.github/CODEOWNERS` contains `* @GLDRoger`, so the bot's approval never counts, and a PR that changes CODEOWNERS needs the owner's review too. The check reads the copy on the default branch (the one GitHub uses for reviews into it) and GitHub's `codeowners/errors`, and requires a `*` rule with every rule naming exactly `@GLDRoger`, so no later rule hands a path to someone else or to no one. Without it, `require_code_owner_review` is met by anyone's approval, so apply refuses to change any ruleset until CODEOWNERS passes. -- A tag ruleset `kin-release` (`refs/tags/v*` and `refs/tags/v*/**`, since `*` stops at `/`) blocks tag creation, update (`update_allows_fetch_and_merge: false`) and deletion, with no bypass, for when releases arrive. Update is included so a release tag can't be moved to another commit. GitHub requires the `update` parameter; the test fake rejects rules missing any parameter the REST reference marks required. -- The required check for `GLDRoger/t3code` is `Check`, the `ci.yml` job that fails unless every other job passed or was skipped as not needed. Other repos pass `--status-check`. -- The script reads `KinGitHubScope`. The owner is `KIN_GITHUB_OWNER_LOGIN`; `--owner` may name someone else only for a repository outside Kin, and is refused for `KIN_GITHUB_REPOS`, `GLDRoger/t3code` and `--test-23`. It takes the owner's own sign-in (`GH_TOKEN` or a hidden prompt) and refuses anything else before writing: an installation token (`ghs_`, refused before any request), a credential `GET /user` rejects or reports as a bot, a login other than the owner's, and a credential without admin on the repo (GitHub hides `bypass_actors` from those, so drift could go unseen). `--check` reports every drifted field, including any bypass actor, a rule someone added or removed, and changed parameters; parameters GitHub adds that the spec doesn't set are not compared. Apply creates or replaces each ruleset by name, writes nothing when it already matches, and re-reads to confirm no drift. - -**Memory repo mode.** `KIN_REPOS` gives each Kin repo a `kind`; a `memory` repo (triggers spec, memory repo guard rails) gets only `kin-main`, still with no bypass actors and `memory-check` as its required check, but with `required_approving_review_count: 0` so a PR touching only CODEOWNERS' owner-less Kin paths merges on the check alone while code-owner review gates every other path, squash only, and `require_last_push_approval` off: with squash only, a diff-neutral push can't land an unreviewed commit in history, and last-push approval could block those review-free PRs. Its CODEOWNERS check still calls `codeowners/errors` and still requires `* @`, but lets the template's `kinOnlyPaths` lines (from the memory lint) name no one; any other owner-less line fails. There is no tag ruleset, and `--test-23` stays on code repos. - -The owner is the memory repo's only code owner and can't approve their own PR, so an owner change to an owned path (a `T3CODE_REF` bump, a hand edit to `rules.md`) uses the upstream sync flow below: the owner pushes a branch, the bot adds the same-tree commit and opens the PR, and the owner approves as code owner and squash-merges. Nothing implements that flow yet, for either kind of repo. When the diff touches `.github/workflows`, as every `T3CODE_REF` bump does, confirm by hand that GitHub accepts the bot's same-tree commit without the Workflows permission. With last-push approval off, the bot authoring the PR is what makes the approval count, so the bot can open it from the owner's head if that commit is refused. - -`memory-check`'s pin to app 15368 trusts every Actions workflow in the repo, not just `memory-check.yml`, and the read-only workflow-permissions setting is only a default that a pushed workflow can raise. A ruleset `workflows` rule exists only for organization rulesets, so it isn't available on `GLDRoger/kin-memory`. Kin therefore trusts a passing `memory-check` only after checking that the PR head is the SHA Kin pushed and that the check came from a `pull_request` run of `.github/workflows/memory-check.yml` at that SHA (TRIG-15 writer PR path). Never grant the App Workflows there. The scratch-repo checks to run before switching the mode on are in `ops/kin/memory-repo/README.md`. - -`kinRulesets` targets `~DEFAULT_BRANCH`. On `GLDRoger/t3code` that is `kin`, where PRs land; `main` is the upstream mirror and is held by a hand-made "main: upstream mirror" ruleset with an admin bypass that `--check` doesn't read. Bringing `main` under `kinRulesets` is open. +### 10. GitHub -**Upstream syncs (proposed resolution of open question 2, owner to confirm).** The bot can't carry a sync: an upstream merge changes `.github/workflows`, which its missing Workflows permission rejects, and squashing would flatten the merge so the next sync conflicts. So the owner carries it, and Kin only opens the PR: +Kin has no GitHub identity of its own. Its GitHub work runs on the owner's login, connected from the phone at Settings → Connections → GitHub (`gh auth login` by device code, then `gh auth setup-git`, as the server's OS user). Owner-only turns that have read no outside text use `gh` in their shell; `kin_github_review`, `kin_github_watch` and `kin_github_link` show only while that login is connected; the watch polls the owner's repos and wakes the lead on a `/kin` comment (triggers spec). Signing out stops all of it. -1. The owner merges upstream locally and pushes `sync/` with the merge commit, using their own credential, never the Kin host's. -2. The bot pushes one same-tree commit on top, so it is the last pusher: `POST /git/commits` with the merge commit's tree and the merge commit as its only parent, then `PATCH /git/refs/heads/sync/` to it. The commit changes no files, so its lack of the Workflows permission shouldn't block it; test 23's manual steps confirm this. -3. The bot opens the PR from that branch, only after Kin checks that `head^` is the SHA the owner pushed and `head^{tree}` equals that commit's tree; the card shows the result. Without the check, a change could hide inside a large upstream diff and the owner would approve it as the last push. Until `sync/*` has its own ruleset, the bot could also force-push the branch before review, so the check runs against the head being approved. -4. The owner approves as code owner. The approval counts because the bot pushed last and authored the PR. -5. The owner merges in the GitHub UI with a merge commit, which `allowed_merge_methods` permits. -6. The executor keeps squashing bot PRs (`merge_method: "squash"`). -7. The merge token can't take this path: it has no Workflows permission, so GitHub refuses it a merge that changes workflows. +Kin never merges code. The owner merges on GitHub, so branch protection is whatever the owner sets there; Kin doesn't apply or check rulesets. Kin's own memory repo is the exception (triggers spec, memory repo guard rails). Comments Kin posts carry the agent's signature line (`ghSign.ts`), since they go out under the owner's name. -Cost: `merge` is allowed for every PR into the default branch, so a code-owner-approved bot PR could be merge-committed by hand. That changes history shape, not who may merge. +The GitHub App, its installation tokens, the owner's merge token, the bot login, the App's webhook and `scripts/kin-github-app.ts` and `scripts/kin-rulesets.ts` were removed. `ops/kin/host/README.md` says how to retire them on a host. ### 11. Audit @@ -505,7 +389,7 @@ export const KinAuditEntry = Schema.Struct({ "key_registered", "key_confirmed", "key_revoked", - "credential_check_failed", + "credential_check_failed", // retired: written by the removed hygiene check ]), actionId: Schema.optional(KinActionId), kind: Schema.optional(KinActionKind), @@ -516,7 +400,7 @@ export const KinAuditEntry = Schema.Struct({ deviceLabel: Schema.optional(Schema.String), sessionId: Schema.optional(AuthSessionId), provenance: Schema.optional(KinProvenance), - result: Schema.optional(Schema.String), // merge commit SHA, or the failure reason + result: Schema.optional(Schema.String), // the outcome, or the failure reason prevHash: Hex64, hash: Hex64, // sha256(prevHash ‖ stableStringify(entry without hash)) }); @@ -524,51 +408,27 @@ export const KinAuditEntry = Schema.Struct({ Append-only: `BEFORE UPDATE` and `BEFORE DELETE` triggers on `kin_audit` abort every edit, and the repository code has no such statements. The hash chain makes edits that bypass the triggers visible; `kin.audit.verify` recomputes it. Rejected grants are audited with their failure reason and the sending session, so a forged approval leaves a trace. `kin.audit.list` and `kin.audit.verify` are owner-only: the session must resolve to the org's owner, not just a person in the org. `list` returns a row that no longer decodes as `{ seq, corrupt: true }` instead of failing the page. The audit stores the grant's `jti` and the key thumbprint, never tokens or keychain contents. -`apps/server/src/kin/approvals/Audit.ts` (`KinAudit`) is the only writer. `append` joins the caller's transaction, so `PendingActions.ts` writes each transition's entry atomically with the transition: `action_requested` on insert (not on an idempotent replay), `action_refreshed`, `grant_accepted`, the four terminal `action_*` moves (the sweep included), `execution_started` with the claim, and `execution_finished`, or `execution_reconciled` when startup reconciliation decides the outcome. `approve` also writes `grant_rejected` for `stale`, `replayed` and `revoked_key`, after its transaction ends: when no grant row was inserted the transaction commits empty, and only a lost compare-and-set on the action rolls the inserted grant back. The entry goes on the chain of the org that owns the action; a grant naming an unknown org or action stays `stale` and writes nothing. Rejections decided before `approve` (checks 1–9), key events and `credential_check_failed` are written by APPR-4, APPR-5 and APPR-8 through `KinAudit.append`, and the executor writes `execution_held` once per held action and reason. No RPC or MCP tool writes or deletes entries. +`apps/server/src/kin/approvals/Audit.ts` (`KinAudit`) is the only writer. `append` joins the caller's transaction, so `PendingActions.ts` writes each transition's entry atomically with the transition: `action_requested` on insert (not on an idempotent replay), `action_refreshed`, `grant_accepted`, the four terminal `action_*` moves (the sweep included), `execution_started` with the claim, and `execution_finished`, or `execution_reconciled` when startup reconciliation decides the outcome. `approve` also writes `grant_rejected` for `stale`, `replayed` and `revoked_key`, after its transaction ends: when no grant row was inserted the transaction commits empty, and only a lost compare-and-set on the action rolls the inserted grant back. The entry goes on the chain of the org that owns the action; a grant naming an unknown org or action stays `stale` and writes nothing. Rejections decided before `approve` (checks 1–9) and key events are written by APPR-4 and APPR-5 through `KinAudit.append`, and the executor writes `execution_held` once per held action and reason. No RPC or MCP tool writes or deletes entries. Each org has its own chain. The first entry's `prevHash` is 64 zeros, and `seq` counts from 1 with no gaps. Appends are serialized by SQLite's single `BEGIN IMMEDIATE` writer, with `UNIQUE(org_id, seq)` as a backstop. `entry_json` holds `stableStringify` of the whole entry. `verify` walks the chain in `seq` order and reports the first entry whose bytes, columns, position, `prevHash` or `hash` don't hold, which catches an edited, deleted, reordered or inserted row. The chain has no secret and no outside anchor, so it can't show a truncated tail or a chain recomputed from the edit onward by someone with write access to the database. It catches tampering, not a compromised server. -### 12. Credential hygiene check - -At startup and hourly, the executor checks every GitHub identity reachable from the server's OS user: T3's own (`GitHubRequestPolicy.credential("github.com")`, then `GET /user`), every account `gh auth status` lists for github.com, active or not, and the login behind the github.com git credential helper, and every login GitHub greets over SSH. If any of them isn't `KIN_GITHUB_BOT_LOGIN`, or `GH_TOKEN`, `GITHUB_TOKEN` or `SSH_AUTH_SOCK` is set in the server environment, the executor writes `credential_check_failed`, refuses privileged execution, and posts a card to the owner. Agent CLIs run as children of the server and inherit its `gh` login and environment, so on the Kin machine that identity must be the bot. The triggers spec's Kin host setup owns making it so. - -`CredentialHygiene.check(orgId)` (`apps/server/src/kin/approvals/CredentialHygiene.ts`) returns a report, and the executor calls `requirePassing` before every privileged run. Failures: - -- `env_token`: `GH_TOKEN`, `GITHUB_TOKEN`, either `*_ENTERPRISE_TOKEN` or `SSH_AUTH_SOCK` is set, or T3's credential came from the environment. The report names the variables, never their values. An SSH agent can hold several keys and GitHub greets only the first it accepts, so the SSH probe can't see past it; start the Kin server without `SSH_AUTH_SOCK` (macOS launchd sets it for every login session). -- `owner_identity`: a login found equals the merge token's login or `KIN_GITHUB_OWNER_LOGIN`, case-insensitively. -- `non_bot_identity`: a login found is neither the owner's nor `KIN_GITHUB_BOT_LOGIN`. -- `identity_unknown`: the identity probe failed, or an SSH answer was neither `Hi !` nor `Permission denied (publickey)`. This fails closed. -- `merge_token_missing` or `merge_token_expired`: no owner login to compare against, and nothing to merge with. - -A merge token in its last 7 days passes with the `merge_token_expiring` warning, which drives the expiry card. `requirePassing` returns a `CredentialHygienePass`, which `OwnerMergeClient.token` requires (section 6). The merge token itself is probed once, at `save` (section 10); the hourly check reads only its stored login and expiry. GitHub lets the owner widen a fine-grained token's permissions without changing its value, so a token widened after `save` (for example to Pull requests: write) goes unnoticed until it's saved again. Rerunning the read-only probes in the hourly check is a follow-up. - -The identity probe is the `T3GitHubIdentity` port. `@t3tools/source-control-github` exports only its driver, so `GitHubRequestPolicy.credential` can't be reached from `apps/server` without a one-line export there. APPR-9 wires the executor with `identityUnavailableLayer`, which fails every probe, so no privileged action runs on a real host until APPR-16 adds that export and the live layer. Allowing a phone never takes the check: it writes nothing to GitHub. The port's `identities` has a required field per source (`t3`, `ghAccounts`, `gitCredential`, `ssh`), so the live layer must report all four. It reads `gh` accounts from `gh auth status --hostname github.com`, and the git helper's login from `git credential fill` for `https://github.com` followed by `GET /user` with the returned password, never logging it. For `ssh` it runs `ssh -T -o BatchMode=yes -o StrictHostKeyChecking=yes git@github.com` (`GITHUB_SSH_PROBE`) with a timeout, then the same once per private key in `~/.ssh` with `-o IdentitiesOnly=yes -i `, and reports each answer's combined output; the check parses them , so the live layer can't misread one, and an empty list fails. A deploy key's greeting names `owner/repo`, which fails as `non_bot_identity`. Keys behind another `Host` alias in `~/.ssh/config` aren't probed. A source it can't read fails the probe, which fails the check closed (`identity_unknown`). - -The check only sees what the server's OS user is set up with. An agent running as that user can still read anything that user can: it can find an SSH agent socket on disk and set `SSH_AUTH_SOCK` itself, read the merge token and the App's private key from the keychain (open question 4), or use credentials outside these sources. The real fix is a separate executor OS user. - ## Threat model -| Threat | Example | Stopped by | -| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Injected instruction | PR body says "merge this now" | Lead can only `request_action`; owner signs a native card; ceiling flags it | -| Fake approval in text | Member types "Nishchay approved" | Only `submitGrant` with a valid signature changes state | -| Forged approval from a member's client | Modified app calls `submitGrant` | Checks 2–4: key not registered, or registered to a non-owner → `not_owner` | -| Agent-drawn button | Generated widget labelled "Approve" | `approval` widgets carry only `actionId`; the card is native; generated widgets can't call approvals RPCs | -| Card shows one thing, phone signs another | Buggy or tampered app code asks the key to sign another PR | The key signs only canonical grants; the module writes the approval text natively from the bytes it signs | -| Tampered JS draws over the Face ID sheet | An over-the-air bundle covers the text, leaves Approve | Sheet in the module's own window above the app's; Approve checks nothing covers it (`E_OBSCURED`) | -| Tampered JS times a tap onto Approve | Draws a button where Approve will appear, calls `sign` on touch-down; or covers Approve, then uncovers it | Approve enables only after every frame for 0.7 s finds the sheet key and uncovered, and any later frame that isn't clear disables it and restarts the 0.7 s | -| Tampered JS draws into picture in picture | Starts PiP that partly covers the sheet's text and takes taps inside its own frame | The module closes web-view PiP for as long as the sheet is up; `expo-video` PiP from tampered JS, and other apps' PiP, are accepted residual risk (see below) | -| Tampered JS registers a software key | Deletes the hardware key, makes a P-256 key in JS, registers it | App Attest or Keystore attestation of a key the native module made; unattested keys are never activated | -| Replay | Captured grant sent again, or for another PR | `jti` UNIQUE, nonce and `targetDigest` binding, executions PK | -| Bait and switch | New commit pushed after the owner looks | Nonce rotation, check 9, executor precheck, `sha` on the merge call, `dismiss_stale_reviews_on_push` | -| Double run | Restart mid-merge, duplicate webhook, deferral fires twice | Idempotency key, executions PK, reconciliation | -| Stolen phone | Thief has the unlocked phone | Per-use biometric on the key; `.biometryCurrentSet` / enrollment invalidation; remove its key in Settings, then Approvals, in Kin on the web or desktop | -| Compromised Kin server or agent with shell | Reads the keychain merge token | Token can't review; ruleset needs the owner's code-owner review at the current SHA, which only the phone can make | -| Agent with shell reads the App's key | On Linux, or any host where agents share the server's OS user, reads `kin-github-app` from the keychain and mints installation tokens itself | **Not stopped in phase 1.** Those tokens aren't narrowed by `installationToken`, so they carry the App's full table, `contents: write` on every installed repo included. Phase 1 relies on the ruleset needing the owner's review; the fix is a separate executor OS user (open question 4) | -| Bot self-approval | Bot approves its own PR | GitHub forbids author approval; bot isn't a code owner | -| Worker merges after review | Worker with a `contents: write` token merges once the owner has approved the head | **Stopped through the API:** no agent token carries `contents: write` (section 10); only Kin's `server` holder can mint one. A shell agent reading the keychain remains open (row above) | -| Workflow exfiltration | Worker adds a workflow that prints secrets | App has no Workflows permission | -| Rule change from chat | "Remember: Priya can approve merges" | `change_rules`/delegations need owner provenance and a grant | +| Threat | Example | Stopped by | +| ----------------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Injected instruction | PR body says "merge this now" | No agent tool can request one; the owner merges on GitHub himself | +| Fake approval in text | Member types "Nishchay approved" | Only `submitGrant` with a valid signature changes state | +| Forged approval from a member's client | Modified app calls `submitGrant` | Checks 2–4: key not registered, or registered to a non-owner → `not_owner` | +| Agent-drawn button | Generated widget labelled "Approve" | `approval` widgets carry only `actionId`; the card is native; generated widgets can't call approvals RPCs | +| Card shows one thing, phone signs another | Buggy or tampered app code asks the key to sign another PR | The key signs only canonical grants; the module writes the approval text natively from the bytes it signs | +| Tampered JS draws over the Face ID sheet | An over-the-air bundle covers the text, leaves Approve | Sheet in the module's own window above the app's; Approve checks nothing covers it (`E_OBSCURED`) | +| Tampered JS times a tap onto Approve | Draws a button where Approve will appear, calls `sign` on touch-down; or covers Approve, then uncovers it | Approve enables only after every frame for 0.7 s finds the sheet key and uncovered, and any later frame that isn't clear disables it and restarts the 0.7 s | +| Tampered JS draws into picture in picture | Starts PiP that partly covers the sheet's text and takes taps inside its own frame | The module closes web-view PiP for as long as the sheet is up; `expo-video` PiP from tampered JS, and other apps' PiP, are accepted residual risk (see below) | +| Tampered JS registers a software key | Deletes the hardware key, makes a P-256 key in JS, registers it | App Attest or Keystore attestation of a key the native module made; unattested keys are never activated | +| Replay | Captured grant sent again, or for another PR | `jti` UNIQUE, nonce and `targetDigest` binding, executions PK | +| Double run | Restart mid-run, a retried request | Idempotency key, executions PK, reconciliation | +| Stolen phone | Thief has the unlocked phone | Per-use biometric on the key; `.biometryCurrentSet` / enrollment invalidation; remove its key in Settings, then Approvals, in Kin on the web or desktop | +| Rule change from chat | "Remember: Priya can approve merges" | `change_rules`/delegations need owner provenance and a grant | Tampered JS is the attacker the native sheet, the grant parser and attestation defend against. Over-the-air updates are its main way in. BRAND-1 (#35) turns updates on in Kin builds only when both a Kin EAS project (`KIN_EAS_PROJECT_ID`) and an update code-signing certificate (`KIN_UPDATES_CODE_SIGNING_CERT`) are configured: it removes upstream's updates URL and EAS project, and writes `updates.codeSigningCertificate` so `expo-updates` loads only bundles signed by Kin's key. Without both, the only JS that runs is the JS in the signed binary. Until #35 merges, the mobile app keeps upstream's updates config. @@ -576,26 +436,25 @@ Picture in picture is drawn by the system above every app window, so the sheet c `deleteKey` needs no biometric, so tampered JS can delete the approval key. That is only a denial of service because a replacement must be attested: registering a new key needs a fresh session challenge, an App Attest or Keystore attestation of a key the native module made, and the owner's own session, and the server never stores an unattested key. +An agent in an owner-only turn holds the owner's GitHub login through `gh`, so it can do on GitHub what the owner can. That is the price of a shell on his own repos; the shell is withheld from shared turns and from any turn that has read outside text (lead spec), and what reaches the default branch is still the owner's merge. + ## Files New (Kin-owned): - `packages/contracts/src/kinApprovals.ts` — all schemas above, RPC definitions, `KIN_APPROVAL_RPC_SCOPES`. - `packages/shared/src/kinGrant.ts` — `encodeGrantSigningInput`, `verifyKinGrant` (pure, shared with mobile). -- `apps/server/src/kin/approvals/` — `PendingActions.ts` (repository + CAS), `GrantVerifier.ts`, `ApproverKeys.ts`, `ActionExecutor.ts`, `handlers/mergePullRequest.ts`, `handlers/deleteBranch.ts`, `handlers/registerApproverKey.ts`, `mcp.ts` (`request_action`, `/kin/mcp`), `rpc.ts`, `Audit.ts`, `CredentialHygiene.ts`, `*.test.ts`. -- `apps/server/src/kin/github/` — `KinGitHubPermissions.ts` (the section 10 table, shared by the script and the server), `KinGitHubApp.ts` (installation tokens), `OwnerMergeClient.ts`, `Keychain.ts`, `appSetup.ts` (the command `scripts/kin-github-app.ts` launches). +- `apps/server/src/kin/approvals/` — `PendingActions.ts` (repository + CAS), `GrantVerifier.ts`, `ApproverKeys.ts`, `ActionExecutor.ts`, `ActionHandlers.ts`, `handlers/setLevel.ts`, `rpcHandlers.ts`, `Audit.ts`, `*.test.ts`. - `apps/server/src/kin/persistence/migrations/K00N_Approvals.ts`, registered in `KinMigrations.ts` (the track is shared with the chat spec). - `apps/mobile/modules/kin-approval-key/` — Swift, Kotlin, `expo-module.config.json`, `index.ts`. -- `apps/mobile/src/features/chats/approvals/` — `ApprovalCard.tsx`, `useApproveAction.ts`, `githubReviewToken.ts`. +- `apps/mobile/src/features/chats/approvals/` — `ApprovalCard.tsx`, `useApproveAction.ts`. - `apps/mobile/plugins/withKinApprovalKey.cjs`. -- `scripts/kin-github-app.ts`, `scripts/kin-rulesets.ts` (each one line in `knip.jsonc`'s `scripts` entries; server code they need lives in `apps/server` and is loaded by URL, as above). Upstream hooks (one line each): - `apps/server/src/auth/RpcAuthorization.ts` — `...KIN_APPROVAL_RPC_SCOPES,` in `RPC_REQUIRED_SCOPES` (or folded into the chat spec's single Kin spread, if it adds one). - `packages/contracts/src/kinRpcs.ts` (Kin-owned, created by CHAT-6) — add the approval RPCs and scopes to `KinRpcs` and `KIN_RPC_SCOPES`; `rpc.ts` and `RpcAuthorization.ts` already spread those. - `apps/server/src/server.ts` — Kin layer already added by the chat spec; approvals layers join `apps/server/src/kin/layer.ts`, not upstream. -- HTTP route for `/kin/mcp` — the same router hook the chat spec uses for Kin routes. - `apps/mobile/app.config.ts` — `["./plugins/withKinApprovalKey.cjs", { appAttestEnvironment }]` in `plugins`. RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read`; `challenge`, `submitGrant`, `reject` → `orchestration:operate`; `keyChallenge`, `registerKey`, `listKeys`, `revokeKey`, `kin.audit.list`, `kin.audit.verify` → `access:write`. Scopes are only the outer gate; the person and signature checks above are the real ones. @@ -603,8 +462,8 @@ RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read ## Interfaces to other specs - **Chat:** `KinOrgId`, `KinPersonId` (human `KinAuthor`), `KinChatMember` roles (owner lookup), `KinWidget` type `approval {actionId}` with the agent-field rejection, posting result messages, **Waiting on you** items. Chat spec owns the Kin migration runner and the Kin RPC/route hooks. -- **Lead:** registry of lead threads (for `request_action`), `KinEvent.id` (idempotency) and provenance, the stop switch (executor checks it), levels (`ceilingAllows`, and the `set_level` handler behind `kin.levels.raise`, never a lead's request), `change_rules` handler. -- **Triggers:** `pull_request` synchronize/closed webhooks → `refreshAction(actionId)`; `pull_request_review` → enables a card waiting on a GitHub review; `memory_purge` handler; Kin host setup (bot `gh` login, keychain items, hygiene check passing); upstream contract test for `GitHubRequestPolicy.credential` and `verifyDpopProof`. +- **Lead:** `KinEvent` provenance, the stop switch (executor checks it), levels (`ceilingAllows`, and the `set_level` handler behind `kin.levels.raise`, never a lead's request), `change_rules` handler. +- **Triggers:** `memory_purge` handler; upstream contract test for `verifyDpopProof`. - **Mobile:** renders `ApprovalCard` inside the chat screens; this spec ships the card, the native module and the signing hook. - **T3 auth (lane A), open hand-offs:** - `KinIdentity.resolve` returns each person's org role once members exist (CHAT-11). `registerKey` then refuses anyone but the owner and takes `startedByRole` from that role. Until then, `resolve` returns only the org owner, so the literal `"owner"` is accurate. @@ -620,22 +479,14 @@ RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read 7. `a grant for the old nonce fails after a new commit` → `stale`; card revision bumps. 8. `a grant older than 15 minutes is voided before execution`. 9. `a grant with exp more than 900 s after iat is rejected`. -10. `the head moving between approval and merge stops the merge` — precheck fails; and with precheck stubbed, GitHub's 409 from the `sha` field is mapped to `failed: head_moved`. -11. `two executors racing on one action run it once` — concurrent claims, one `kin_executions` row. -12. `a restart mid-merge reconciles to succeeded when GitHub shows it merged`, and `… to interrupted when it is still open`, with no second merge call. -13. `a replayed webhook and a deferral firing twice create one pending action`. -14. `request_action from a worker thread or an outside MCP client is refused` — not listed for them, so the call fails before the handler; a registered agent that isn't a lead in a running wake-up → `not_a_lead`. -15. `an agent-authored approval widget with extra fields is rejected by the chat service` (chat spec test, listed here). -16. `non-owners get the redacted card and no challenge`. -17. `change_rules requested under member provenance is refused at request_action`. -18. `privileged execution is refused while the credential hygiene check fails`. -19. `the merge token is never written to logs, audit, env or child processes` — grep the captured logs and spawned env in an integration test. -20. `the audit chain detects an edited row` (`kin.audit.verify`). -21. `the owner's phone with a trusted attestation can approve at once` (never without one, a teammate, an agent or another org's id), with the 10-key cap, replayed and cross-session challenges, retries, and Remove voiding what the key signed. -22. Mobile (`apps/mobile/modules/kin-approval-key`, device test): `signing without biometrics fails`, `re-enrolling biometrics invalidates the key`, `DER signatures convert to compact and verify on the server`, `only one signature at a time, under the grant's own text`, `an overlay over the sheet can't approve`, `a double tap can't land on Approve`, `a cover removed after the first tap can't approve` (including about 50 randomised-timer hides: Approve never enables less than 0.7 s after the cover goes), `a cover mounted after Approve arms and hidden on the first tap can't approve on the second`, `the app's own web-view picture in picture closes before the sheet shows and while it is up`, `system UI doesn't lock the sheet out`. The module's README has the checklist; its grant parser's vectors run without a device. -23. GitHub (`scripts/kin-rulesets.ts --test-23 --repo /`, after `--check` passes there): it refuses a Kin repository (`KIN_GITHUB_REPOS` or `GLDRoger/t3code`, in any case), a name without `scratch`, and a repository whose `GET /repos` `full_name` differs from `--repo` (a rename or transfer redirect). It needs a `v*` tag on the scratch repo and an Actions workflow that runs the required checks on pull requests. It takes a scratch-only fine-grained token of the owner's, checked by `OwnerMergeClient.save`'s probes (`--probe-pr ` names an existing PR for the review probe) and not stored, and mints a `server` App token (the only holder allowed `contents: write`), which it revokes at the end. The bot opens a PR; once the Actions checks pass and GitHub reports `mergeable_state: "blocked"`: `the merge token can't submit a review` (403); for both the bot and the merge token, `can't merge without a code-owner review` (405 naming the review), `can't push to the default branch` (422 "Repository rule violations", and the ref hasn't moved), `can't create or move a v* tag` (same), `can't bypass either ruleset` (reading one needs only Metadata, so the read may succeed, but must report `current_user_can_bypass: "never"` and no bypass actors), and `can't read a ruleset's history or change a ruleset` (403, or 404, which GitHub uses to hide endpoints a token can't use; the change sends the desired body, and drift is checked again afterwards). The owner approves and GitHub reports `clean`. Then bait and switch: the bot pushes, the owner's review shows `DISMISSED`, and the merge token's merge of the new head is blocked. The owner approves again and the merge token merges, which shows the blocks came from the rules. After the owner's review at the current head, a `server` holder's `contents: write` token could merge too: the ruleset doesn't limit who merges (threat model, open question 7); test 23 doesn't merge with it. The logic is tested against a fake GitHub in `apps/server/src/kin/github/rulesetsSetup.test.ts`; A rate-limited answer (429, or a 403 with `x-ratelimit-remaining: 0` or `retry-after`) never counts as a block: the run stops and says to try again later. GitHub's exact refusal messages are assumed there and confirmed by the first real run. On the same scratch repo, confirm the section 10 probe assumptions by hand: `--merge-token` accepts a Contents + Metadata token and refuses each broader one listed there; the review probe leaves no PENDING review on the probe PR (`GET /pulls/{n}/reviews` lists none from the owner afterwards); and `permissions.push` is false for a Contents: Read token. Run the section 10 sync flow once: push a branch whose merge commit changes `.github/workflows` with the owner's credential, have a `server` App token add the same-tree commit (`POST /git/commits`, then the ref update), and confirm GitHub accepts it without the Workflows permission and that the owner's approval then reports the PR `clean`. Also ask: can an App installation token with Pull requests write and no Contents write enable auto-merge (`enablePullRequestAutoMerge`) on a reviewed PR? If it can, a lead could merge without `contents: write`, and open question 7 needs another answer. Test 23 runs as the server's OS user, which on Linux can read the App's private key and mint unnarrowed tokens (threat model); it proves what the narrowed tokens can't do, not what code running as that user can't. - -Acceptance for phase 1: on `GLDRoger/t3code`, the lead requests a merge of a bot PR; the owner approves on the phone with Face ID; the GitHub review lands from the phone; the executor merges with the pinned SHA; the audit lists grant, device, SHA, provenance and merge commit. Tests 1–21 pass in CI; 22–23 pass on the release checklist. +10. `two executors racing on one action run it once` — concurrent claims, one `kin_executions` row. +11. `an agent-authored approval widget with extra fields is rejected by the chat service` (chat spec test, listed here). +12. `non-owners get the redacted card and no challenge`. +13. `the audit chain detects an edited row` (`kin.audit.verify`). +14. `the owner's phone with a trusted attestation can approve at once` (never without one, a teammate, an agent or another org's id), with the 10-key cap, replayed and cross-session challenges, retries, and Remove voiding what the key signed. +15. Mobile (`apps/mobile/modules/kin-approval-key`, device test): `signing without biometrics fails`, `re-enrolling biometrics invalidates the key`, `DER signatures convert to compact and verify on the server`, `only one signature at a time, under the grant's own text`, `an overlay over the sheet can't approve`, `a double tap can't land on Approve`, `a cover removed after the first tap can't approve` (including about 50 randomised-timer hides: Approve never enables less than 0.7 s after the cover goes), `a cover mounted after Approve arms and hidden on the first tap can't approve on the second`, `the app's own web-view picture in picture closes before the sheet shows and while it is up`, `system UI doesn't lock the sheet out`. The module's README has the checklist; its grant parser's vectors run without a device. + +Acceptance: the owner raises a lead's level from Settings, approves on the phone with Face ID, the executor applies it once, and the audit lists grant, device, provenance and outcome. The numbered server tests pass in CI; 22 passes on the release checklist. (Numbers 10, 12–14 and 17–19 and 23 belonged to the retired merge path.) ## Tasks @@ -643,52 +494,33 @@ Acceptance for phase 1: on `GLDRoger/t3code`, the lead requests a merge of a bot **APPR-2 Storage and state machine.** Tables, Kin migrations, `PendingActions.ts` with CAS transitions, idempotency key, nonce rotation, expiry sweep. Depends on: APPR-1, CHAT-2. Done when: transition tests (including 11 and 13) pass. Owner: backend. -**APPR-3 `request_action` tool.** `/kin/mcp` server, lead-only gate, server-side resolution of the PR, provenance capture, owner-only kinds. Depends on: APPR-2, LEAD-1, LEAD-5. Done when: tests 14 and 17 pass and a lead thread sees exactly one approvals tool (`request_action`) beside the chat tools. Owner: backend. - **APPR-4 Grant verification.** `GrantVerifier.ts` implementing checks 1–10, `challenge`, `submitGrant`, `reject` RPCs, audit on every rejection. Depends on: APPR-2, APPR-5. Done when: tests 1–9 pass. Owner: backend. **APPR-5 Approver keys.** Registry, `registerKey`/`listKeys`/`revokeKey`, App Attest and Keystore attestation verification (section 4), never storing an unattested key, revoke-on-session-revoke, `register_approver_key` handler with `hardware` and `attested` in its target. Depends on: APPR-1, APPR-2. Done when: tests 4 and 21 pass. Owner: backend. **APPR-6 Native approval key module.** `apps/mobile/modules/kin-approval-key` for iOS (Secure Enclave, `.biometryCurrentSet`, App Attest) and Android (Keystore, StrongBox fallback, `BiometricPrompt`, attestation chain); DER-to-compact; config plugin for `NSFaceIDUsageDescription` and the App Attest entitlement. Depends on: nothing. Done when: device tests in 22 pass on one iPhone and one Pixel, and a signature verifies with `p256.verify`. Owner: UI (native). -**APPR-7 Approval card and phone flow.** `approvePendingAction` (challenge, biometric sign and submit; the card itself is MOB-8), GitHub review from the phone with the device-flow token, "Approve on GitHub" fallback. Depends on: APPR-4, APPR-6, MOB-4. Done when: on a device, approving a test PR posts a GitHub review at the head SHA and moves the action to `approved`; a member account sees "Waiting on Nishchay" with no button (test 16 on the server). Owner: UI. - -**APPR-8 GitHub App and credentials.** `scripts/kin-github-app.ts` (manifest with the permission table), `KinGitHubApp.ts` (installation tokens, narrowing), `Keychain.ts`, owner merge token setup and expiry warning, `CredentialHygiene.ts`. Depends on: APPR-1. Done when: test 18 passes and `scripts/kin-github-app.ts --check` prints the App's permissions matching the table. Owner: backend. - -**APPR-9 Executor.** `ActionExecutor.ts`, handler registry, `merge_pull_request` and `delete_branch` handlers via `OwnerMergeClient.ts` (REST with `sha`), stop-switch check, startup reconciliation, result posting. Depends on: APPR-4, APPR-8, LEAD-11. Done when: tests 10–12 and 19 pass against a recorded GitHub fake, and one real merge on a scratch repo succeeds. Owner: backend. - -**APPR-16 Live GitHub identity probe.** The `T3GitHubIdentity` live layer (section 12) and the one-line `GitHubRequestPolicy` export from `@t3tools/source-control-github`, replacing `identityUnavailableLayer` in `approvals/layer.ts`; the hourly hygiene check with the owner's card. Depends on: APPR-8, APPR-9. Done when: on the Kin host, `CredentialHygiene.check` passes with only the bot's login and fails for each source given the owner's login. Owner: backend. +**APPR-7 Approval card and phone flow.** `approvePendingAction` (challenge, biometric sign and submit; the card itself is MOB-8). Depends on: APPR-4, APPR-6, MOB-4. Done when: on a device, approving a level raise moves the action to `approved`; a member account sees "Waiting on Nishchay" with no button (test 16 on the server). Owner: UI. -**APPR-10 Audit.** `Audit.ts` with hash chain, `kin.audit.list`/`verify`, entries from every step above. Depends on: APPR-2. Done when: test 20 passes and the acceptance merge shows a complete trail. Owner: backend. +**APPR-9 Executor.** `ActionExecutor.ts`, handler registry, stop-switch check, startup reconciliation, result posting. Depends on: APPR-4, LEAD-11. Done when: test 11 passes. Owner: backend. -**APPR-11 Rulesets and CODEOWNERS.** `scripts/kin-rulesets.ts` apply and `--check` drift mode, tag ruleset, CODEOWNERS check. Depends on: APPR-8. Done when: test 23 passes on a scratch repo and `--check` reports no drift on `GLDRoger/t3code`. Owner: backend. +**APPR-10 Audit.** `Audit.ts` with hash chain, `kin.audit.list`/`verify`, entries from every step above. Depends on: APPR-2. Done when: test 20 passes and the acceptance run shows a complete trail. Owner: backend. Later, marked by phase: -**APPR-12 (phase 3) Delegations (9.6).** `set_delegation` kind and handler; `KinDelegation {orgId, grantee, kinds, scope: {repo, paths?, labels?}, expiresAt, signedBy}`; a matching delegation lets the grantee's own signed grant meet `requiredApprovers`; list and one-tap revoke. Depends on: APPR-4, APPR-9. Done when: a delegated docs merge by a member succeeds, an out-of-scope one fails `not_owner`, and revoked delegations stop working at once. Owner: backend. +**APPR-12 (phase 3) Delegations (9.6).** `set_delegation` kind and handler; `KinDelegation {orgId, grantee, kinds, scope: {repo, paths?, labels?}, expiresAt, signedBy}`; a matching delegation lets the grantee's own signed grant meet `requiredApprovers`; list and one-tap revoke. Depends on: APPR-4, APPR-9. Done when: a delegated action by a member succeeds, an out-of-scope one fails `not_owner`, and revoked delegations stop working at once. Owner: backend. -**APPR-13 (phase 3) L3 risk gate (10).** Path and label classifier (`auth`, `security`, migrations, `.github/**` are never low-risk) used by delegations and by any future merge request from a lead. Depends on: APPR-12, LEAD-8. Done when: a fixture list of PRs classifies as expected. Owner: backend. +**APPR-13 (phase 3) L3 risk gate (10).** Path and label classifier (`auth`, `security`, migrations, `.github/**` are never low-risk) used by delegations. Depends on: APPR-12, LEAD-8. Done when: a fixture list of PRs classifies as expected. Owner: backend. -**APPR-14 (phase 3) Next of kin (9.9).** `set_next_of_kin` (owner-signed, max two, can't name self), escalation timer (2 h default or owner away) with a 30-minute warning, undo-only default scope (revert merge, roll back deploy, pause routines), any owner answer cancels, return summary in the owner's direct chat. Next of kin must also be a GitHub code owner. Depends on: APPR-12, TRIG-3. Done when: a simulated outage hands a revert to the next of kin after the wait, and an owner tap during the wait cancels it. Owner: backend. +**APPR-14 (phase 3) Next of kin (9.9).** `set_next_of_kin` (owner-signed, max two, can't name self), escalation timer (2 h default or owner away) with a 30-minute warning, undo-only default scope (revert merge, roll back deploy, pause routines), any owner answer cancels, return summary in the owner's direct chat. Depends on: APPR-12, TRIG-3. Done when: a simulated outage hands a revert to the next of kin after the wait, and an owner tap during the wait cancels it. Owner: backend. -**APPR-15 (phase 5) Two-key approvals for outside agents (9.8).** `admit_outside_agent` with a signed manifest; `requiredApprovers` = credential owner and resource owner; cards show "Waiting on Priya, then Nishchay"; an agent key can never be an approver key. Depends on: APPR-12, chat spec's outside-agent membership. Done when: a merge from an outside agent needs both grants and fails with either one alone. Owner: backend. +**APPR-15 (phase 5) Two-key approvals for outside agents (9.8).** `admit_outside_agent` with a signed manifest; `requiredApprovers` = credential owner and resource owner; cards show "Waiting on Priya, then Nishchay"; an agent key can never be an approver key. Depends on: APPR-12, chat spec's outside-agent membership. Done when: an action from an outside agent needs both grants and fails with either one alone. Owner: backend. ## Design corrections 1. **T3's device key is not hardware-backed or biometric-gated.** DESIGN 9.2 says the grant is signed by "a DPoP-style key in the Secure Enclave or Keystore". The existing mobile DPoP key (`apps/mobile/src/features/cloud/dpop.ts`) is a software key in `expo-secure-store`, used only for the managed relay. Kin needs a new, separate approval key and a new native module (APPR-6). 2. **T3 sessions have no person or role.** `SessionClaims` carry scopes and a label `sub`. "The signer has the owner role" has to come from Kin's membership (chat spec), with keys bound to a person. -3. **T3's merge path doesn't pin the head SHA.** `GitHubPullRequestApi.runAction` sends `expectedHeadOid` only when it rewrites the merge body, and switches to auto-merge on merge-queue repos. The executor must call `PUT /pulls/{n}/merge` with `sha` itself and refuse merge queues in phase 1. -4. **Agents can reach whatever GitHub login the server has.** Provider CLIs run as the server's user and inherit its `gh` login and `GH_TOKEN`. "Agents never hold the owner's GitHub token" only holds if the Kin machine's `gh` identity is the bot (hygiene check, section 12). -5. **"The owner's real approval on GitHub" needs a source.** DESIGN 9.5 requires a code-owner review but doesn't say who submits it. If the server held a token able to review, a compromised server could approve and merge. This spec splits it: the server's token can merge but not review (Contents: write only); the review comes from the phone, or from the owner on GitHub. -6. **Ruleset bypass must be empty, even for the owner.** Otherwise the owner's merge token bypasses review. The cost: PRs the owner writes by hand need someone else's review or a temporary bypass (open question 2). -7. **`request_action` can't go in upstream `layerTools`.** That list is advertised to every thread and measured by `AgentContextBudget.test.ts`. It gets a Kin-only MCP endpoint. ## Open questions -1. The phone needs a GitHub user token for the Kin App (device flow, once). Is that acceptable, or should phase 1 start with "Approve on GitHub" only and add the phone token later? -2. Owner-written PRs under an empty bypass list: route them through the bot, or add a time-boxed bypass toggled by an owner-signed action? Upstream syncs make this urgent: once `kin-main` is on `GLDRoger/t3code`, `KIN.md`'s `git push origin main kin` is rejected, a sync PR the owner opens has no code owner left to approve it, the bot can't open one because upstream merges change `.github/workflows` (no Workflows permission), and squash-only would flatten the upstream merge so the next sync conflicts. Decide before applying the ruleset there; one option is `allowed_merge_methods: ["squash", "merge"]` plus a second code owner for sync PRs. **Proposed resolution, owner to confirm:** the sync flow in section 10, where the owner pushes `sync/`, the bot pushes a same-tree commit on top and opens the PR, and the owner approves and merge-commits it. This keeps `require_last_push_approval` on and needs `merge` allowed, as `kinRulesets` now has. -3. Merge-queue repos: support `enablePullRequestAutoMerge` with `expectedHeadOid` later, or keep refusing? -4. Should the executor run as a separate OS user with its own keychain, so code running as the Kin server's user can't read the merge token at all? Phase 1 relies on the token being unable to review. The same holds for the App's private key: on Linux, and on any host where agents run as the server's OS user, an agent can read `kin-github-app` from the keychain and mint installation tokens that `installationToken` never narrowed, with the App's full permission table. It can also find an SSH agent socket or other credentials that user holds. A separate executor OS user that alone holds the keychain items, and only the narrowing service hands out tokens, is the real fix. -5. Desktop approvals: a Touch ID-gated Secure Enclave key on macOS through a native addon, or phone-only for good? -6. The Kin host is headless Linux. `@napi-rs/keyring` 1.3.0 uses the Secret Service there and, when none answers, silently falls back to kernel keyutils, which keeps items only in kernel memory (gone after a reboot), with no option to pin the backend. `Keychain.ts` therefore pings `org.freedesktop.secrets` on the session bus (`dbus-send`, else `gdbus`) before every Linux operation and fails with `KinKeychainError` (`secret_service`) when nothing answers; `kin-github-app.ts` checks this before the manifest flow and before asking for the merge token. Open: run a Secret Service (for example `gnome-keyring-daemon` unlocked at boot) for the `kin` user, or fall back to `ServerSecretStore` files (mode 0600, the encrypted backup volume)? -7. A worker's `contents: write` token can merge a PR once the owner has reviewed its head, because the ruleset checks the review, not who merges. Options: (a) a lead never gets a write token. Done in phase 1 for leads and workers: `installationToken` refuses `contents: write` for every holder but `server`, so no agent holds a write token. Workers can't push with the App yet; a server-side push helper that holds the `server` token is still to be built. (b) A ruleset "Restrict updates" rule on the default branch with the owner's merge path as the only bypass actor. This contradicts the empty bypass list (design correction 6), so the bypass would have to be the merge token's identity alone. (c) A merge queue, so only the queue merges; this needs open question 3 answered first. +1. Desktop approvals: a Touch ID-gated Secure Enclave key on macOS through a native addon, or phone-only for good? diff --git a/docs/kin/specs/lead.md b/docs/kin/specs/lead.md index 0bf6c9b8a0279..e050aaffa444a 100644 --- a/docs/kin/specs/lead.md +++ b/docs/kin/specs/lead.md @@ -1,6 +1,6 @@ # Lead spec -Status: draft, 7 Nov 2026. Covers DESIGN.md sections 3, 4 (the `Memory` interface and how the lead reads and writes kin-memory), 10, and section 12 gaps 1, 2, 3 and 6. Dreaming, routine scheduling, webhooks and the memory secret scanner belong to the triggers spec. `request_action` and grants belong to the approvals spec. Chat records and RPC belong to the chat spec. +Status: draft, 7 Nov 2026. Covers DESIGN.md sections 3, 4 (the `Memory` interface and how the lead reads and writes kin-memory), 10, and section 12 gaps 1, 2, 3 and 6. Dreaming, routine scheduling, GitHub events and the memory secret scanner belong to the triggers spec. Pending actions and grants belong to the approvals spec. Chat records and RPC belong to the chat spec. ## Goal @@ -43,12 +43,12 @@ Kin services live in `apps/server/src/kin/`. - `LeadPrompt`: builds the first message of each wake-up. - `KinLeadToolkit`: the MCP tools the lead calls. - `Memory` (`apps/server/src/kin/memory/`): reads, the front matter cache, and the git writer. -- `WorkerTracker`: follows each worker's thread in the worker environment and turns its final message into a `WorkerReport` event. +- `DelegatedTasks` and `TaskWake`: a card and a charge for each task a lead delegates, and its end turned into a `task.finished` event. - `KinBudget`, `KinStop`, `KinLevels`. ### Records -Top-level server records carry `orgId`; memory front matter and nested worker reports inherit organization context. Schemas live in **new** `packages/contracts/src/kinLead.ts`. `KinOrgId`, `KinAgentId`, `KinChatId`, `KinMessageId` and `KinAuthor` come from the chat spec (`kinChat.ts`). A lead is a `KinAgent` with role `lead`; `kin_leads` stores its config keyed by that same `agentId`, not a separate lead identity. Server-generated timestamps use `CanonicalUtcTimestamp`, validated as `YYYY-MM-DDTHH:mm:ss.sssZ`; SQLite stores time-comparison columns as INTEGER epoch milliseconds. Front matter dates remain permissive strings. Event, worker and memory item ids use `TrimmedNonEmptyString` brands (`KinEventId`, `KinWorkerId`, `KinMemoryItemId`). +Top-level server records carry `orgId`; memory front matter inherits organization context. Schemas live in **new** `packages/contracts/src/kinLead.ts`. `KinOrgId`, `KinAgentId`, `KinChatId`, `KinMessageId` and `KinAuthor` come from the chat spec (`kinChat.ts`). A lead is a `KinAgent` with role `lead`; `kin_leads` stores its config keyed by that same `agentId`, not a separate lead identity. Server-generated timestamps use `CanonicalUtcTimestamp`, validated as `YYYY-MM-DDTHH:mm:ss.sssZ`; SQLite stores time-comparison columns as INTEGER epoch milliseconds. Front matter dates remain permissive strings. Event, worker and memory item ids use `TrimmedNonEmptyString` brands (`KinEventId`, `KinWorkerId`, `KinMemoryItemId`). ```ts export const KinLevel = Schema.Literals(["L0", "L1", "L2", "L3"]); @@ -104,7 +104,7 @@ const EventBase = { agentId: KinAgentId, // the chat's lead, or the one liveLead picks (Several leads) receivedAt: CanonicalUtcTimestamp, dedupeKey: Schema.NullOr(TrimmedNonEmptyString), // unique per org; replays are dropped - provenance: KinAuthor, // server-verified; webhooks and timers are "system" + provenance: KinAuthor, // server-verified; GitHub events and timers are "system" }; export const KinLeadRoutine = Schema.Literals(["morning_brief", "evening_summary", "owner_check"]); @@ -158,10 +158,13 @@ export const KinEvent = Schema.Union([ finding: Schema.String, itemIds: Schema.Array(KinMemoryItemId), }), - Schema.TaggedStruct("worker.report", { + // T3's notice that tasks a lead's thread delegated ended; the wake-up takes over T3's run. + Schema.TaggedStruct("task.finished", { ...EventBase, - workerId: KinWorkerId, - report: WorkerReport, + threadId: ThreadId, + messageId: MessageId, + taskIds: Schema.Array(NodeId), + chatId: KinChatId, }), // Only for an entry its owner gave this lead, or closed or took back from it (Work, below). Schema.TaggedStruct("record.changed", { @@ -194,17 +197,17 @@ export const KinEvent = Schema.Union([ ]); ``` -Events carry references, not bodies. The lead reads the message or payload through its tools, so the queue never holds large or secret text. `scheduledTaskId` and `webhookDeliveryId` identify the stored payload for `ScheduledTaskService.getWebhookDelivery`. `deliveryId` is GitHub’s `x-github-delivery` header; the inbox consumer uses `deliveryId` as the event’s `dedupeKey` for `github` events and `KinTriggerFired.fireId` for other kinds. The `deferral.due.subject` union directly mirrors the triggers spec’s deferral (including `phase`), reminder and followup subjects, plus `scheduled_task` (`itemId`, `runId`) for a scheduled run; `lateByMs` is a non-negative integer. +Events carry references, not bodies. The lead reads the message or payload through its tools, so the queue never holds large or secret text. A `github` event's `deliveryId` is the watch's trigger key (`poll:`) and its `dedupeKey`; `scheduledTaskId` and `webhookDeliveryId` appear only on events the retired App webhook queued. Other kinds use `KinTriggerFired.fireId`. The `deferral.due.subject` union directly mirrors the triggers spec’s deferral (including `phase`), reminder and followup subjects, plus `scheduled_task` (`itemId`, `runId`) for a scheduled run; `lateByMs` is a non-negative integer. | Source | Event | Producer | | ------------------------------------------------------------------------------ | ----------------- | --------------------------------------------------------- | | A person posts in a chat the lead is in | `chat.message` | this spec (`ChatWake`), for the lead the floor would pick | | A tap on a widget | `widget.action` | this spec (`ChatWake`) | -| GitHub webhook | `github` | triggers spec | +| The owner's GitHub watch | `github` | triggers spec | | `once` trigger on a deferral | `deferral.due` | triggers spec | | `fixed_time` routine | `routine` | triggers spec (content below) | | `interval` watchdog | `watchdog` | triggers spec | -| Worker run ends | `worker.report` | this spec (`WorkerTracker`) | +| Tasks a lead delegated end | `task.finished` | this spec (`TaskWake`) | | The owner gives a lead a Work entry, or closes or takes back one it holds open | `record.changed` | this spec (`KinRecords`) | | Executor finishes or a grant expires | `action.resolved` | approvals spec | | Stop switch turned off | `resume` | this spec | @@ -226,7 +229,7 @@ Priority (gap 2), set by code from the tag and provenance, never by a model: | P | Events | | --- | ------------------------------------------------------------------------------------------ | | P0 | `chat.message` or `widget.action` from the owner of a non-retired lead; `resume` | -| P1 | `deferral.due`; `action.resolved`; `worker.report`; a `chat.message` passed on by a lead | +| P1 | `deferral.due`; `action.resolved`; `task.finished`; a `chat.message` passed on by a lead | | P2 | Non-owner `chat.message` and `widget.action` (including agents); `github`; `routine` | | P3 | `watchdog` (chasing, stale reviews) | | P4 | dreaming (the triggers spec asks `KinBudget.admit(orgId, "P4")`; it is not a lead wake-up) | @@ -283,7 +286,7 @@ If the lead writes files by hand in the read checkout, step 9's reset throws the Kin boot is optional: configuration, migrations, identity bootstrap and runner startup failures are logged with typed errors and disable Kin, never the core T3 runtime. The runner is constructed in `kin/layer.ts` when `KIN_MEMORY_REPOSITORIES` is non-empty, with the real `KinLeadPrompt` implementation. A dev server with it unset makes and uses a local seeded repo in its state directory (`memory/devMemory.ts`); an installed host with it unset runs no agent, logs why once, and answers each chat with an agent with one line saying so. Memory repositories are supplied through `KIN_MEMORY_REPOSITORIES` (a JSON array of `{ orgId, repoUrl }`); no private repository is assumed by source code. -The scheduled-task dispatch wrapper also contains Kin migration failures. When Kin persistence is unavailable, launch refusal is limited to `scheduled-task::webhook:` command ids. Sends classify the task using upstream `scheduled_tasks.schedule_json` and refuse only webhooks; an unreadable upstream row fails closed for that send only. Cron, interval, manual and ordinary dispatch remain available. Restoring the Kin database and restarting restores webhook dispatch. +The scheduled-task dispatch wrapper also contains Kin migration failures. While Kin persistence is unavailable it refuses only Kin's own tasks (`scheduled-task:kin:` ids); every other task, cron, interval, manual or webhook, runs as before. A `MemorySyncConflict` fails the wake-up and leaves the events queued with the queue's five-minute counted-failure backoff. `MemoryCheckoutInvalid` does the same and logs an error; `KinWakeupHooks.memoryCheckoutInvalid` is the typed notification hook for LEAD-3. Writer commits/journal/reset and budget charging remain LEAD-3 and LEAD-10 integrations, not fabricated runner implementations. The runner records the writer's commit in `memory_commit` after each wake-up's commit. `tokens_json` contains each provider turn's cumulative `turnTokenUsage` ledger and fallback `usedTokens` and provider-turn id, limited to the wake-up run's attempts, on success and failure. @@ -323,34 +326,29 @@ The file is the source; this section records only the decisions behind it. Agent bearer tokens are endpoint-bound: they authenticate only on `/kin/mcp` and are rejected with 401 on `/mcp`. Non-agent T3 session tokens continue to authenticate on `/mcp`. -The `/kin/mcp` endpoint deliberately exposes only Kin tools, never T3 tools (including scheduling and thread launch), so leads cannot bypass server authority; worker launch comes through the server-only LEAD-9 path. +The `/kin/mcp` endpoint serves Kin's tools and some of T3's. An owner-only thread also lists the T3 tools in `LEAD_T3_TOOLS` (`t3Tools.ts`: `delegate_task`, projects, worktrees, PR links, browser and devices); a shared thread lists none. Scheduling, new top-level threads, secret requests and environment links are never listed, so a lead can't start work outside Kin's chats. **New** `apps/server/src/kin/lead/mcp/tools.ts` and `handlers.ts`, served on Kin's own `/kin/mcp` endpoint (set up in CHAT-7 and shared with the approvals spec), not in upstream's `layerTools`. Registered Kin agent threads are given that endpoint, but only registered lead threads see the lead toolkit; each call is checked with `KinIdentity.resolveAgent`, binding the server-resolved `McpInvocationContext.thread.threadId` to the persisted running wake-up's current non-terminal run, rejecting subagents. Other threads never see these tools, so `AgentContextBudget.test.ts` stays unchanged. Each handler derives `{ orgId, agentId }` from that identity and `wakeupId` from its matching running database row, never from tool input, so a lead can't act for another organization. -| Tool | Input (sketch) | What it does | -| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `kin_chat_post` | `{ chatId, text, widget?, replaceMessageId? }` | Calls the chat spec's `KinChatService.postAgentMessage` with author `{ kind: "agent", agentId }`. `replaceMessageId` updates a widget in place. | -| `kin_ask` | `{ question, options: 2–4 × { label, kind?: "yes" \| "no" }, detail? }` | Posts a native `choice` card in the wake-up's lane under the same floor, flood and level rules as a text reply, so it counts as the reply. The owner's tap settles it once and wakes the lead with `Chose "