Skip to main content

trusty_memory/
attribution.rs

1//! Drawer creator-attribution tag helpers.
2//!
3//! Why: prior to this module, drawers carried content, room, importance,
4//! and free-form tags but no first-class metadata describing the writer.
5//! Operators who saw noise drawers in a palace had no way to trace which
6//! client wrote them — was it the trusty-memory MCP, a curl from a shell
7//! script, claude-mpm's Python hook, the dashboard form? This module
8//! defines a reserved `creator:*` tag namespace that every write path
9//! (HTTP, MCP, CLI, hook) attaches automatically. With `creator:client=…`
10//! present on every drawer, "where did this come from?" becomes
11//! grep-able. The namespace approach (vs. a `Drawer` schema change)
12//! piggy-backs on the existing `msg:` tag pattern from #99 so no
13//! migration is required.
14//!
15//! What:
16//!   - `CREATOR_*_PREFIX` constants — the four reserved tag prefixes.
17//!   - [`CreatorInfo`] — small value type carrying client name, version,
18//!     source, and optional cwd. `into_tags()` renders the four tag
19//!     strings (or three, when cwd is absent) in a stable order.
20//!   - [`is_creator_tag`] — predicate used by UI render code that wants
21//!     to hide the namespace from the main tag chips (mirroring how
22//!     `msg:*` is filtered today).
23//!
24//! Test: see the `tests` module at the bottom — covers tag composition,
25//! prefix detection, and round-trip via `is_creator_tag`.
26//!
27//! # Spec References
28//!
29//! - [`SPEC-WSCLAIM-03~draft`](docs/specs/DOC-53-workstream-claim-drawer-convention.md#SPEC-WSCLAIM-03~draft) (§4 workstream-attributed memory)
30
31use crate::ActivitySource;
32
33/// Tag prefix carrying the writing client's short name
34/// (e.g. `creator:client=trusty-memory-mcp`).
35///
36/// Why: the dominant question "who wrote this drawer?" reduces to a
37/// single substring search against this prefix. Stable string so curl
38/// and grep workflows keep working over time.
39/// Test: `creator_info_renders_all_fields`.
40pub const CREATOR_CLIENT_PREFIX: &str = "creator:client=";
41
42/// Tag prefix carrying the writing client's version string
43/// (e.g. `creator:version=0.5.1`).
44///
45/// Why: lets operators distinguish "old buggy client wrote this" from
46/// "current client wrote this" without rummaging through logs.
47/// Test: `creator_info_renders_all_fields`.
48pub const CREATOR_VERSION_PREFIX: &str = "creator:version=";
49
50/// Tag prefix carrying the originating subsystem (`http`/`mcp`/`hook`/`cli`).
51///
52/// Why: same labels as [`ActivitySource`] for HTTP / MCP / hook; CLI is
53/// a fourth value we accept here because drawers written from the
54/// `trusty-memory send-message` CLI never travel through the activity
55/// log emit path but still need attribution.
56/// What: lowercase string after the prefix.
57/// Test: `creator_info_renders_all_fields`.
58pub const CREATOR_SOURCE_PREFIX: &str = "creator:source=";
59
60/// Tag prefix carrying the writing process' cwd at write time
61/// (e.g. `creator:cwd=/Users/alice/projects/foo`).
62///
63/// Why: cwd is the single most useful clue when chasing noise — if a
64/// drawer carries `creator:cwd=/Users/alice/projects/claude-mpm`, the
65/// operator knows the write came from that working directory and can
66/// look at *what* was running there. Absent when the writer could not
67/// resolve a cwd (e.g. a remote HTTP client that did not send the
68/// optional header).
69/// Test: `creator_info_omits_cwd_when_absent`.
70pub const CREATOR_CWD_PREFIX: &str = "creator:cwd=";
71
72/// Tag prefix carrying the short session id of the writer (issue #202).
73///
74/// Why: when a session UUID is already attached as a bare tag, the TUI
75/// activity panel cannot easily pick it out of the tag list. Emitting a
76/// dedicated `creator:session=<first-8>` tag puts the session shorthand
77/// in the same reserved namespace as the rest of the attribution data so
78/// the dashboard / TUI can render it without bespoke parsing.
79/// What: prefix string; the suffix is the first 8 hex characters of the
80/// originating UUID.
81/// Test: `session_tag_from_tags_returns_first_uuid_short`.
82pub const CREATOR_SESSION_PREFIX: &str = "creator:session=";
83
84/// Tag prefix carrying the originating tm workstream's name (DOC-53).
85///
86/// Why: mirrors the rest of the `creator:*` namespace, but for the *workstream*
87/// (tm PM session) that wrote the drawer rather than the writing *client*
88/// binary. Lets operators (and the claim-drawer convention, DOC-53 §3) answer
89/// "which workstream wrote this?" the same grep-able way `creator:client=`
90/// answers "which binary wrote this?".
91/// What: rendered only when [`resolve_workstream_name`] returns `Some` — never
92/// a placeholder value.
93/// Test: `creator_info_renders_workstream_tags_when_resolvable`.
94pub const CREATOR_WORKSTREAM_PREFIX: &str = "creator:workstream=";
95
96/// Bare, non-namespaced tag carrying the same workstream name as
97/// [`CREATOR_WORKSTREAM_PREFIX`] (DOC-53 §4.2).
98///
99/// Why: `creator:*` tags are hidden from the primary tag chips
100/// ([`is_creator_tag`]) and from `memory_list`'s exact-tag filter unless the
101/// caller already knows the reserved-prefix form. A first-class `ws:<name>`
102/// tag lets `memory_list(tag: "ws:<name>")` find every drawer a workstream
103/// touched — both auto-stamped writes (this module) and hand-written claim
104/// drawers (DOC-53 §3.1), which use the identical `ws:<name>` tag by
105/// convention.
106/// What: always rendered together with `creator:workstream=`, never alone.
107/// Test: `creator_info_renders_workstream_tags_when_resolvable`.
108pub const WORKSTREAM_TAG_PREFIX: &str = "ws:";
109
110/// Environment variable carrying an explicit, human-readable workstream name
111/// (DOC-53 §4.3).
112///
113/// Why: `tm` does not currently export this — the only session-identity
114/// environment variable a managed session inherits today is
115/// `TM_MANAGED_SESSION_ID` (a UUID). This constant exists so resolution is
116/// forward-compatible: the day `tm` starts exporting a human-readable
117/// workstream name under this key, [`resolve_workstream_name`] picks it up
118/// with no code change here. Until then, resolution falls back to the
119/// cwd-derived heuristic (see that function).
120/// Test: `resolve_workstream_name_prefers_env_var`.
121pub const WORKSTREAM_NAME_ENV: &str = "TM_WORKSTREAM_NAME";
122
123/// HTTP request header carrying the writing client's short name.
124///
125/// Why: lets remote HTTP callers self-identify so the recipient daemon
126/// can populate `creator:client=` without guessing. The dashboard /
127/// claude-mpm / future trusty-* clients all set this when they make
128/// writes; clients that don't get the conservative fallback below.
129/// Test: `drawer_creator_attribution_http_default`,
130/// `drawer_creator_attribution_http_header`.
131pub const X_TRUSTY_CLIENT_NAME: &str = "x-trusty-client-name";
132
133/// HTTP request header carrying the writing client's cwd.
134///
135/// Why: trusts the caller's self-reported cwd because the daemon has
136/// no other way to know it (the HTTP request originates from a remote
137/// process whose cwd is opaque). Absent header → `creator:cwd=` is
138/// omitted from the drawer tags rather than synthesised from the
139/// daemon's own cwd, which would be wrong.
140/// Test: `drawer_creator_attribution_http_default`.
141pub const X_TRUSTY_CLIENT_CWD: &str = "x-trusty-client-cwd";
142
143/// HTTP request header carrying the writing client's explicit workstream
144/// name (DOC-53 §4.3), the HTTP-transport counterpart of the MCP
145/// `args["workstream"]` field the stdio bridge injects
146/// (`commands::serve_stdio_bridge::inject_caller_context`).
147///
148/// Why: symmetric with [`X_TRUSTY_CLIENT_CWD`] — an HTTP caller that already
149/// knows its own workstream name (rather than relying on the
150/// `.worktrees/<name>` cwd-path heuristic [`resolve_workstream_name`]
151/// applies) can self-report it directly. Absent header → `creator:workstream=`
152/// falls back to the cwd heuristic, same precedence
153/// [`CreatorInfo::new_for_caller`] applies to the MCP path.
154/// Test: `drawer_creator_attribution_http_workstream_header`.
155pub const X_TRUSTY_CLIENT_WORKSTREAM: &str = "x-trusty-client-workstream";
156
157/// Default client name used when an HTTP caller omits the
158/// `X-Trusty-Client-Name` header.
159///
160/// Why: every drawer must carry a `creator:client=` tag so the
161/// dashboard renders a consistent "client" column; a missing header
162/// must not yield a missing tag. The fallback is verbose on purpose so
163/// operators can tell "the caller forgot to identify itself" apart from
164/// "the caller is a known trusty-* binary".
165/// Test: `drawer_creator_attribution_http_default`.
166pub const HTTP_DEFAULT_CLIENT: &str = "unknown-http-client";
167
168/// Client name attached to drawers written by the MCP tool surface.
169pub const MCP_CLIENT_NAME: &str = "trusty-memory-mcp";
170
171/// Client name attached to drawers written by the `trusty-memory` CLI.
172pub const CLI_CLIENT_NAME: &str = "trusty-memory-cli";
173
174/// Client name attached to drawers written by hook-driven code paths.
175///
176/// Why: hooks currently only read; the constant is reserved here so a
177/// future hook that *does* write a drawer (e.g. an inbox auto-archive)
178/// would tag itself consistently with the rest of the namespace.
179/// Test: `creator_info_renders_all_fields`.
180pub const HOOK_CLIENT_NAME: &str = "trusty-memory-hook";
181
182/// Originating-subsystem labels emitted into `creator:source=`.
183///
184/// Why: matches [`ActivitySource`] for HTTP/MCP/hook plus a fourth `cli`
185/// label that has no analogue on the activity-feed source enum (CLI
186/// writes go through the HTTP API, but the *origin* of the request was a
187/// CLI process; the user wants to see that distinction).
188/// What: stable lower-case strings.
189/// Test: `creator_info_renders_all_fields`.
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub enum CreatorSource {
192    Http,
193    Mcp,
194    Hook,
195    Cli,
196}
197
198impl CreatorSource {
199    /// Stable lower-case string used in the `creator:source=` tag.
200    pub fn as_str(&self) -> &'static str {
201        match self {
202            Self::Http => "http",
203            Self::Mcp => "mcp",
204            Self::Hook => "hook",
205            Self::Cli => "cli",
206        }
207    }
208}
209
210impl From<ActivitySource> for CreatorSource {
211    fn from(s: ActivitySource) -> Self {
212        match s {
213            ActivitySource::Http => Self::Http,
214            ActivitySource::Mcp => Self::Mcp,
215            ActivitySource::Hook => Self::Hook,
216        }
217    }
218}
219
220/// Value type describing the writer of a drawer.
221///
222/// Why: each write path builds one of these and merges the rendered tags
223/// into the caller-supplied tag list before persisting. Keeping the
224/// rendering centralised guarantees every write produces tags in the
225/// same order with the same prefixes, so curl + grep workflows stay
226/// stable.
227/// What: holds an owned client name, an owned version string, the source
228/// enum, and an optional cwd. `into_tags()` consumes the value and
229/// returns the rendered tag list.
230/// Test: `creator_info_renders_all_fields`,
231/// `creator_info_omits_cwd_when_absent`.
232#[derive(Debug, Clone, PartialEq, Eq)]
233pub struct CreatorInfo {
234    pub client: String,
235    pub version: String,
236    pub source: CreatorSource,
237    pub cwd: Option<String>,
238    pub workstream: Option<String>,
239}
240
241impl CreatorInfo {
242    /// Build a `CreatorInfo` with the supplied client + source, defaulting
243    /// the version to this crate's `CARGO_PKG_VERSION` and the cwd/workstream
244    /// to whatever *this process* has at construction time.
245    ///
246    /// # ⚠️ Daemon-vs-caller hazard — read before calling this from a shared
247    /// # server dispatch path
248    ///
249    /// `new_self` resolves identity from the CALLING PROCESS' own
250    /// environment (`std::env::current_dir()`, `TM_WORKSTREAM_NAME`). That is
251    /// correct only when the process constructing the `CreatorInfo` genuinely
252    /// **is** the writer — a standalone CLI invocation, or a hook that runs
253    /// once per invocation in the caller's own process tree. It is **WRONG**
254    /// for any handler that runs inside `trusty-memory`'s shared HTTP/MCP
255    /// daemon (every `crate::tools::*` handler, reached via `POST /rpc` from
256    /// the stdio bridge or any other remote caller): the daemon is ONE
257    /// long-lived process serving MANY concurrently-attached sessions, so
258    /// `new_self` there would resolve the **daemon's own** cwd/env — the same
259    /// value for every caller — producing cross-session mis-attribution (the
260    /// exact bug DOC-53's caller-supplied design (`new_for_caller`) exists to
261    /// prevent). Use [`CreatorInfo::new_for_caller`] for any write reached
262    /// through the shared daemon's dispatch surface; reserve `new_self` for
263    /// code that truly executes in the writer's own process.
264    /// What: `client.into()` + `env!("CARGO_PKG_VERSION").into()` +
265    /// `std::env::current_dir().ok().map(...)` + [`resolve_own_workstream_name`].
266    /// Test: `creator_info_self_populates_version_and_cwd`.
267    pub fn new_self(client: impl Into<String>, source: CreatorSource) -> Self {
268        let cwd = std::env::current_dir()
269            .ok()
270            .map(|p| p.to_string_lossy().into_owned());
271        let workstream = resolve_own_workstream_name(cwd.as_deref());
272        Self {
273            client: client.into(),
274            version: env!("CARGO_PKG_VERSION").to_string(),
275            source,
276            cwd,
277            workstream,
278        }
279    }
280
281    /// Build a `CreatorInfo` for a write reached through the shared daemon's
282    /// dispatch surface (MCP `tools/call`/direct-method, or HTTP), using ONLY
283    /// caller-supplied context — never the daemon process' own env/cwd.
284    ///
285    /// Why (critical fix, DOC-53 §4.3): the daemon serves every
286    /// concurrently-attached session from ONE process. `new_self`'s
287    /// `std::env::current_dir()`/`TM_WORKSTREAM_NAME` reads would resolve the
288    /// *daemon's* identity, identically for every caller — this is the
289    /// constructor that instead trusts only what the specific request
290    /// carried, mirroring the existing `args["cwd"]` precedent in
291    /// `tools::palace_ops::handle_palace_create` (caller value wins; no
292    /// silent daemon-identity fallback for either field).
293    /// What: `cwd` is `caller_cwd` verbatim (empty-string treated as absent,
294    /// never re-derived from the daemon's own cwd). `workstream` prefers
295    /// `caller_workstream` when it passes [`is_valid_workstream_name`] — an
296    /// explicit-but-invalid value resolves to `None`, NOT a silent fallback
297    /// to the cwd heuristic (same "explicit-but-bad is `None`" rule
298    /// [`resolve_own_workstream_name`] already applies to the env var) —
299    /// else falls back to [`resolve_workstream_name`] against `caller_cwd`.
300    /// Neither field ever touches this process' own env or cwd.
301    /// Test: `new_for_caller_prefers_explicit_workstream_over_cwd`,
302    /// `new_for_caller_falls_back_to_cwd_when_workstream_absent`,
303    /// `new_for_caller_omits_workstream_when_neither_resolvable`,
304    /// `new_for_caller_invalid_explicit_workstream_returns_none_not_cwd_fallback`.
305    pub fn new_for_caller(
306        client: impl Into<String>,
307        source: CreatorSource,
308        caller_cwd: Option<&str>,
309        caller_workstream: Option<&str>,
310    ) -> Self {
311        let cwd = caller_cwd.map(str::to_string).filter(|c| !c.is_empty());
312        let workstream = match caller_workstream.filter(|w| !w.is_empty()) {
313            Some(w) => is_valid_workstream_name(w).then(|| w.to_string()),
314            None => resolve_workstream_name(cwd.as_deref()),
315        };
316        Self {
317            client: client.into(),
318            version: env!("CARGO_PKG_VERSION").to_string(),
319            source,
320            cwd,
321            workstream,
322        }
323    }
324
325    /// Render the rendered tag strings in stable order.
326    ///
327    /// Why: stable order keeps tests deterministic and gives operators a
328    /// predictable layout when they grep through palaces with `jq`.
329    /// What: `[client, version, source, cwd?, creator:workstream?, ws?]`.
330    /// `cwd` and the workstream pair are each omitted when absent rather
331    /// than rendered with an empty/placeholder value, so downstream
332    /// consumers can distinguish "writer didn't share this" from "writer's
333    /// value was literally empty" (DOC-53 §4.1 — no placeholder ever).
334    /// Test: `creator_info_renders_all_fields`,
335    /// `creator_info_omits_cwd_when_absent`,
336    /// `creator_info_renders_workstream_tags_when_resolvable`,
337    /// `creator_info_omits_workstream_tags_when_absent_or_invalid`.
338    pub fn into_tags(self) -> Vec<String> {
339        let mut out = Vec::with_capacity(6);
340        out.push(format!("{CREATOR_CLIENT_PREFIX}{}", self.client));
341        out.push(format!("{CREATOR_VERSION_PREFIX}{}", self.version));
342        out.push(format!("{CREATOR_SOURCE_PREFIX}{}", self.source.as_str()));
343        if let Some(cwd) = self.cwd.filter(|c| !c.is_empty()) {
344            out.push(format!("{CREATOR_CWD_PREFIX}{cwd}"));
345        }
346        if let Some(ws) = self.workstream.filter(|w| is_valid_workstream_name(w)) {
347            out.push(format!("{CREATOR_WORKSTREAM_PREFIX}{ws}"));
348            out.push(format!("{WORKSTREAM_TAG_PREFIX}{ws}"));
349        }
350        out
351    }
352
353    /// Render the tags and append them to an existing tag list.
354    ///
355    /// Why: write-path call sites already hold a `Vec<String>` of
356    /// user-supplied tags; merging in place avoids an allocation and
357    /// preserves the caller's ordering.
358    /// What: pushes each rendered tag onto `dst`. Does not deduplicate —
359    /// caller is expected to pass a freshly-built or de-duplicated list.
360    /// Test: `merge_into_appends_creator_tags`.
361    pub fn merge_into(self, dst: &mut Vec<String>) {
362        for tag in self.into_tags() {
363            dst.push(tag);
364        }
365    }
366
367    /// Render the tags and append them to an existing tag list, skipping any
368    /// tag already present verbatim in `dst`.
369    ///
370    /// Why (MEDIUM 1, DOC-53 §3.1): a hand-written claim drawer already
371    /// carries `ws:<name>` in its caller-supplied tags by convention (the
372    /// claim-drawer shape); [`merge_into`] would then append a *second*,
373    /// identical `ws:<name>` (and, since the caller-supplied workstream and
374    /// the auto-stamped one are the same value, an identical
375    /// `creator:workstream=<name>` too if the caller happened to write that
376    /// literal tag). Use this instead of `merge_into` for any write path
377    /// where the caller's own tags may already overlap the auto-stamped
378    /// namespace — currently [`crate::tools::helpers::attach_mcp_attribution`].
379    /// What: exact-string dedup only (not case-insensitive, not prefix-aware)
380    /// — a tag is skipped iff it already appears verbatim in `dst`.
381    /// Test: `merge_into_deduped_skips_tags_already_present`,
382    /// `merge_into_deduped_appends_when_no_overlap`.
383    pub fn merge_into_deduped(self, dst: &mut Vec<String>) {
384        for tag in self.into_tags() {
385            if !dst.contains(&tag) {
386                dst.push(tag);
387            }
388        }
389    }
390}
391
392/// Return `true` when a tag belongs to the `creator:*` reserved namespace.
393///
394/// Why: render paths (TUI, dashboard) want to hide attribution tags from
395/// the main tag chips so they don't clutter the UI alongside meaningful
396/// user-supplied tags (same pattern as `msg:*` hiding from #99). A single
397/// predicate keeps every renderer in lock-step.
398/// What: returns `tag.starts_with("creator:")`.
399/// Test: `is_creator_tag_detects_namespace`.
400pub fn is_creator_tag(tag: &str) -> bool {
401    tag.starts_with("creator:")
402}
403
404/// Resolve a workstream name from a cwd, if any (DOC-53 §4.3).
405///
406/// Why: the sole heuristic available for a cwd whose owner is not
407/// necessarily this process — a `.worktrees/<name>` path segment is already
408/// implicit in the cwd used for `creator:cwd=` (self-reported by an MCP/CLI
409/// call, or client-reported over HTTP via `X-Trusty-Client-Cwd`), so no new
410/// input is required to try it. Deliberately does **not** consult
411/// [`WORKSTREAM_NAME_ENV`] — that variable describes *this process'*
412/// environment, which is meaningless for a remote HTTP caller's cwd; only
413/// [`resolve_own_workstream_name`] (this process' own identity) reads it.
414/// What: the path segment immediately following a `.worktrees` component in
415/// `cwd`, gated by [`is_valid_workstream_name`] — an invalid candidate
416/// (empty, UUID-shaped, unsafe characters, too long) resolves to `None`,
417/// never a sanitized substitute.
418/// Test: `resolve_workstream_name_falls_back_to_worktrees_cwd_segment`,
419/// `resolve_workstream_name_rejects_uuid_shaped_cwd_segment`,
420/// `resolve_workstream_name_none_when_unresolvable`.
421pub fn resolve_workstream_name(cwd: Option<&str>) -> Option<String> {
422    let cwd = cwd?;
423    // #5204: match the CONFIGURED worktree base as well as the built-in
424    // `.worktrees`. Hardcoding the literal here silently dropped the
425    // `creator:workstream=` tag off every memory written after a retarget —
426    // and looked retroactive, since drawers written before it kept their tags.
427    let names = trusty_common::workspace_layout::WorktreeDirNames::resolve();
428    let mut components = cwd.split('/');
429    while let Some(part) = components.next() {
430        if names.matches(part) {
431            let candidate = components.next()?;
432            return is_valid_workstream_name(candidate).then(|| candidate.to_string());
433        }
434    }
435    None
436}
437
438/// Resolve *this process'* workstream name (DOC-53 §4.3).
439///
440/// Why: `tm` does not currently export a human-readable workstream-name
441/// environment variable to a managed session (only `TM_MANAGED_SESSION_ID`,
442/// a UUID) — see DOC-53 §4.3 for the investigation. Rather than block the
443/// feature on a session-launch change (a surface with several in-flight PRs
444/// at spec-authoring time), resolution uses only context this process
445/// already has: [`WORKSTREAM_NAME_ENV`] first (forward-compatible — the key
446/// `tm` would use if it starts exporting one), else the
447/// [`resolve_workstream_name`] cwd fallback. An env var that is *set but
448/// invalid* is treated as an explicit-but-bad signal and resolves to `None`
449/// rather than silently falling through to the cwd the caller never asked
450/// for.
451/// What: called from [`CreatorInfo::new_self`] (code that truly runs in its
452/// own writer process — see that method's doc for the daemon-vs-caller
453/// hazard) and from the MCP stdio bridge
454/// (`commands::serve_stdio_bridge::run_stdio_bridge`), which — unlike the
455/// shared daemon it proxies to — genuinely IS a fresh, per-session process,
456/// so resolving "this process' own identity" there is correct and is the
457/// mechanism that turns into the caller-supplied `args["workstream"]` the
458/// daemon-side [`CreatorInfo::new_for_caller`] then trusts. The HTTP write
459/// path (`web::rpc::creator_info_from_http`) and the daemon-side MCP
460/// dispatch handlers instead call [`resolve_workstream_name`] /
461/// [`CreatorInfo::new_for_caller`] directly against caller-supplied context,
462/// since the shared daemon's own environment says nothing about a specific
463/// caller's identity.
464/// Test: `resolve_workstream_name_prefers_env_var`,
465/// `resolve_workstream_name_invalid_env_var_returns_none`.
466pub(crate) fn resolve_own_workstream_name(cwd: Option<&str>) -> Option<String> {
467    if let Ok(name) = std::env::var(WORKSTREAM_NAME_ENV) {
468        return is_valid_workstream_name(&name).then_some(name);
469    }
470    resolve_workstream_name(cwd)
471}
472
473/// Validate a workstream-name candidate before it is ever rendered into a
474/// tag (DOC-53 §4.3).
475///
476/// Why: two independent hazards must both be rejected — an empty/overlong/
477/// unsafe-character candidate would corrupt the tag grammar, and a
478/// UUID-shaped candidate (the naming convention for ephemeral/anonymous
479/// scratch worktrees, as opposed to named workstream worktrees) would stamp
480/// noise indistinguishable from a real workstream name. Rejecting both means
481/// the caller omits the tag cleanly rather than sanitizing-and-including.
482/// What: non-empty, at most 64 bytes, matches
483/// `^[A-Za-z0-9][A-Za-z0-9_.-]*$`, and does not parse as a [`uuid::Uuid`].
484/// Test: `is_valid_workstream_name_accepts_slugs`,
485/// `is_valid_workstream_name_rejects_uuid_and_unsafe_names`.
486pub fn is_valid_workstream_name(name: &str) -> bool {
487    if name.is_empty() || name.len() > 64 {
488        return false;
489    }
490    if uuid::Uuid::parse_str(name).is_ok() {
491        return false;
492    }
493    let mut chars = name.chars();
494    let Some(first) = chars.next() else {
495        return false;
496    };
497    if !first.is_ascii_alphanumeric() {
498        return false;
499    }
500    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '-')
501}
502
503/// Build a `creator:session=<first-8-chars>` tag from the first bare UUID
504/// found in `tags`, if any (issue #202).
505///
506/// Why: MCP writers (claude-mpm hooks, in particular) already pass the
507/// session UUID as a free-form tag in the `tags` array. Turning that into
508/// an explicit `creator:session=...` tag puts the session id alongside
509/// the rest of the attribution data so the dashboard / TUI can surface
510/// it without inspecting every tag for UUID-shaped strings.
511/// What: scans the slice in order, parses each entry with
512/// `uuid::Uuid::parse_str`, and on the first success returns
513/// `Some("creator:session=<first-8-hex>")`. Returns `None` when no entry
514/// parses as a UUID, or when the matching tag is itself already a
515/// `creator:*` tag (so dashboard-supplied creator tags don't get
516/// re-projected).
517/// Test: `session_tag_from_tags_returns_first_uuid_short`,
518/// `session_tag_from_tags_skips_non_uuid_entries`.
519pub fn session_tag_from_tags(tags: &[String]) -> Option<String> {
520    for tag in tags {
521        // Skip the reserved-namespace tags so a stray
522        // `creator:cwd=<uuid-shaped-path>` can never be misinterpreted
523        // as a session id. We only consider free-form bare tags.
524        if is_creator_tag(tag) {
525            continue;
526        }
527        if let Ok(uuid) = uuid::Uuid::parse_str(tag) {
528            // `uuid.simple()` renders as 32 lowercase hex chars; the
529            // first 8 are the same characters that appear before the
530            // first dash in the hyphenated form. Both forms parse to the
531            // same `Uuid`, so we render canonically here for stability.
532            let simple = uuid.simple().to_string();
533            let short: String = simple.chars().take(8).collect();
534            return Some(format!("{CREATOR_SESSION_PREFIX}{short}"));
535        }
536    }
537    None
538}
539
540#[cfg(test)]
541mod tests {
542    use super::*;
543
544    /// Why: every render path must emit the four tags in stable order
545    /// (`client`, `version`, `source`, `cwd`) so dashboards can rely on
546    /// the layout. A regression that swapped two would silently change
547    /// every downstream consumer's parsing.
548    /// What: constructs a `CreatorInfo` with all fields populated and
549    /// asserts the rendered list.
550    /// Test: itself.
551    #[test]
552    fn creator_info_renders_all_fields() {
553        let info = CreatorInfo {
554            client: "qa-curl".into(),
555            version: "0.1.2".into(),
556            source: CreatorSource::Http,
557            cwd: Some("/tmp/proj".into()),
558            workstream: None,
559        };
560        let tags = info.into_tags();
561        assert_eq!(
562            tags,
563            vec![
564                "creator:client=qa-curl".to_string(),
565                "creator:version=0.1.2".to_string(),
566                "creator:source=http".to_string(),
567                "creator:cwd=/tmp/proj".to_string(),
568            ]
569        );
570    }
571
572    /// Why: absent cwd must produce three tags, not four with an empty
573    /// `cwd=` — that would force every parser to special-case the empty
574    /// suffix. Same for an empty-string cwd.
575    /// What: omits cwd and renders; then sets it to "" and renders.
576    /// Test: itself.
577    #[test]
578    fn creator_info_omits_cwd_when_absent() {
579        let info = CreatorInfo {
580            client: "mcp".into(),
581            version: "0.1.0".into(),
582            source: CreatorSource::Mcp,
583            cwd: None,
584            workstream: None,
585        };
586        assert_eq!(info.into_tags().len(), 3);
587
588        let info_empty = CreatorInfo {
589            client: "mcp".into(),
590            version: "0.1.0".into(),
591            source: CreatorSource::Mcp,
592            cwd: Some(String::new()),
593            workstream: None,
594        };
595        assert_eq!(info_empty.into_tags().len(), 3);
596    }
597
598    /// Why: `new_self` is the one-line convenience entry point most call
599    /// sites use; it must populate the version from the crate version and
600    /// the cwd from the running process so tests don't have to wire it up
601    /// by hand.
602    /// What: constructs and asserts version + cwd are non-empty. Serialises
603    /// on [`crate::commands::env_test_lock`] and clears
604    /// [`WORKSTREAM_NAME_ENV`] first since `new_self` now also resolves a
605    /// workstream name from the environment.
606    /// Test: itself.
607    #[tokio::test]
608    async fn creator_info_self_populates_version_and_cwd() {
609        let _guard = crate::commands::env_test_lock().lock().await;
610        // SAFETY: serialised by env_test_lock; only this var is touched.
611        unsafe {
612            std::env::remove_var(WORKSTREAM_NAME_ENV);
613        }
614        let info = CreatorInfo::new_self("client", CreatorSource::Cli);
615        assert!(!info.version.is_empty(), "version must be populated");
616        assert!(info.cwd.is_some(), "cwd should resolve in tests");
617    }
618
619    /// Why: the merge helper exists so call sites with an existing tag
620    /// vec don't have to allocate; the contract is "appends in stable
621    /// order".
622    /// What: starts with one caller-supplied tag, merges, asserts the
623    /// trailing tags are the creator tags in order.
624    /// Test: itself.
625    #[test]
626    fn merge_into_appends_creator_tags() {
627        let mut tags = vec!["user-supplied".to_string()];
628        CreatorInfo {
629            client: "x".into(),
630            version: "1".into(),
631            source: CreatorSource::Cli,
632            cwd: None,
633            workstream: None,
634        }
635        .merge_into(&mut tags);
636        assert_eq!(
637            tags,
638            vec![
639                "user-supplied".to_string(),
640                "creator:client=x".to_string(),
641                "creator:version=1".to_string(),
642                "creator:source=cli".to_string(),
643            ]
644        );
645    }
646
647    /// Why: dashboards / TUI renderers must hide `creator:*` tags from
648    /// the main tag chips so the user-supplied tags remain prominent.
649    /// What: tests true / false cases against the predicate.
650    /// Test: itself.
651    #[test]
652    fn is_creator_tag_detects_namespace() {
653        assert!(is_creator_tag("creator:client=foo"));
654        assert!(is_creator_tag("creator:cwd=/tmp"));
655        assert!(is_creator_tag(CREATOR_VERSION_PREFIX));
656        assert!(!is_creator_tag("user-tag"));
657        assert!(!is_creator_tag("msg:v1"));
658        assert!(!is_creator_tag("creatorx"));
659    }
660
661    /// Why: issue #202 — MCP writers (claude-mpm hooks) commonly pass
662    /// the session UUID as a bare tag in the `tags` array. The helper
663    /// must pick out the first parseable UUID and emit the short form
664    /// in the reserved `creator:session=` namespace so the TUI activity
665    /// panel renders it without bespoke parsing.
666    /// What: feeds a mixed tag list and asserts the first 8 hex chars
667    /// of the UUID round-trip into the returned tag.
668    /// Test: itself.
669    #[test]
670    fn session_tag_from_tags_returns_first_uuid_short() {
671        let tags = vec![
672            "user-tag".to_string(),
673            "01919e90-8a2e-7c1d-9f8b-1234567890ab".to_string(),
674            "ignored-second-uuid:11111111-2222-3333-4444-555555555555".to_string(),
675        ];
676        let session = session_tag_from_tags(&tags).expect("session tag");
677        assert_eq!(session, "creator:session=01919e90");
678    }
679
680    /// Why: non-UUID entries (free-form tags, scoped tags like `idx:0`)
681    /// must not be misinterpreted as session ids — the helper has to
682    /// return `None` when no entry parses as a UUID.
683    /// What: feeds a tag list with no UUIDs and asserts `None`.
684    /// Test: itself.
685    #[test]
686    fn session_tag_from_tags_skips_non_uuid_entries() {
687        let tags = vec![
688            "user-tag".to_string(),
689            "idx:0".to_string(),
690            "session-prefix-not-a-uuid".to_string(),
691        ];
692        assert!(session_tag_from_tags(&tags).is_none());
693
694        // Empty list returns `None`.
695        assert!(session_tag_from_tags(&[]).is_none());
696    }
697
698    /// Why: a tag in the reserved `creator:*` namespace must never be
699    /// re-projected as a session id, even if its value parses as a UUID.
700    /// `creator:cwd=` carrying a UUID-shaped temporary path is the
701    /// motivating example.
702    /// What: feeds a `creator:` tag whose value parses as a UUID and a
703    /// real bare UUID later in the list, then asserts the real one wins.
704    /// Test: itself.
705    #[test]
706    fn session_tag_from_tags_skips_reserved_namespace() {
707        let tags = vec![
708            // Reserved namespace tag with a UUID-shaped value — must be skipped.
709            "creator:cwd=11111111-1111-1111-1111-111111111111".to_string(),
710            // The real session tag — must win.
711            "22222222-2222-2222-2222-222222222222".to_string(),
712        ];
713        let session = session_tag_from_tags(&tags).expect("session tag");
714        assert_eq!(session, "creator:session=22222222");
715    }
716
717    /// Why: the `From<ActivitySource>` impl lets the HTTP path build a
718    /// `CreatorSource` from the existing `ActivitySource::Http` without
719    /// a manual match; the mapping must be identity for the three shared
720    /// variants.
721    /// What: round-trips each variant.
722    /// Test: itself.
723    #[test]
724    fn creator_source_from_activity_source() {
725        assert_eq!(
726            CreatorSource::from(ActivitySource::Http),
727            CreatorSource::Http
728        );
729        assert_eq!(CreatorSource::from(ActivitySource::Mcp), CreatorSource::Mcp);
730        assert_eq!(
731            CreatorSource::from(ActivitySource::Hook),
732            CreatorSource::Hook
733        );
734    }
735
736    /// Why: `into_tags` must render both the reserved `creator:workstream=`
737    /// tag and the ergonomic bare `ws:` tag, in that order, immediately
738    /// after `cwd` — DOC-53 §4.1/§4.2.
739    /// What: constructs a `CreatorInfo` with a resolvable workstream and
740    /// asserts both trailing tags.
741    /// Test: itself.
742    #[test]
743    fn creator_info_renders_workstream_tags_when_resolvable() {
744        let info = CreatorInfo {
745            client: "mcp".into(),
746            version: "0.1.0".into(),
747            source: CreatorSource::Mcp,
748            cwd: Some("/tmp/proj".into()),
749            workstream: Some("feat-ws-memory-claims".into()),
750        };
751        let tags = info.into_tags();
752        assert_eq!(
753            tags,
754            vec![
755                "creator:client=mcp".to_string(),
756                "creator:version=0.1.0".to_string(),
757                "creator:source=mcp".to_string(),
758                "creator:cwd=/tmp/proj".to_string(),
759                "creator:workstream=feat-ws-memory-claims".to_string(),
760                "ws:feat-ws-memory-claims".to_string(),
761            ]
762        );
763    }
764
765    /// Why: DOC-53 §4.1's "no placeholder, ever" rule must hold both when
766    /// `workstream` is `None` (the common case) AND when a caller manually
767    /// sets an invalid value — `into_tags` must re-validate rather than
768    /// trust its input, since [`CreatorInfo`] is a public struct any caller
769    /// can construct directly.
770    /// What: `None` renders no trailing tags; an unsafe/UUID-shaped value
771    /// also renders none, rather than being sanitized and included.
772    /// Test: itself.
773    #[test]
774    fn creator_info_omits_workstream_tags_when_absent_or_invalid() {
775        let absent = CreatorInfo {
776            client: "mcp".into(),
777            version: "0.1.0".into(),
778            source: CreatorSource::Mcp,
779            cwd: None,
780            workstream: None,
781        };
782        assert_eq!(absent.into_tags().len(), 3);
783
784        let invalid = CreatorInfo {
785            client: "mcp".into(),
786            version: "0.1.0".into(),
787            source: CreatorSource::Mcp,
788            cwd: None,
789            workstream: Some("11111111-1111-1111-1111-111111111111".into()),
790        };
791        assert_eq!(invalid.into_tags().len(), 3);
792    }
793
794    /// Why (CRITICAL fix, DOC-53 §4.3): `new_for_caller` is the ONLY
795    /// constructor the shared daemon's dispatch handlers should use — it
796    /// must never touch this process' own env/cwd, only what the caller
797    /// supplied. This is the base case: an explicit, valid workstream wins
798    /// even when a plausible cwd fallback is also present.
799    /// What: supplies both a caller cwd and a distinct caller workstream;
800    /// asserts the explicit workstream is used, not one derived from cwd.
801    /// Test: itself.
802    #[test]
803    fn new_for_caller_prefers_explicit_workstream_over_cwd() {
804        let info = CreatorInfo::new_for_caller(
805            "trusty-memory-mcp",
806            CreatorSource::Mcp,
807            Some("/x/.worktrees/cwd-derived-name"),
808            Some("explicit-ws"),
809        );
810        assert_eq!(info.workstream.as_deref(), Some("explicit-ws"));
811        assert_eq!(info.cwd.as_deref(), Some("/x/.worktrees/cwd-derived-name"));
812    }
813
814    /// Why: when the caller omits `workstream` entirely (but supplies
815    /// `cwd`), the cwd-derived heuristic is the correct fallback — same
816    /// derivation [`resolve_workstream_name`] already provides for the HTTP
817    /// path.
818    /// What: caller workstream `None`, caller cwd a `.worktrees/<name>`
819    /// path; asserts the derived name.
820    /// Test: itself.
821    #[test]
822    fn new_for_caller_falls_back_to_cwd_when_workstream_absent() {
823        let info = CreatorInfo::new_for_caller(
824            "trusty-memory-mcp",
825            CreatorSource::Mcp,
826            Some("/x/.worktrees/cwd-derived-name"),
827            None,
828        );
829        assert_eq!(info.workstream.as_deref(), Some("cwd-derived-name"));
830    }
831
832    /// Why: no caller cwd AND no caller workstream is the honest "we don't
833    /// know" case — DOC-53 §4.1's omit-cleanly rule, at the caller-supplied
834    /// constructor.
835    /// What: both `None`; asserts `workstream` is `None` (never falls back
836    /// to this process' own identity).
837    /// Test: itself.
838    #[test]
839    fn new_for_caller_omits_workstream_when_neither_resolvable() {
840        let info = CreatorInfo::new_for_caller("trusty-memory-mcp", CreatorSource::Mcp, None, None);
841        assert_eq!(info.workstream, None);
842        assert_eq!(info.cwd, None);
843    }
844
845    /// Why: an explicit-but-invalid caller workstream (unsafe chars,
846    /// UUID-shaped, empty) is an explicit-but-bad signal — DOC-53 §4.3
847    /// treats that as `None`, NOT a silent fallback to the cwd heuristic the
848    /// caller didn't ask for (mirrors [`resolve_own_workstream_name`]'s
849    /// identical rule for the env var).
850    /// What: an invalid explicit workstream alongside a valid cwd fallback;
851    /// asserts `None`, not the cwd-derived value.
852    /// Test: itself.
853    #[test]
854    fn new_for_caller_invalid_explicit_workstream_returns_none_not_cwd_fallback() {
855        let info = CreatorInfo::new_for_caller(
856            "trusty-memory-mcp",
857            CreatorSource::Mcp,
858            Some("/x/.worktrees/cwd-derived-name"),
859            Some("not a valid name!"),
860        );
861        assert_eq!(info.workstream, None);
862    }
863
864    /// Why (MEDIUM 1, DOC-53 §3.1): a hand-written claim drawer's own tags
865    /// may already carry `ws:<name>` (and, less commonly, a literal
866    /// `creator:workstream=<name>`) — `merge_into_deduped` must not append a
867    /// second copy of either.
868    /// What: seeds `dst` with `ws:feat-x` already present, merges a
869    /// `CreatorInfo` whose rendered tags include `ws:feat-x`, asserts the
870    /// tag appears exactly once while the OTHER rendered tags (which were
871    /// not already present) still land.
872    /// Test: itself.
873    #[test]
874    fn merge_into_deduped_skips_tags_already_present() {
875        let mut tags = vec!["user-tag".to_string(), "ws:feat-x".to_string()];
876        CreatorInfo {
877            client: "trusty-memory-mcp".into(),
878            version: "0.1.0".into(),
879            source: CreatorSource::Mcp,
880            cwd: None,
881            workstream: Some("feat-x".into()),
882        }
883        .merge_into_deduped(&mut tags);
884        assert_eq!(
885            tags.iter().filter(|t| *t == "ws:feat-x").count(),
886            1,
887            "ws:feat-x must not be duplicated; got {tags:?}"
888        );
889        assert!(
890            tags.contains(&"creator:client=trusty-memory-mcp".to_string()),
891            "non-overlapping tags must still be appended; got {tags:?}"
892        );
893        assert!(
894            tags.contains(&"creator:workstream=feat-x".to_string()),
895            "creator:workstream= must still be appended (only ws: overlapped); got {tags:?}"
896        );
897    }
898
899    /// Why: dedup must not become a no-append bug — when nothing overlaps,
900    /// every rendered tag lands exactly as `merge_into` would produce.
901    /// What: seeds `dst` with an unrelated tag only; asserts all rendered
902    /// tags are present.
903    /// Test: itself.
904    #[test]
905    fn merge_into_deduped_appends_when_no_overlap() {
906        let mut tags = vec!["unrelated".to_string()];
907        CreatorInfo {
908            client: "trusty-memory-mcp".into(),
909            version: "0.1.0".into(),
910            source: CreatorSource::Mcp,
911            cwd: None,
912            workstream: Some("feat-x".into()),
913        }
914        .merge_into_deduped(&mut tags);
915        assert_eq!(
916            tags,
917            vec![
918                "unrelated".to_string(),
919                "creator:client=trusty-memory-mcp".to_string(),
920                "creator:version=0.1.0".to_string(),
921                "creator:source=mcp".to_string(),
922                "creator:workstream=feat-x".to_string(),
923                "ws:feat-x".to_string(),
924            ]
925        );
926    }
927
928    /// Why: [`WORKSTREAM_NAME_ENV`] is the forward-compatible primary
929    /// source (DOC-53 §4.3) and must win over the cwd fallback whenever
930    /// set. Serialises on `env_test_lock` since it mutates process-wide
931    /// state.
932    /// What: sets the env var, passes an unrelated (even a `.worktrees`-
933    /// bearing) cwd, and asserts the env value wins.
934    /// Test: itself.
935    #[tokio::test]
936    async fn resolve_workstream_name_prefers_env_var() {
937        let _guard = crate::commands::env_test_lock().lock().await;
938        // SAFETY: serialised by env_test_lock; only this var is touched,
939        // and it is always cleared before returning.
940        unsafe {
941            std::env::set_var(WORKSTREAM_NAME_ENV, "explicit-ws");
942        }
943        let resolved = resolve_own_workstream_name(Some("/x/.worktrees/other-name"));
944        unsafe {
945            std::env::remove_var(WORKSTREAM_NAME_ENV);
946        }
947        assert_eq!(resolved, Some("explicit-ws".to_string()));
948    }
949
950    /// Why: an env var that is SET but fails validation (DOC-53 §4.3) is an
951    /// explicit-but-bad signal — it must resolve to `None`, not silently
952    /// fall through to the cwd heuristic the writer never asked for.
953    /// What: sets an unsafe env value with a plausible cwd fallback present
954    /// and asserts `None`.
955    /// Test: itself.
956    #[tokio::test]
957    async fn resolve_workstream_name_invalid_env_var_returns_none() {
958        let _guard = crate::commands::env_test_lock().lock().await;
959        // SAFETY: serialised by env_test_lock.
960        unsafe {
961            std::env::set_var(WORKSTREAM_NAME_ENV, "not a valid name!");
962        }
963        let resolved = resolve_own_workstream_name(Some("/x/.worktrees/other-name"));
964        unsafe {
965            std::env::remove_var(WORKSTREAM_NAME_ENV);
966        }
967        assert_eq!(resolved, None);
968    }
969
970    /// Why: the common case — a `tm`-managed PM session running directly in
971    /// its own `.worktrees/<name>` checkout — must resolve without any `tm`
972    /// changes (DOC-53 §4.3). [`resolve_workstream_name`] is pure cwd-based
973    /// (no env var involved, see its doc comment), so no locking is needed.
974    /// What: feeds a realistic worktree cwd, asserts the segment
975    /// immediately after `.worktrees` is returned.
976    /// Test: itself.
977    #[test]
978    fn resolve_workstream_name_falls_back_to_worktrees_cwd_segment() {
979        let resolved = resolve_workstream_name(Some(
980            "/Users/bob/trusty-tools/.base/.worktrees/feat-ws-memory-claims",
981        ));
982        assert_eq!(resolved, Some("feat-ws-memory-claims".to_string()));
983    }
984
985    /// Why: ephemeral/anonymous scratch worktrees are named by UUID, not by
986    /// workstream (DOC-53 §4.3) — stamping one would produce noise
987    /// indistinguishable from a real name, so it must resolve to `None`.
988    /// What: feeds a UUID-named `.worktrees/<uuid>` cwd, asserts `None`.
989    /// Test: itself.
990    #[test]
991    fn resolve_workstream_name_rejects_uuid_shaped_cwd_segment() {
992        let resolved = resolve_workstream_name(Some(
993            "/Users/bob/trusty-tools/.base/.worktrees/2eb72dca-de08-481b-8dfa-22ab7f81b1f9",
994        ));
995        assert_eq!(resolved, None);
996    }
997
998    /// Why: a cwd with no `.worktrees` component (or no cwd at all) is the
999    /// honest "can't resolve this" case — DOC-53 §4.1's omit-cleanly rule,
1000    /// exercised at the resolver level.
1001    /// What: cwd `None`; then a cwd with no `.worktrees` segment. Both
1002    /// resolve to `None`.
1003    /// Test: itself.
1004    #[test]
1005    fn resolve_workstream_name_none_when_unresolvable() {
1006        assert_eq!(resolve_workstream_name(None), None);
1007        assert_eq!(
1008            resolve_workstream_name(Some("/Users/bob/some/other/project")),
1009            None
1010        );
1011    }
1012
1013    /// Why: the validator is the single gate standing between untrusted
1014    /// input (env var or cwd segment) and a rendered tag — it must accept
1015    /// ordinary slugs.
1016    /// What: table of accepted names.
1017    /// Test: itself.
1018    #[test]
1019    fn is_valid_workstream_name_accepts_slugs() {
1020        for name in [
1021            "feat-ws-memory-claims",
1022            "tm_search_eviction_01",
1023            "a",
1024            "release.0.20.0",
1025        ] {
1026            assert!(is_valid_workstream_name(name), "expected valid: {name}");
1027        }
1028    }
1029
1030    /// Why: the validator must reject both structurally-unsafe candidates
1031    /// (empty, overlong, unsafe characters, non-alnum leading char) and
1032    /// UUID-shaped candidates (DOC-53 §4.3's anonymous-worktree exclusion),
1033    /// since a caller (env var or cwd) is untrusted input.
1034    /// What: table of rejected names.
1035    /// Test: itself.
1036    #[test]
1037    fn is_valid_workstream_name_rejects_uuid_and_unsafe_names() {
1038        for name in [
1039            "",
1040            "2eb72dca-de08-481b-8dfa-22ab7f81b1f9",
1041            "-leading-dash",
1042            "has space",
1043            "has/slash",
1044            "has;semicolon",
1045            &"x".repeat(65),
1046        ] {
1047            assert!(!is_valid_workstream_name(name), "expected invalid: {name}");
1048        }
1049    }
1050}