Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(importer): decode WebVTT cue character references
Samir Hanna Verza5a289f3abe83
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e65cba04..e51cc01a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,9 @@ version in [`docs/changelog/`](docs/changelog/):### Fixed+- Decoded WebVTT cue character references before document-import sanitization,+ preserving literal escaped tags and applying the existing text-size limit+ to the decoded text. SRT extraction is unchanged (#PR).- Refused empty and whitespace-only `--workspace` and `--project` flags at theshared CLI scope-resolution choke point (`resolve_scope`,`resolve_scope_noting_marker_project`, `resolve_scope_with_marker`, anddiff --git a/companions/ai-memory-importer/Cargo.lock b/companions/ai-memory-importer/Cargo.lockindex f84ecffe..7774f66c 100644--- a/companions/ai-memory-importer/Cargo.lock+++ b/companions/ai-memory-importer/Cargo.lock@@ -44,6 +44,7 @@ dependencies = ["ai-memory-client","anyhow","clap",+ "htmlize","libc","lopdf","quick-xml",@@ -603,6 +604,19 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]+name = "htmlize"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e815d50d9e411ba2690d730e6ec139c08260dddb756df315dbd16d01a587226"+dependencies = [+ "memchr",+ "pastey",+ "phf",+ "phf_codegen",+ "serde_json",+]+[[package]]name = "http"version = "1.4.2"@@ -1010,12 +1024,56 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"+[[package]]+name = "pastey"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"+[[package]]name = "percent-encoding"version = "2.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+[[package]]+name = "phf"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"+dependencies = [+ "phf_shared",+]++[[package]]+name = "phf_codegen"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"+dependencies = [+ "phf_generator",+ "phf_shared",+]++[[package]]+name = "phf_generator"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"+dependencies = [+ "fastrand",+ "phf_shared",+]++[[package]]+name = "phf_shared"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"+dependencies = [+ "siphasher",+]+[[package]]name = "pin-project-lite"version = "0.2.17"@@ -1473,6 +1531,12 @@ version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"+[[package]]+name = "siphasher"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"+[[package]]name = "slab"version = "0.4.12"diff --git a/companions/ai-memory-importer/Cargo.toml b/companions/ai-memory-importer/Cargo.tomlindex 93d0eb22..527f05b9 100644--- a/companions/ai-memory-importer/Cargo.toml+++ b/companions/ai-memory-importer/Cargo.toml@@ -11,6 +11,7 @@ publish = falseai-memory-client = { version = "0.1.0", path = "../ai-memory-client" }anyhow = "1"clap = { version = "4", features = ["derive", "env"] }+htmlize = { version = "1.1", features = ["unescape"] }# Pure-Rust text-layer extraction. It does not OCR scanned/image-only PDFs.lopdf = { version = "0.45", default-features = false }quick-xml = "0.42"diff --git a/companions/ai-memory-importer/README.md b/companions/ai-memory-importer/README.mdindex 2e3eb91b..30a9efe5 100644--- a/companions/ai-memory-importer/README.md+++ b/companions/ai-memory-importer/README.md@@ -147,7 +147,9 @@ visibility rules matter.VTT/SRT files accept LF, CRLF, or CR line endings and any number of blank linesbetween cues. WebVTT comments are omitted; identifiers such as `NOTE123` keep-their cue text.+their cue text. WebVTT character references such as `&` and `é` are+decoded once before sanitization. Escaped tags remain literal text, and SRT+character references retain their original spelling.## Safety contractdiff --git a/companions/ai-memory-importer/src/document.rs b/companions/ai-memory-importer/src/document.rsindex 3622194b..ccbb1e83 100644--- a/companions/ai-memory-importer/src/document.rs+++ b/companions/ai-memory-importer/src/document.rs@@ -1061,7 +1061,7 @@ fn extract_transcript(bytes: &[u8], webvtt: bool) -> Result<String> {if line.is_empty() {continue;}- push_bounded(&mut output, clean_transcript_markup(line).trim())?;+ push_bounded(&mut output, clean_transcript_markup(line, webvtt).trim())?;push_bounded(&mut output, "\n")?;}if !output.is_empty() && !output.ends_with("\n\n") {@@ -1086,14 +1086,25 @@ fn is_timing_line(line: &str) -> bool {looks_like_timestamp(start) && looks_like_timestamp(end)}-fn clean_transcript_markup(line: &str) -> String {+fn clean_transcript_markup(line: &str, webvtt: bool) -> String {+ // WebVTT uses HTML character references in text (not attribute) context:+ // https://www.w3.org/TR/webvtt1/#webvtt-cue-text-parsing-rules+ // Decode original text segments once: escaped tags remain literal, and+ // removing markup cannot join fragments into a new character reference.+ let push_text = |output: &mut String, text: &str| {+ if webvtt {+ output.push_str(&htmlize::unescape(text));+ } else {+ output.push_str(text);+ }+ };let mut output = String::with_capacity(line.len());let mut rest = line;while let Some(start) = rest.find('<') {- output.push_str(&rest[..start]);+ push_text(&mut output, &rest[..start]);let after_start = &rest[start + 1..];let Some(end) = after_start.find('>') else {- output.push_str(&rest[start..]);+ push_text(&mut output, &rest[start..]);return output;};let candidate = &after_start[..end];@@ -1104,7 +1115,7 @@ fn clean_transcript_markup(line: &str) -> String {}rest = &after_start[end + 1..];}- output.push_str(rest);+ push_text(&mut output, rest);output}@@ -1734,6 +1745,98 @@ mod tests {assert_eq!(text.trim(), "12345\n\nSecond line");}+ #[test]+ fn webvtt_decodes_character_references_in_cue_text() {+ for (payload, expected) in [+ (+ "AT&T: 1 < 2 > 0, a b ‎left ‏right",+ "AT&T: 1 < 2 > 0, a\u{a0}b \u{200e}left \u{200f}right",+ ),+ (+ "'café' 🙂 ™ ≂̸",+ "'café' 🙂 ™ ≂\u{338}",+ ),+ ("¬it; © 2026 A A A", "¬it; © 2026 A A A"),+ (+ "� � � € �",+ "� � � € �",+ ),+ (+ "&unknown; &#; &#x; bare & ampersand &",+ "&unknown; &#; &#x; bare & ampersand &",+ ),+ ] {+ let input = format!("WEBVTT\n\n00:00:01.000 --> 00:00:02.000\n{payload}\n");+ assert_eq!(+ extract_transcript(input.as_bytes(), true).unwrap().trim(),+ expected,+ "cue payload {payload:?}"+ );+ }+ }++ #[test]+ fn webvtt_decodes_once_without_reparsing_or_joining_markup() {+ for (payload, expected) in [+ (+ "<v Alice><b>AT&T</b> <b>literal</b></v>",+ "AT&T <b>literal</b>",+ ),+ ("&lt; &amp;", "< &"),+ ("&am<b></b>p; &#x<i></i>41;", "& A"),+ ("<unknown>&</unknown>", "<unknown>&</unknown>"),+ ("1 < 2 &", "1 < 2 &"),+ (+ "<v Alice><b>First &\nSecond <third></b></v>",+ "First &\nSecond <third>",+ ),+ ("&am\np;", "&am\np;"),+ ] {+ let input = format!("WEBVTT\n\n00:00:01.000 --> 00:00:02.000\n{payload}\n");+ assert_eq!(+ extract_transcript(input.as_bytes(), true).unwrap().trim(),+ expected,+ "cue payload {payload:?}"+ );+ }+ }++ #[test]+ fn srt_keeps_character_references_literal() {+ let input =+ b"1\n00:00:01,000 --> 00:00:02,000\n<b>AT&T</b> <b>literal</b> A\n";+ assert_eq!(+ extract_transcript(input, false).unwrap().trim(),+ "AT&T <b>literal</b> A"+ );+ }++ #[test]+ fn webvtt_decoded_text_is_sanitized_before_the_document_plan() {+ let temp = TempDir::new().unwrap();+ let file = temp.path().join("captions.vtt");+ fs::write(+ &file,+ "WEBVTT\n\nNOTE annotation\nCOMMENT_SENTINEL\n\n00:00:01.000 --> 00:00:02.000\nKnown fact AT&T token=abcdefghijklmnop\nLiteral <b>sample</b> &lt;\n",+ )+ .unwrap();+ let plan = plan_document(&file, "w", "p", DEFAULT_DEST_PREFIX, None).unwrap();+ assert!(plan.body.contains("Known fact AT&T"));+ assert!(plan.body.contains("token=[REDACTED]"));+ assert!(plan.body.contains("Literal <b>sample</b> <"));+ assert!(!plan.body.contains("abcdefghijklmnop"));+ assert!(!plan.body.contains("COMMENT_SENTINEL"));+ }++ #[test]+ fn webvtt_entity_expansion_respects_the_working_text_limit() {+ // ≫⃒ has five input bytes and expands to six UTF-8 bytes.+ let payload = "≫⃒".repeat(MAX_WORKING_TEXT_BYTES / 6 + 1);+ assert!(payload.len() < MAX_WORKING_TEXT_BYTES);+ let input = format!("WEBVTT\n\n00:00:01.000 --> 00:00:02.000\n{payload}\n");+ assert!(extract_transcript(input.as_bytes(), true).is_err());+ }+#[test]fn webvtt_keeps_cues_whose_identifiers_only_start_with_note() {let vtt = b"WEBVTT\n\nNOTE an actual comment\nNot spoken\n\nNOTEworthy\n00:00:01.000 --> 00:00:02.000\nKeep this fact\n\nNOTE123\n00:00:03.000 --> 00:00:04.000\nKeep this too\n\nNOTE\tanother comment\nNot spoken either\n\nNOTE\nNot spoken at all\n";diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 23b2d5a6..4f671daf 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -138,7 +138,7 @@ the legitimate restricted-project control and the failed-query cases.| 14h | Wiki link graph pages and JSON show only readable projects (#708) | `ai-memory-web/src/routes/graph.rs` `global_handler` calls `ReaderPool::cross_project_edges(None, viewer)` so an edge needs both ends readable; `project_handler` resolves through `resolve_read_scope` (`lookup_existing_scope_guarded`, no-create, `ProjectAccess::Read`) then `project_link_graph`, which ranks and caps nodes in SQL before loading them and queries only edges whose endpoints are among those selected pages; `api.rs` `graph_handler` accepts `workspace`+`project` together (partial scope 400) and passes the same viewer filter, and `project_graph_handler` uses `lookup_project` | `routes.rs` `metadata_shows_only_what_the_viewer_may_read` (HTML `/web/graph`, `/web/w/…/graph`, `/api/v1/…/graph`, and scoped `/api/v1/graph?workspace=&project=`: bob cannot see alpha or client-work, a 403 on alpha's graph leaks neither title nor path, a scoped graph hides an edge whose far end he cannot read; carol and no-viewer controls keep the edge; partial scope 400); store `project_link_graph.rs` hides expired pages, omits cross-project and unresolved links, and verifies the 120-node SQL cap preserves high-degree nodes; `graph.rs` `graph_page_renders_hostile_titles_inert` | STRONG. Bite checks: passing no viewer to `cross_project_edges` in the HTML global handler, resolving the project graph through unguarded `lookup_existing_scope`, or removing the SQL limit fails the restricted-project or node-cap assertions || 14i | Decoded ordinary Markdown destinations stay inside their original project | `ai-memory-wiki/src/markdown.rs` `decode_markdown_destination_path` decodes URL path bytes once before `normalize_link_target` applies scheme, separator and project-root traversal checks; wikilinks remain literal. `ai-memory-web/src/markdown.rs` `scope_relative_link` checks the decoded path before route encoding; an encoded spelling cannot become a generated cross-scope route. | `markdown_url_paths_decode_once_before_link_resolution` (space, Unicode and literal-percent controls); `decoded_markdown_paths_cannot_escape_or_change_scope` (encoded root escape, backslash, external scheme, invalid UTF-8 and controls refused; legitimate in-root normalization passes); `routes.rs` `encoded_markdown_links_resolve_and_remain_in_the_source_scope` writes colliding targets in sibling projects and workspaces, verifies home resolution and no foreign backlinks, and follows the generated home URL; web `decoded_markdown_destinations_cannot_change_the_web_scope` (encoded traversal, root route, separator and scheme refused, encoded `w/` remains a page inside the current scope); `markdown_url_destinations_are_decoded_once_before_route_encoding` | STRONG for one-decode path handling and project confinement; URL grammar outside local Markdown destinations remains owned by the Markdown parser and existing safe-URL checks || 14j | Structured MCP query filters only narrow authorized page results | `ai-memory-mcp/src/server.rs` parses bounded `kind`, `tier`, literal `path_prefix` and exact `tag` values without changing the normal scope-shape or authorization paths, then passes one typed `PageFilter` through project, multi-scope, cross-project, reserved-global/profile, historical and pinned searches. `ai-memory-store/src/reader.rs` binds every filter value as a SQL parameter before each stream's candidate cut; path wildcard characters are escaped and an exact binary-prefix check preserves case, while tags match only string members of a JSON array. A filtered miss cannot fall through to raw observations, which carry no page metadata. | `server.rs` `memory_query_filters_apply_before_every_result_source` combines all filters and covers literal `%`/`_`, case-sensitive paths, tag arrays versus scalars, multi-scope and global search, `as_of`, superseded metadata, `pin_first`, the reserved-global/profile union, traversal-shaped input, invalid tiers, controls and Unicode length bounds; store `structured_filters_hold_in_vector_and_both_graph_directions` isolates path filtering in the vector stream and tag filtering in outgoing and incoming graph expansion; `page_filtering_precedes_the_observation_candidate_cut` puts 80 stronger excluded observations ahead of an eligible tagged session; `memory_query_returns_raw_hits_when_pages_miss` proves an unfiltered miss retains fallback while a filtered miss omits it; `prompts_and_tool_schema_document_query_options` pins the public schema. Existing web every-stream and authorization tests in row 14g exercise kind/tier across the same shared SQL. | STRONG: filters are candidate predicates, never an alternative scope resolver. Empty filter fields normalize to absent for backward compatibility; observation fallback remains available only to unfiltered queries. |-| 14k | Optional document import treats local files as bounded untrusted input | `companions/ai-memory-importer/src/document.rs` accepts one explicit regular file on Unix (and fails closed elsewhere), refuses final symlinks, uses `O_NOFOLLOW` plus opened-inode verification, caps source/archive/entry/working/stored text/PDF-stream/sheet/actual-cell dimensions, streams XLSX cells without allocating their coordinate rectangle, follows PPTX relationship order, rejects unsupported or malformed formats, sanitizes extracted text before manifest or transport, derives the destination and stable provenance key from the source SHA-256, and writes through MCP `create_only` with explicit scope. A conflict is accepted as idempotent only when the current page body exactly equals the current sanitized plan; a provenance marker alone is never trusted and another page is never replaced. Shared manifests use randomized private same-directory temporary files, fsync, and atomic replacement. | Importer `document::tests`: generated bounded and over-limit PDF, visible-text DOCX, relationship-ordered PPTX, sparse-coordinate XLSX, text and cue-state VTT/SRT controls; `subtitle_cues_are_sanitized_before_the_document_plan` keeps ordinary and NOTE-prefixed cues across LF/CRLF/CR, redacts a credential in each, and excludes actual comments; `text_plan_is_redacted_bounded_attributed_and_deterministic`; `unsafe_sources_prefixes_and_malformed_archives_fail_closed`; `zip_preflight_refuses_excessive_claimed_expansion`; `apply_is_conditional_idempotent_and_refuses_foreign_pages`; shared writer tests cover repeated replacement and a pre-created legacy temp symlink. | STRONG for explicit Unix local text extraction and conditional persistence. Operator review with `--show-body` remains necessary because DOCX formatting-hidden text can be extracted. OCR, images, raw media, watch folders and server-side upload are excluded. |+| 14k | Optional document import treats local files as bounded untrusted input | `companions/ai-memory-importer/src/document.rs` accepts one explicit regular file on Unix (and fails closed elsewhere), refuses final symlinks, uses `O_NOFOLLOW` plus opened-inode verification, caps source/archive/entry/working/stored text/PDF-stream/sheet/actual-cell dimensions, streams XLSX cells without allocating their coordinate rectangle, follows PPTX relationship order, rejects unsupported or malformed formats, decodes WebVTT character references once in original text segments before sanitization and the working-text limit, sanitizes extracted text before manifest or transport, derives the destination and stable provenance key from the source SHA-256, and writes through MCP `create_only` with explicit scope. A conflict is accepted as idempotent only when the current page body exactly equals the current sanitized plan; a provenance marker alone is never trusted and another page is never replaced. Shared manifests use randomized private same-directory temporary files, fsync, and atomic replacement. | Importer `document::tests`: generated bounded and over-limit PDF, visible-text DOCX, relationship-ordered PPTX, sparse-coordinate XLSX, text and cue-state VTT/SRT controls; `subtitle_cues_are_sanitized_before_the_document_plan` keeps ordinary and NOTE-prefixed cues across LF/CRLF/CR, redacts a credential in each, and excludes actual comments; `webvtt_decoded_text_is_sanitized_before_the_document_plan` redacts a credential after reference decoding with retained cue text as its control (fails when sanitization is removed); `webvtt_decodes_once_without_reparsing_or_joining_markup` preserves escaped tags, single decoding, and tag/line boundaries; `webvtt_entity_expansion_respects_the_working_text_limit` refuses text that grows beyond the cap when decoded; `text_plan_is_redacted_bounded_attributed_and_deterministic`; `unsafe_sources_prefixes_and_malformed_archives_fail_closed`; `zip_preflight_refuses_excessive_claimed_expansion`; `apply_is_conditional_idempotent_and_refuses_foreign_pages`; shared writer tests cover repeated replacement and a pre-created legacy temp symlink. | STRONG for explicit Unix local text extraction and conditional persistence. Operator review with `--show-body` remains necessary because DOCX formatting-hidden text can be extracted. OCR, images, raw media, watch folders and server-side upload are excluded. || 15 | Agent-archive restore path confinement, resource bounds, and consistency | `ai-memory-cli/src/commands/restore_agents.rs` stages only bounded regular UTF-8 entries; requires a one-to-one manifest/body/checksum/target mapping; allowlists destinations by scope; rejects symlinked descendants; treats differing portable permissions as an overwrite requiring `--apply --force`; writes each file atomically and rolls back earlier writes after a later failure. `backup_agents.rs` skips direct and directory-root source symlinks, bounds individual assets, attributes a shared skill root only once, and atomically replaces a private archive only after gzip completion | `backup_agents.rs` `restore_agents_checks_permissions_before_skipping_identical_content` (same bytes with changed mode are previewed and refused without `--force`; forced restore preserves a backup and a second run is a no-op), `restore_agents_without_archived_permissions_keeps_identical_file_mode` (missing-mode control), `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`, `restore_agents_requires_a_complete_one_to_one_manifest`, `restore_agents_rejects_oversized_entries_from_the_header`, `restore_agents_rejects_a_symlinked_destination_parent`, `backup_agents_does_not_follow_config_or_asset_root_symlinks` (Claude and Antigravity roots), and `failed_backup_leaves_the_previous_archive_intact`; `backup_and_restore_agents_round_trip` and `antigravity_backup_round_trips_every_documented_skill_root` are the valid-path controls; `restore_agents::tests::rollback_removes_new_files_and_restores_overwrites` covers recovery | STRONG || 16 | Relay queue identity, migration, and private filesystem state | `companions/ai-memory-relay/src/queue.rs` `Queue::open_inner` performs read-only identity preflight, rechecks under `IMMEDIATE`, commits schema and metadata together; `configure` checks the presence of user objects and rechecks `identity`/`schema_version` metadata on the same connection before every bounded BUSY/LOCKED retry; `fsguard.rs` checks existing paths and creates owner-only files before SQLite opens them | `tests/relay.rs` `a_foreign_database_is_refused_byte_for_byte`, `unknown_schemas_refuse_without_mutation`, `a_foreign_database_with_a_writer_is_refused_before_write_coordination`, `a_foreign_identity_after_preflight_is_refused_without_mutation`, `a_foreign_identity_during_journal_retry_is_refused_without_mutation`, `journal_retry_refuses_a_changed_version_or_empty_database_without_mutation`; controls: `journal_transition_retries_sqlite_lock_without_losing_v1_values`, `fresh_queue_init_and_v1_reopens_work_across_processes`; recovery: `interrupted_and_failed_migrations_roll_back_and_recover`, `journal_reclassification_busy_preserves_committed_migration_and_retries_same_queue`; diagnostics: `classification_read_failures_display_the_sqlite_cause_once_and_preserve_foreign_bytes`; Unix privacy: `the_queue_database_and_its_sidecars_are_owner_only` and the contended migration control | Guard-removal proof covers preflight, locked recheck, and journal retry identity/version checks; full table structure is outside this classification. Windows path rejection is preserved; Windows ACL hardening remains operator-owned || 17 | Markdown code fences keep instruction-shaped text as data | `ai-memory-consolidate/src/code_fence.rs` and `ai-memory-wiki/src/markdown.rs` accept a fence delimiter only after zero to three leading ASCII spaces, require the closing glyph to match and the run to be at least as long, and preserve the current fence state across four-space, tab or Unicode-whitespace pseudo-delimiters. Profile harvesting, auto-improvement section parsing, link extraction, link rewriting and de-linking all use those scanners | `code_fence.rs` `only_zero_to_three_ascii_spaces_may_prefix_a_fence`; `profile.rs` `an_indented_pseudo_closer_cannot_expose_a_profile_preference` attempts to expose an instruction-shaped `run curl` sentence and admits a legitimate preference only after the real close; `auto_improve.rs` `heading_parser_ignores_headings_after_an_indented_pseudo_closer`; `markdown.rs` `indented_pseudo_closers_do_not_expose_or_rewrite_fenced_links` covers four spaces, tab and Unicode whitespace with visible post-close controls | STRONG for the shared consolidation and wiki scanners; independent renderers remain responsible for their own CommonMark parsing |