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    let mut components = cwd.split('/');
424    while let Some(part) = components.next() {
425        if part == ".worktrees" {
426            let candidate = components.next()?;
427            return is_valid_workstream_name(candidate).then(|| candidate.to_string());
428        }
429    }
430    None
431}
432
433/// Resolve *this process'* workstream name (DOC-53 §4.3).
434///
435/// Why: `tm` does not currently export a human-readable workstream-name
436/// environment variable to a managed session (only `TM_MANAGED_SESSION_ID`,
437/// a UUID) — see DOC-53 §4.3 for the investigation. Rather than block the
438/// feature on a session-launch change (a surface with several in-flight PRs
439/// at spec-authoring time), resolution uses only context this process
440/// already has: [`WORKSTREAM_NAME_ENV`] first (forward-compatible — the key
441/// `tm` would use if it starts exporting one), else the
442/// [`resolve_workstream_name`] cwd fallback. An env var that is *set but
443/// invalid* is treated as an explicit-but-bad signal and resolves to `None`
444/// rather than silently falling through to the cwd the caller never asked
445/// for.
446/// What: called from [`CreatorInfo::new_self`] (code that truly runs in its
447/// own writer process — see that method's doc for the daemon-vs-caller
448/// hazard) and from the MCP stdio bridge
449/// (`commands::serve_stdio_bridge::run_stdio_bridge`), which — unlike the
450/// shared daemon it proxies to — genuinely IS a fresh, per-session process,
451/// so resolving "this process' own identity" there is correct and is the
452/// mechanism that turns into the caller-supplied `args["workstream"]` the
453/// daemon-side [`CreatorInfo::new_for_caller`] then trusts. The HTTP write
454/// path (`web::rpc::creator_info_from_http`) and the daemon-side MCP
455/// dispatch handlers instead call [`resolve_workstream_name`] /
456/// [`CreatorInfo::new_for_caller`] directly against caller-supplied context,
457/// since the shared daemon's own environment says nothing about a specific
458/// caller's identity.
459/// Test: `resolve_workstream_name_prefers_env_var`,
460/// `resolve_workstream_name_invalid_env_var_returns_none`.
461pub(crate) fn resolve_own_workstream_name(cwd: Option<&str>) -> Option<String> {
462    if let Ok(name) = std::env::var(WORKSTREAM_NAME_ENV) {
463        return is_valid_workstream_name(&name).then_some(name);
464    }
465    resolve_workstream_name(cwd)
466}
467
468/// Validate a workstream-name candidate before it is ever rendered into a
469/// tag (DOC-53 §4.3).
470///
471/// Why: two independent hazards must both be rejected — an empty/overlong/
472/// unsafe-character candidate would corrupt the tag grammar, and a
473/// UUID-shaped candidate (the naming convention for ephemeral/anonymous
474/// scratch worktrees, as opposed to named workstream worktrees) would stamp
475/// noise indistinguishable from a real workstream name. Rejecting both means
476/// the caller omits the tag cleanly rather than sanitizing-and-including.
477/// What: non-empty, at most 64 bytes, matches
478/// `^[A-Za-z0-9][A-Za-z0-9_.-]*$`, and does not parse as a [`uuid::Uuid`].
479/// Test: `is_valid_workstream_name_accepts_slugs`,
480/// `is_valid_workstream_name_rejects_uuid_and_unsafe_names`.
481pub fn is_valid_workstream_name(name: &str) -> bool {
482    if name.is_empty() || name.len() > 64 {
483        return false;
484    }
485    if uuid::Uuid::parse_str(name).is_ok() {
486        return false;
487    }
488    let mut chars = name.chars();
489    let Some(first) = chars.next() else {
490        return false;
491    };
492    if !first.is_ascii_alphanumeric() {
493        return false;
494    }
495    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '-')
496}
497
498/// Build a `creator:session=<first-8-chars>` tag from the first bare UUID
499/// found in `tags`, if any (issue #202).
500///
501/// Why: MCP writers (claude-mpm hooks, in particular) already pass the
502/// session UUID as a free-form tag in the `tags` array. Turning that into
503/// an explicit `creator:session=...` tag puts the session id alongside
504/// the rest of the attribution data so the dashboard / TUI can surface
505/// it without inspecting every tag for UUID-shaped strings.
506/// What: scans the slice in order, parses each entry with
507/// `uuid::Uuid::parse_str`, and on the first success returns
508/// `Some("creator:session=<first-8-hex>")`. Returns `None` when no entry
509/// parses as a UUID, or when the matching tag is itself already a
510/// `creator:*` tag (so dashboard-supplied creator tags don't get
511/// re-projected).
512/// Test: `session_tag_from_tags_returns_first_uuid_short`,
513/// `session_tag_from_tags_skips_non_uuid_entries`.
514pub fn session_tag_from_tags(tags: &[String]) -> Option<String> {
515    for tag in tags {
516        // Skip the reserved-namespace tags so a stray
517        // `creator:cwd=<uuid-shaped-path>` can never be misinterpreted
518        // as a session id. We only consider free-form bare tags.
519        if is_creator_tag(tag) {
520            continue;
521        }
522        if let Ok(uuid) = uuid::Uuid::parse_str(tag) {
523            // `uuid.simple()` renders as 32 lowercase hex chars; the
524            // first 8 are the same characters that appear before the
525            // first dash in the hyphenated form. Both forms parse to the
526            // same `Uuid`, so we render canonically here for stability.
527            let simple = uuid.simple().to_string();
528            let short: String = simple.chars().take(8).collect();
529            return Some(format!("{CREATOR_SESSION_PREFIX}{short}"));
530        }
531    }
532    None
533}
534
535#[cfg(test)]
536mod tests {
537    use super::*;
538
539    /// Why: every render path must emit the four tags in stable order
540    /// (`client`, `version`, `source`, `cwd`) so dashboards can rely on
541    /// the layout. A regression that swapped two would silently change
542    /// every downstream consumer's parsing.
543    /// What: constructs a `CreatorInfo` with all fields populated and
544    /// asserts the rendered list.
545    /// Test: itself.
546    #[test]
547    fn creator_info_renders_all_fields() {
548        let info = CreatorInfo {
549            client: "qa-curl".into(),
550            version: "0.1.2".into(),
551            source: CreatorSource::Http,
552            cwd: Some("/tmp/proj".into()),
553            workstream: None,
554        };
555        let tags = info.into_tags();
556        assert_eq!(
557            tags,
558            vec![
559                "creator:client=qa-curl".to_string(),
560                "creator:version=0.1.2".to_string(),
561                "creator:source=http".to_string(),
562                "creator:cwd=/tmp/proj".to_string(),
563            ]
564        );
565    }
566
567    /// Why: absent cwd must produce three tags, not four with an empty
568    /// `cwd=` — that would force every parser to special-case the empty
569    /// suffix. Same for an empty-string cwd.
570    /// What: omits cwd and renders; then sets it to "" and renders.
571    /// Test: itself.
572    #[test]
573    fn creator_info_omits_cwd_when_absent() {
574        let info = CreatorInfo {
575            client: "mcp".into(),
576            version: "0.1.0".into(),
577            source: CreatorSource::Mcp,
578            cwd: None,
579            workstream: None,
580        };
581        assert_eq!(info.into_tags().len(), 3);
582
583        let info_empty = CreatorInfo {
584            client: "mcp".into(),
585            version: "0.1.0".into(),
586            source: CreatorSource::Mcp,
587            cwd: Some(String::new()),
588            workstream: None,
589        };
590        assert_eq!(info_empty.into_tags().len(), 3);
591    }
592
593    /// Why: `new_self` is the one-line convenience entry point most call
594    /// sites use; it must populate the version from the crate version and
595    /// the cwd from the running process so tests don't have to wire it up
596    /// by hand.
597    /// What: constructs and asserts version + cwd are non-empty. Serialises
598    /// on [`crate::commands::env_test_lock`] and clears
599    /// [`WORKSTREAM_NAME_ENV`] first since `new_self` now also resolves a
600    /// workstream name from the environment.
601    /// Test: itself.
602    #[tokio::test]
603    async fn creator_info_self_populates_version_and_cwd() {
604        let _guard = crate::commands::env_test_lock().lock().await;
605        // SAFETY: serialised by env_test_lock; only this var is touched.
606        unsafe {
607            std::env::remove_var(WORKSTREAM_NAME_ENV);
608        }
609        let info = CreatorInfo::new_self("client", CreatorSource::Cli);
610        assert!(!info.version.is_empty(), "version must be populated");
611        assert!(info.cwd.is_some(), "cwd should resolve in tests");
612    }
613
614    /// Why: the merge helper exists so call sites with an existing tag
615    /// vec don't have to allocate; the contract is "appends in stable
616    /// order".
617    /// What: starts with one caller-supplied tag, merges, asserts the
618    /// trailing tags are the creator tags in order.
619    /// Test: itself.
620    #[test]
621    fn merge_into_appends_creator_tags() {
622        let mut tags = vec!["user-supplied".to_string()];
623        CreatorInfo {
624            client: "x".into(),
625            version: "1".into(),
626            source: CreatorSource::Cli,
627            cwd: None,
628            workstream: None,
629        }
630        .merge_into(&mut tags);
631        assert_eq!(
632            tags,
633            vec![
634                "user-supplied".to_string(),
635                "creator:client=x".to_string(),
636                "creator:version=1".to_string(),
637                "creator:source=cli".to_string(),
638            ]
639        );
640    }
641
642    /// Why: dashboards / TUI renderers must hide `creator:*` tags from
643    /// the main tag chips so the user-supplied tags remain prominent.
644    /// What: tests true / false cases against the predicate.
645    /// Test: itself.
646    #[test]
647    fn is_creator_tag_detects_namespace() {
648        assert!(is_creator_tag("creator:client=foo"));
649        assert!(is_creator_tag("creator:cwd=/tmp"));
650        assert!(is_creator_tag(CREATOR_VERSION_PREFIX));
651        assert!(!is_creator_tag("user-tag"));
652        assert!(!is_creator_tag("msg:v1"));
653        assert!(!is_creator_tag("creatorx"));
654    }
655
656    /// Why: issue #202 — MCP writers (claude-mpm hooks) commonly pass
657    /// the session UUID as a bare tag in the `tags` array. The helper
658    /// must pick out the first parseable UUID and emit the short form
659    /// in the reserved `creator:session=` namespace so the TUI activity
660    /// panel renders it without bespoke parsing.
661    /// What: feeds a mixed tag list and asserts the first 8 hex chars
662    /// of the UUID round-trip into the returned tag.
663    /// Test: itself.
664    #[test]
665    fn session_tag_from_tags_returns_first_uuid_short() {
666        let tags = vec![
667            "user-tag".to_string(),
668            "01919e90-8a2e-7c1d-9f8b-1234567890ab".to_string(),
669            "ignored-second-uuid:11111111-2222-3333-4444-555555555555".to_string(),
670        ];
671        let session = session_tag_from_tags(&tags).expect("session tag");
672        assert_eq!(session, "creator:session=01919e90");
673    }
674
675    /// Why: non-UUID entries (free-form tags, scoped tags like `idx:0`)
676    /// must not be misinterpreted as session ids — the helper has to
677    /// return `None` when no entry parses as a UUID.
678    /// What: feeds a tag list with no UUIDs and asserts `None`.
679    /// Test: itself.
680    #[test]
681    fn session_tag_from_tags_skips_non_uuid_entries() {
682        let tags = vec![
683            "user-tag".to_string(),
684            "idx:0".to_string(),
685            "session-prefix-not-a-uuid".to_string(),
686        ];
687        assert!(session_tag_from_tags(&tags).is_none());
688
689        // Empty list returns `None`.
690        assert!(session_tag_from_tags(&[]).is_none());
691    }
692
693    /// Why: a tag in the reserved `creator:*` namespace must never be
694    /// re-projected as a session id, even if its value parses as a UUID.
695    /// `creator:cwd=` carrying a UUID-shaped temporary path is the
696    /// motivating example.
697    /// What: feeds a `creator:` tag whose value parses as a UUID and a
698    /// real bare UUID later in the list, then asserts the real one wins.
699    /// Test: itself.
700    #[test]
701    fn session_tag_from_tags_skips_reserved_namespace() {
702        let tags = vec![
703            // Reserved namespace tag with a UUID-shaped value — must be skipped.
704            "creator:cwd=11111111-1111-1111-1111-111111111111".to_string(),
705            // The real session tag — must win.
706            "22222222-2222-2222-2222-222222222222".to_string(),
707        ];
708        let session = session_tag_from_tags(&tags).expect("session tag");
709        assert_eq!(session, "creator:session=22222222");
710    }
711
712    /// Why: the `From<ActivitySource>` impl lets the HTTP path build a
713    /// `CreatorSource` from the existing `ActivitySource::Http` without
714    /// a manual match; the mapping must be identity for the three shared
715    /// variants.
716    /// What: round-trips each variant.
717    /// Test: itself.
718    #[test]
719    fn creator_source_from_activity_source() {
720        assert_eq!(
721            CreatorSource::from(ActivitySource::Http),
722            CreatorSource::Http
723        );
724        assert_eq!(CreatorSource::from(ActivitySource::Mcp), CreatorSource::Mcp);
725        assert_eq!(
726            CreatorSource::from(ActivitySource::Hook),
727            CreatorSource::Hook
728        );
729    }
730
731    /// Why: `into_tags` must render both the reserved `creator:workstream=`
732    /// tag and the ergonomic bare `ws:` tag, in that order, immediately
733    /// after `cwd` — DOC-53 §4.1/§4.2.
734    /// What: constructs a `CreatorInfo` with a resolvable workstream and
735    /// asserts both trailing tags.
736    /// Test: itself.
737    #[test]
738    fn creator_info_renders_workstream_tags_when_resolvable() {
739        let info = CreatorInfo {
740            client: "mcp".into(),
741            version: "0.1.0".into(),
742            source: CreatorSource::Mcp,
743            cwd: Some("/tmp/proj".into()),
744            workstream: Some("feat-ws-memory-claims".into()),
745        };
746        let tags = info.into_tags();
747        assert_eq!(
748            tags,
749            vec![
750                "creator:client=mcp".to_string(),
751                "creator:version=0.1.0".to_string(),
752                "creator:source=mcp".to_string(),
753                "creator:cwd=/tmp/proj".to_string(),
754                "creator:workstream=feat-ws-memory-claims".to_string(),
755                "ws:feat-ws-memory-claims".to_string(),
756            ]
757        );
758    }
759
760    /// Why: DOC-53 §4.1's "no placeholder, ever" rule must hold both when
761    /// `workstream` is `None` (the common case) AND when a caller manually
762    /// sets an invalid value — `into_tags` must re-validate rather than
763    /// trust its input, since [`CreatorInfo`] is a public struct any caller
764    /// can construct directly.
765    /// What: `None` renders no trailing tags; an unsafe/UUID-shaped value
766    /// also renders none, rather than being sanitized and included.
767    /// Test: itself.
768    #[test]
769    fn creator_info_omits_workstream_tags_when_absent_or_invalid() {
770        let absent = CreatorInfo {
771            client: "mcp".into(),
772            version: "0.1.0".into(),
773            source: CreatorSource::Mcp,
774            cwd: None,
775            workstream: None,
776        };
777        assert_eq!(absent.into_tags().len(), 3);
778
779        let invalid = CreatorInfo {
780            client: "mcp".into(),
781            version: "0.1.0".into(),
782            source: CreatorSource::Mcp,
783            cwd: None,
784            workstream: Some("11111111-1111-1111-1111-111111111111".into()),
785        };
786        assert_eq!(invalid.into_tags().len(), 3);
787    }
788
789    /// Why (CRITICAL fix, DOC-53 §4.3): `new_for_caller` is the ONLY
790    /// constructor the shared daemon's dispatch handlers should use — it
791    /// must never touch this process' own env/cwd, only what the caller
792    /// supplied. This is the base case: an explicit, valid workstream wins
793    /// even when a plausible cwd fallback is also present.
794    /// What: supplies both a caller cwd and a distinct caller workstream;
795    /// asserts the explicit workstream is used, not one derived from cwd.
796    /// Test: itself.
797    #[test]
798    fn new_for_caller_prefers_explicit_workstream_over_cwd() {
799        let info = CreatorInfo::new_for_caller(
800            "trusty-memory-mcp",
801            CreatorSource::Mcp,
802            Some("/x/.worktrees/cwd-derived-name"),
803            Some("explicit-ws"),
804        );
805        assert_eq!(info.workstream.as_deref(), Some("explicit-ws"));
806        assert_eq!(info.cwd.as_deref(), Some("/x/.worktrees/cwd-derived-name"));
807    }
808
809    /// Why: when the caller omits `workstream` entirely (but supplies
810    /// `cwd`), the cwd-derived heuristic is the correct fallback — same
811    /// derivation [`resolve_workstream_name`] already provides for the HTTP
812    /// path.
813    /// What: caller workstream `None`, caller cwd a `.worktrees/<name>`
814    /// path; asserts the derived name.
815    /// Test: itself.
816    #[test]
817    fn new_for_caller_falls_back_to_cwd_when_workstream_absent() {
818        let info = CreatorInfo::new_for_caller(
819            "trusty-memory-mcp",
820            CreatorSource::Mcp,
821            Some("/x/.worktrees/cwd-derived-name"),
822            None,
823        );
824        assert_eq!(info.workstream.as_deref(), Some("cwd-derived-name"));
825    }
826
827    /// Why: no caller cwd AND no caller workstream is the honest "we don't
828    /// know" case — DOC-53 §4.1's omit-cleanly rule, at the caller-supplied
829    /// constructor.
830    /// What: both `None`; asserts `workstream` is `None` (never falls back
831    /// to this process' own identity).
832    /// Test: itself.
833    #[test]
834    fn new_for_caller_omits_workstream_when_neither_resolvable() {
835        let info = CreatorInfo::new_for_caller("trusty-memory-mcp", CreatorSource::Mcp, None, None);
836        assert_eq!(info.workstream, None);
837        assert_eq!(info.cwd, None);
838    }
839
840    /// Why: an explicit-but-invalid caller workstream (unsafe chars,
841    /// UUID-shaped, empty) is an explicit-but-bad signal — DOC-53 §4.3
842    /// treats that as `None`, NOT a silent fallback to the cwd heuristic the
843    /// caller didn't ask for (mirrors [`resolve_own_workstream_name`]'s
844    /// identical rule for the env var).
845    /// What: an invalid explicit workstream alongside a valid cwd fallback;
846    /// asserts `None`, not the cwd-derived value.
847    /// Test: itself.
848    #[test]
849    fn new_for_caller_invalid_explicit_workstream_returns_none_not_cwd_fallback() {
850        let info = CreatorInfo::new_for_caller(
851            "trusty-memory-mcp",
852            CreatorSource::Mcp,
853            Some("/x/.worktrees/cwd-derived-name"),
854            Some("not a valid name!"),
855        );
856        assert_eq!(info.workstream, None);
857    }
858
859    /// Why (MEDIUM 1, DOC-53 §3.1): a hand-written claim drawer's own tags
860    /// may already carry `ws:<name>` (and, less commonly, a literal
861    /// `creator:workstream=<name>`) — `merge_into_deduped` must not append a
862    /// second copy of either.
863    /// What: seeds `dst` with `ws:feat-x` already present, merges a
864    /// `CreatorInfo` whose rendered tags include `ws:feat-x`, asserts the
865    /// tag appears exactly once while the OTHER rendered tags (which were
866    /// not already present) still land.
867    /// Test: itself.
868    #[test]
869    fn merge_into_deduped_skips_tags_already_present() {
870        let mut tags = vec!["user-tag".to_string(), "ws:feat-x".to_string()];
871        CreatorInfo {
872            client: "trusty-memory-mcp".into(),
873            version: "0.1.0".into(),
874            source: CreatorSource::Mcp,
875            cwd: None,
876            workstream: Some("feat-x".into()),
877        }
878        .merge_into_deduped(&mut tags);
879        assert_eq!(
880            tags.iter().filter(|t| *t == "ws:feat-x").count(),
881            1,
882            "ws:feat-x must not be duplicated; got {tags:?}"
883        );
884        assert!(
885            tags.contains(&"creator:client=trusty-memory-mcp".to_string()),
886            "non-overlapping tags must still be appended; got {tags:?}"
887        );
888        assert!(
889            tags.contains(&"creator:workstream=feat-x".to_string()),
890            "creator:workstream= must still be appended (only ws: overlapped); got {tags:?}"
891        );
892    }
893
894    /// Why: dedup must not become a no-append bug — when nothing overlaps,
895    /// every rendered tag lands exactly as `merge_into` would produce.
896    /// What: seeds `dst` with an unrelated tag only; asserts all rendered
897    /// tags are present.
898    /// Test: itself.
899    #[test]
900    fn merge_into_deduped_appends_when_no_overlap() {
901        let mut tags = vec!["unrelated".to_string()];
902        CreatorInfo {
903            client: "trusty-memory-mcp".into(),
904            version: "0.1.0".into(),
905            source: CreatorSource::Mcp,
906            cwd: None,
907            workstream: Some("feat-x".into()),
908        }
909        .merge_into_deduped(&mut tags);
910        assert_eq!(
911            tags,
912            vec![
913                "unrelated".to_string(),
914                "creator:client=trusty-memory-mcp".to_string(),
915                "creator:version=0.1.0".to_string(),
916                "creator:source=mcp".to_string(),
917                "creator:workstream=feat-x".to_string(),
918                "ws:feat-x".to_string(),
919            ]
920        );
921    }
922
923    /// Why: [`WORKSTREAM_NAME_ENV`] is the forward-compatible primary
924    /// source (DOC-53 §4.3) and must win over the cwd fallback whenever
925    /// set. Serialises on `env_test_lock` since it mutates process-wide
926    /// state.
927    /// What: sets the env var, passes an unrelated (even a `.worktrees`-
928    /// bearing) cwd, and asserts the env value wins.
929    /// Test: itself.
930    #[tokio::test]
931    async fn resolve_workstream_name_prefers_env_var() {
932        let _guard = crate::commands::env_test_lock().lock().await;
933        // SAFETY: serialised by env_test_lock; only this var is touched,
934        // and it is always cleared before returning.
935        unsafe {
936            std::env::set_var(WORKSTREAM_NAME_ENV, "explicit-ws");
937        }
938        let resolved = resolve_own_workstream_name(Some("/x/.worktrees/other-name"));
939        unsafe {
940            std::env::remove_var(WORKSTREAM_NAME_ENV);
941        }
942        assert_eq!(resolved, Some("explicit-ws".to_string()));
943    }
944
945    /// Why: an env var that is SET but fails validation (DOC-53 §4.3) is an
946    /// explicit-but-bad signal — it must resolve to `None`, not silently
947    /// fall through to the cwd heuristic the writer never asked for.
948    /// What: sets an unsafe env value with a plausible cwd fallback present
949    /// and asserts `None`.
950    /// Test: itself.
951    #[tokio::test]
952    async fn resolve_workstream_name_invalid_env_var_returns_none() {
953        let _guard = crate::commands::env_test_lock().lock().await;
954        // SAFETY: serialised by env_test_lock.
955        unsafe {
956            std::env::set_var(WORKSTREAM_NAME_ENV, "not a valid name!");
957        }
958        let resolved = resolve_own_workstream_name(Some("/x/.worktrees/other-name"));
959        unsafe {
960            std::env::remove_var(WORKSTREAM_NAME_ENV);
961        }
962        assert_eq!(resolved, None);
963    }
964
965    /// Why: the common case — a `tm`-managed PM session running directly in
966    /// its own `.worktrees/<name>` checkout — must resolve without any `tm`
967    /// changes (DOC-53 §4.3). [`resolve_workstream_name`] is pure cwd-based
968    /// (no env var involved, see its doc comment), so no locking is needed.
969    /// What: feeds a realistic worktree cwd, asserts the segment
970    /// immediately after `.worktrees` is returned.
971    /// Test: itself.
972    #[test]
973    fn resolve_workstream_name_falls_back_to_worktrees_cwd_segment() {
974        let resolved = resolve_workstream_name(Some(
975            "/Users/bob/trusty-tools/.base/.worktrees/feat-ws-memory-claims",
976        ));
977        assert_eq!(resolved, Some("feat-ws-memory-claims".to_string()));
978    }
979
980    /// Why: ephemeral/anonymous scratch worktrees are named by UUID, not by
981    /// workstream (DOC-53 §4.3) — stamping one would produce noise
982    /// indistinguishable from a real name, so it must resolve to `None`.
983    /// What: feeds a UUID-named `.worktrees/<uuid>` cwd, asserts `None`.
984    /// Test: itself.
985    #[test]
986    fn resolve_workstream_name_rejects_uuid_shaped_cwd_segment() {
987        let resolved = resolve_workstream_name(Some(
988            "/Users/bob/trusty-tools/.base/.worktrees/2eb72dca-de08-481b-8dfa-22ab7f81b1f9",
989        ));
990        assert_eq!(resolved, None);
991    }
992
993    /// Why: a cwd with no `.worktrees` component (or no cwd at all) is the
994    /// honest "can't resolve this" case — DOC-53 §4.1's omit-cleanly rule,
995    /// exercised at the resolver level.
996    /// What: cwd `None`; then a cwd with no `.worktrees` segment. Both
997    /// resolve to `None`.
998    /// Test: itself.
999    #[test]
1000    fn resolve_workstream_name_none_when_unresolvable() {
1001        assert_eq!(resolve_workstream_name(None), None);
1002        assert_eq!(
1003            resolve_workstream_name(Some("/Users/bob/some/other/project")),
1004            None
1005        );
1006    }
1007
1008    /// Why: the validator is the single gate standing between untrusted
1009    /// input (env var or cwd segment) and a rendered tag — it must accept
1010    /// ordinary slugs.
1011    /// What: table of accepted names.
1012    /// Test: itself.
1013    #[test]
1014    fn is_valid_workstream_name_accepts_slugs() {
1015        for name in [
1016            "feat-ws-memory-claims",
1017            "tm_search_eviction_01",
1018            "a",
1019            "release.0.20.0",
1020        ] {
1021            assert!(is_valid_workstream_name(name), "expected valid: {name}");
1022        }
1023    }
1024
1025    /// Why: the validator must reject both structurally-unsafe candidates
1026    /// (empty, overlong, unsafe characters, non-alnum leading char) and
1027    /// UUID-shaped candidates (DOC-53 §4.3's anonymous-worktree exclusion),
1028    /// since a caller (env var or cwd) is untrusted input.
1029    /// What: table of rejected names.
1030    /// Test: itself.
1031    #[test]
1032    fn is_valid_workstream_name_rejects_uuid_and_unsafe_names() {
1033        for name in [
1034            "",
1035            "2eb72dca-de08-481b-8dfa-22ab7f81b1f9",
1036            "-leading-dash",
1037            "has space",
1038            "has/slash",
1039            "has;semicolon",
1040            &"x".repeat(65),
1041        ] {
1042            assert!(!is_valid_workstream_name(name), "expected invalid: {name}");
1043        }
1044    }
1045}