Skip to content

Identity propagation — canonical platform:id from channels through the agent - #119

Merged
FMXExpress merged 2 commits into
mainfrom
claude/identity
Jun 1, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/identity

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Ports picoclaw's pkg/identity/identity.go pattern: every inbound channel message gets tagged with <platform>:<id> (e.g. slack:U12345, telegram:5551234, matrix:@eli:matrix.org), threaded through TToolLoopConfig, and optionally gated by an allow_senders config array. Was the one genuine parent-feature gap from the empty-dir audit — picoclaw has full identity plumbing through every channel + session keying + IsAllowedSender. ~320 LOC.

What's new

  • src/pkg/identity/PasClaw.Identity.pas — TIdentity record (Source, UserId, UserName, RoomId), BuildCanonicalID / ParseCanonicalID (first-colon-split so Matrix MXIDs survive), MakeIdentity, CanonicalOf, FormatIdentity, IsAllowedSender with * and <platform>:* wildcard patterns.

  • TToolLoopConfig.Identity — per-turn canonical identity. RunToolLoop logs toolloop start identity=… at turn start when populated (empty identity logs nothing to keep CLI / cron quiet).

  • TConfig.AllowSenders: array of string — operator allowlist; ser/deser; stays out of ToJSON when empty.

  • All 7 channels wired — each extracts the platform-native sender id at the inbound boundary, builds a TIdentity, calls IsAllowedSender(LoopCfg.Identity, FCfg.AllowSenders) BEFORE RunToolLoop. Rejected senders are dropped at the boundary with a log line; the model never sees them.

    Channel Source UserId extras
    Telegram telegram chat.id (as string) —
    Discord discord author.id UserName=username, RoomId=channel
    LINE line source.userId/groupId/roomId —
    WhatsApp whatsapp from (phone) —
    Matrix matrix sender (MXID) RoomId=room_id
    IRC irc nick RoomId=channel-or-PM-target
    Email email From: address —
  • Cmd.Agent stamps cli:$USER (POSIX) / cli:%USERNAME% (Windows), falling back to cli:local so the canonical id is never empty.

  • Gateway stamps gateway:anon at all 3 RunToolLoop sites. Header-derived identity is a follow-up alongside gateway auth — terminating an unauthenticated socket, client-asserted headers can't be trusted to gate by yet.

allow_senders config

"allow_senders": [
  "slack:U-eli",
  "telegram:*",
  "matrix:@eli:matrix.org",
  "cli:*"
]

Patterns are exact canonical ids or <platform>:* wildcards; bare * matches anyone. Empty array (default) = no gate, matching picoclaw's pkg/channels/base.go IsAllowedSender default-allow semantics.

Out of scope (v2)

  • Subagent identity propagation. Parent loop logs its identity at start, so the audit chain is intact through the spawn boundary; but the child RunToolLoop inherits empty identity since the parent's per-turn identity isn't on the stored TSubagentContext. Wiring this is one field + one assignment but I left it for v2 since spawn is parent-scoped already.
  • Gateway header-derived identity (X-PasClaw-Identity: slack:U123). Needs request signing to be safe to gate on; punt with gateway auth work.

Test plan

  • make clean && make clean (442213 lines)
  • make smoke 11/11 OK
  • Focused identity test (built, ran, removed): 6 groups — canonical compose/parse incl. Matrix MXID, MakeIdentity overloads, FormatIdentity (empty / no UserName / with UserName), IsAllowedSender (empty list / * / exact / <platform>:* / mixed / unknown-identity-deny-without-*), AllowSenders JSON roundtrip, defaults-out-of-ToJSON
  • pasclaw agent starts cleanly with cli:$USER identity (live spot check)
  • Manual: live pasclaw agent against a real Telegram bot with allow_senders: ["telegram:<my-chat-id>"] — confirm non-allowlisted senders get the boundary-reject log line and don't reach the model
  • Manual: pasclaw gateway /v1/chat/completions request shows up in logs as gateway:anon

Generated by Claude Code

…h the agent

Ports picoclaw's pkg/identity pattern (BuildCanonicalID + per-channel
SenderInfo + IsAllowedSender allowlist) so embedder hooks and audit
logs can attribute each turn to the user that triggered it, and
channels can refuse non-allowlisted senders before invoking the
model. ~250 LOC.

  - New src/pkg/identity/PasClaw.Identity.pas: TIdentity record
    (Source, UserId, UserName, RoomId), BuildCanonicalID +
    ParseCanonicalID (rightmost-colon-safe so Matrix MXIDs survive),
    MakeIdentity, CanonicalOf, FormatIdentity, IsAllowedSender
    with `*` and `<platform>:*` wildcard patterns. Empty allowlist
    = no gate (matches picoclaw's channel/base.go default).
  - TToolLoopConfig.Identity field; RunToolLoop logs
    "toolloop start identity=…" at turn start when populated (empty
    identity logs nothing — keeps CLI / cron noise low).
  - TConfig.AllowSenders: array of string with JSON ser/deser. Stays
    out of ToJSON when empty (stock configs remain tidy).
  - All 7 channels wired (Telegram chat id, Discord author id +
    username + channel id, LINE source id, WhatsApp from-number,
    Matrix sender MXID + room id, IRC nick + reply target, Email
    From addr). Each channel calls IsAllowedSender immediately
    after building TIdentity; rejected senders are logged + skipped
    BEFORE RunToolLoop, never reaching the model.
  - Cmd.Agent sets `cli:$USER` (or `cli:local` if unset / Windows
    %USERNAME% if MSWINDOWS); the gateway sets `gateway:anon` at all
    three RunToolLoop sites since gateway terminates an unauthenticated
    socket and client-asserted headers can't be trusted yet (header-
    derived identity is a follow-up alongside gateway auth).
  - Subagents currently inherit empty identity (parent's per-turn
    identity isn't exposed to the spawn tool's stored context); the
    parent loop logs its identity at start, so the audit chain is
    intact. Threading identity into TSubagentContext is a v2 extension.

Verified with a focused test (created, built, ran, removed) covering
all six assertion groups: canonical compose/parse, MakeIdentity
overloads, FormatIdentity edge cases (empty, no UserName, with
UserName), IsAllowedSender (empty list, `*`, exact, `<platform>:*`,
mixed, unknown-identity-deny-without-`*`), and TConfig.AllowSenders
JSON roundtrip + defaults-out-of-ToJSON.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 12dc2442c8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Exit;
end;

LoopCfg.Identity := MakeIdentity('telegram', IntToStr(ChatId));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Gate Telegram group messages by the actual sender

When the bot is added to a Telegram group, chat.id identifies the group rather than the user who sent the message. As a result, allowing telegram:<group-id> permits every member of that group to invoke the agent and its tools, while it is impossible to allow only selected group members. Parse message.from.id for Identity.UserId and keep chat.id separately as the room or reply target.

Useful? React with 👍 / 👎.

client-asserted and unsafe to gate on. Stamp 'gateway:anon' so
downstream hooks/logs see SOMETHING; tightening this is a
follow-up alongside gateway auth. }
LoopCfg.Identity := MakeIdentity('gateway', 'anon');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the system prompt on the legacy chat route

On the gateway's HandleChat route, adding gateway:anon replaced the existing LoopCfg.Options.SystemPrompt := BuildSystemPrompt(...) assignment instead of being added alongside it. Requests to this route now run without the configured PasClaw system prompt, unlike /v1/chat/completions and /v1/responses, which can change persona and tool-use behavior for existing clients.

Useful? React with 👍 / 👎.

Comment on lines +397 to +401
if not IsAllowedSender(LoopCfg.Identity, FCfg.AllowSenders) then
begin
LogInfo('email: sender %s rejected by allow_senders',
[FormatIdentity(LoopCfg.Identity)]);
Continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark globally rejected emails as seen

When an email passes the existing MatchesAllow check but fails the new global allow_senders check, this Continue skips the IMAP.StoreFlags(..., [mfSeen]) call. Because the message was fetched with RetrievePeek, it remains unseen and is fetched and rejected again on every poll indefinitely. Mark it seen here, as the earlier channel-specific rejection branch already does.

Useful? React with 👍 / 👎.

Comment on lines +130 to +137
StarPos := Pos('*', Pattern);
if StarPos = 0 then Exit(False);
{ Only suffix wildcards supported — '<platform>:*' or '<platform>:<x>*'.
Match by prefix (everything up to but not including the star). }
Prefix := Copy(Pattern, 1, StarPos - 1);
Result := (Prefix <> '')
and (Length(Canon) >= Length(Prefix))
and (Copy(Canon, 1, Length(Prefix)) = Prefix);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject wildcard patterns with trailing characters

For an accidentally malformed allowlist entry such as telegram:*admin, Pos('*', Pattern) finds the star and the matcher compares only the telegram: prefix, silently allowing every Telegram sender. The comment and README describe suffix wildcards, so patterns containing a star anywhere except the final position should fail closed rather than broadening access.

Useful? React with 👍 / 👎.

Comment on lines +77 to +81
Hooks read Cfg.Identity to gate behaviour by sender. The
allowlist check (PasClaw.Identity.IsAllowedSender) is run by
the channel BEFORE RunToolLoop — by the time the loop is
called, the operator has already approved this sender. *)
Identity: TIdentity;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Expose the propagated identity to hooks

The new field is documented as allowing hooks to gate behavior by sender, but none of the hook callbacks receive Cfg or an identity: BeforeTurn, BeforeToolCall, AfterToolResult, and OnError in PasClaw.Agent.Hooks retain their previous signatures, and the dispatch helpers pass only their existing arguments. Consequently, registered hooks cannot inspect the per-turn identity despite the newly documented API behavior. Thread the identity into the hook callbacks or provide an equivalent per-turn context.

Useful? React with 👍 / 👎.

LoopCfg.Fallbacks := ResolveFallbacks(FCfg);
LoopCfg.Options := DefaultChatOptions;
ApplyPromptCacheConfig(LoopCfg.Options, FCfg.PromptCache);
LoopCfg.Identity := MakeIdentity('gateway', 'anon');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stamp identity on the responses tool-loop path

The added gateway identity assignment covers HandleChat and /v1/chat/completions, but the internal-tool-loop branch of /v1/responses still calls RunToolLoop at PasClaw.Gateway.Server.pas:3034 without setting LoopCfg.Identity. Requests to that endpoint therefore remain unattributed in the new audit log while equivalent gateway requests log gateway:anon. Add the same assignment when configuring that branch.

Useful? React with 👍 / 👎.

…ty, email mark-seen, wildcard fail-closed, hook identity

Six Codex findings on the identity PR — all legit, all addressed
in place on PR #119.

  P1 — Telegram from.id vs chat.id. message.chat.id identifies the
  GROUP in group chats, not the sender — keying TIdentity.UserId
  on chat.id let every group member through a single allowlist
  entry. Now parse message.from.id for UserId (+ from.username
  for UserName); chat.id rides on RoomId so room-level filters
  still work. allow_senders entries can finally gate per-user in
  groups.

  P2 — Gateway HandleChat dropped its system prompt. The identity
  edit overwrote the existing
  `LoopCfg.Options.SystemPrompt := BuildSystemPrompt(...)` line
  instead of being added alongside, so HandleChat requests started
  running without the PasClaw persona while /v1/chat/completions
  and /v1/responses kept theirs. Re-added — three of three gateway
  routes now stamp identity AND inject the system prompt.

  P2 — Email rejected via global allow_senders stayed unseen.
  After RetrievePeek (no mark-seen) the rejection branch called
  Continue without IMAP.StoreFlags(..., [mfSeen]); the same
  message would get re-fetched and re-rejected on every poll
  forever. Mark seen before Continue (matches the existing
  channel-specific MatchesAllow rejection branch above).

  P2 — Wildcard pattern fail-closed. MatchPattern used to extract
  the prefix from any `*` position, so a typo like "telegram:*admin"
  silently broadened to every Telegram user. Now require `*` to be
  the LAST character of the pattern; any mid-string star matches
  nothing. Suffix wildcards ("telegram:*") still work; bare "*"
  still works.

  P2 — Hook identity surface. The doc claimed hooks could gate
  by sender but no callback received Cfg or Identity — so a
  TPasClawHook subclass had no way to read the per-turn id.
  Added a public Identity: TIdentity field on TPasClawHook;
  RunToolLoop now writes it onto every registered hook once per
  loop, before any BeforeTurn / BeforeToolCall / AfterToolResult /
  OnError dispatch. Hooks read `Self.Identity` from any virtual
  — no signature change to existing hook subclasses, fully
  backwards-compatible.

  P2 — /v1/responses internal-tool-loop branch missed the identity
  stamp. HandleChat and /v1/chat/completions both got
  `LoopCfg.Identity := MakeIdentity('gateway', 'anon')`; the third
  RunToolLoop site (internal-tools branch of /v1/responses) didn't.
  Audit log was inconsistent. Added.

Verified with a focused test (created, built, ran, removed) covering
the three runtime-verifiable fixes: Telegram from.id keys the
allowlist (Eli is allowed, Bob in the same group is rejected),
malformed mid-string wildcards fail closed across multiple shapes
(telegram:*admin, *:admin, tele*ram:U-eli), and TPasClawHook subclass
reads Self.Identity from BeforeTurn. The three compile-checked fixes
(gateway SystemPrompt re-add, email mark-seen, /v1/responses
identity) are kept honest by the build itself + the line-by-line
diff review.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit 73e3a28 into main Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants