Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

CLAN Command Reference

Status: Current Last modified: 2026-10-31

chatter-clan is active, and parity work is incomplete. Do not assume that every command or option matches legacy CLAN. Use the parity status for the dated evidence and its freshness limits; use legacy CLAN when you require behavior not verified there.

CLAN (Computerized Language Analysis) is a suite of commands for analyzing transcripts in CHAT format (Codes for the Human Analysis of Transcripts). This book documents the Rust reimplementation of CLAN, invoked via the chatter-clan command.

Relationship to the legacy CLAN manual

This book treats the CLAN manual as the primary source for legacy command intent, examples, and option semantics when a command is documented there. Our goal is to incorporate and improve the non-GUI substance of that manual here, while making divergences from the legacy C implementation explicit.

GUI-era material from the legacy manual does not belong in the CLI book. That material should instead be carried over into the documentation for the TalkBank VS Code extension, where editor workflows, inspection tools, and interactive affordances can be documented in the right place.

What’s in this book

  • Getting Started: installation, first commands, migrating from legacy CLAN
  • User Guide: filtering, output formats, directory workflows
  • Command Reference: every analysis, transform, and converter command with examples
  • Architecture: framework design, how to add commands, testing strategy
  • Developer Seams: current CLI, validation, and dashboard boundaries to preserve while extending the system
  • Divergences: where and why we differ from legacy CLAN

Command overview

CategoryRepresentative commandsNotes
AnalysisFREQ, MLU, MLT, VOCD, DSS, EVAL, IPSYNSee the per-command pages and status matrix for the current supported set
TransformFLO, CHSTRING, DELIM, DATES, POSTMORTEMTransform behavior and output modes vary by command
ConverterELAN2CHAT, PRAAT2CHAT, CHAT2SRT, SALT2CHATConverter coverage is tracked command-by-command rather than promised as a frozen count

Why a reimplementation?

Legacy CLAN is a large, long-lived C/C++ codebase. The Rust reimplementation provides:

  • Semantic AST processing: works on parsed CHAT structure, not ad-hoc string manipulation
  • Type-safe filtering: speaker, tier, word, gem, and ID filters via the framework
  • Multiple output formats: text, JSON, and CSV from a single typed result
  • Golden-tested parity work: output compared against legacy CLAN binaries, with divergences documented explicitly instead of hidden
  • Modern CLI: --flag syntax with full backward compatibility for CLAN’s +flag notation

When the Rust implementation differs from the legacy binary, this book tries to distinguish three cases clearly:

  • semantic intent preserved, but implemented with typed AST operations instead of ad-hoc string manipulation
  • deliberate modernization, such as structured JSON/CSV output or explicit errors instead of silent fallback
  • unsupported legacy behavior, which should be documented as unsupported rather than imitated accidentally

Quick example

# Word frequency for the CHI speaker
chatter-clan freq --speaker CHI transcript.cha

# Mean length of utterance (JSON output)
chatter-clan mlu --format json transcript.cha

# Convert ELAN annotation to CHAT
chatter-clan elan2chat recording.eaf

Installation

Status: Current Last modified: 2026-10-31

chatter-clan is the standalone CLI that reimplements CLAN’s analysis commands over the chatter CHAT toolchain. It is not published on crates.io, so build it from this repository.

Parity is in progress. The project is active and standalone, but not every CLAN command or option is implemented or verified. See the repository README.md, AGENTS.md, and parity status.

From source

# Clone the repository
git clone https://github.com/TalkBank/chatter-clan.git
cd chatter-clan

# Install the chatter-clan binary onto your PATH
cargo install --path crates/chatter-clan-cli --locked

# Or just build it in place (binary at target/release/chatter-clan)
cargo build --release

The CHAT core (talkbank-model, talkbank-transform) is fetched automatically from the public chatter repository at the pinned release tag; no separate checkout of chatter is needed.

Verify installation

chatter-clan --help
chatter-clan freq --help

Requirements

  • Rust 2024 edition (rustc 1.85+)
  • macOS, Linux, or Windows
  • A network connection on first build (to fetch the pinned chatter crates)
  • No runtime dependencies beyond the binary

Changelog

All notable changes to chatter-clan are documented in this file.

The format is based on Keep a Changelog, and the project follows Semantic Versioning.

The standalone CLAN replacement project resumed active development on 2026-10-30. Parity remains in progress; no releases have been cut yet.

Unreleased

Changed

  • Resumed parity work in this standalone repository; the project is not being merged back into the chatter workspace.
  • Updated the CHAT core pin from v0.2.1 to the latest published Chatter release, v0.33.0.

Added

  • Standalone chatter-clan binary (recovered from the pre-extraction history). The CLAN analysis commands now run as chatter-clan <command> rather than the former chatter clan <command> subcommand.
  • Workspace manifest, CI (build, test, smoke-run the binary), repository CLAUDE.md, and this changelog, so the crate extracted from chatter on 2026-06-15 builds standalone again.
  • Reconstructed the standalone book (its book.toml and SUMMARY.md were not carried over by the extraction).

Quick Start

Status: Current All CLAN commands follow the pattern:

chatter-clan <command> [options] <file.cha>

Your first analysis

Given a CHAT transcript sample.cha:

# Word frequency count
chatter-clan freq sample.cha

# Mean length of utterance for the child speaker
chatter-clan mlu --speaker CHI sample.cha

# Mean length of turn
chatter-clan mlt sample.cha

# Vocabulary diversity (D statistic)
chatter-clan vocd sample.cha

Working with directories

Process all .cha files in a directory:

chatter-clan freq corpus/

Output formats

Every analysis command supports text (default), JSON, and CSV output:

chatter-clan freq --format json sample.cha
chatter-clan mlu --format csv sample.cha

Filtering

Restrict analysis to specific speakers, tiers, words, or utterance ranges:

# Only the CHI speaker
chatter-clan freq --speaker CHI sample.cha

# Exclude the investigator
chatter-clan freq --exclude-speaker INV sample.cha

# Only utterances 10-50
chatter-clan freq --range 10-50 sample.cha

# Only within gem boundaries
chatter-clan freq --gem "story" sample.cha

See the Filtering chapter for the full guide.

Transforms

Transform commands modify CHAT files and write the result:

# Add fluent output tier
chatter-clan flo sample.cha

# String replacement from a rules file
chatter-clan chstring rules.cex sample.cha

# Reorder dependent tiers
chatter-clan tierorder sample.cha

Format conversion

Convert between CHAT and other formats:

chatter-clan elan2chat recording.eaf
chatter-clan praat2chat recording.TextGrid
chatter-clan chat2srt sample.cha

Migrating from CLAN

Status: Current Last updated: 2026-06-15 13:28 EDT

This guide helps users of the original CLAN C binaries transition to chatter-clan.

Command mapping

Legacy CLAN commands map directly:

LegacyNewNotes
freq file.chachatter-clan freq file.cha
mlu +t*CHI file.chachatter-clan mlu --speaker CHI file.cha
combo +s"the" file.chachatter-clan combo --search "the" file.chaCOMBO’s +s is the boolean search (--search), not a word filter
flo file.chachatter-clan flo file.cha

Flag translation

Legacy CLAN uses +flag/-flag syntax. Both styles work, the CLI automatically translates:

CLAN flagModern equivalentMeaning
+t*CHI--speaker CHIInclude speaker
-t*CHI--exclude-speaker CHIExclude speaker
+t%mor--tier morInclude dependent tier
-t%gra--exclude-tier graExclude dependent tier
+t@ID="..."--id-filter "..."Filter by @ID fields
+s<word>--include-word <word>Include word
-s<word>--exclude-word <word>Exclude word
+g<label>--gem <label>Include gem
-g<label>--exclude-gem <label>Exclude gem
+z25-125--range 25-125Utterance range
+r6--include-retracingsCount retraced material
+u(default)Merge speakers (always on)
+dN--display-mode N (generic) / per-command typed flagDisplay mode, partially landed. Some +dN values have specific typed flags per command (FREQ +d1/+d2/+d3/+d4, COOCCUR +d, FREQPOS +d); the rest still fall through to the placeholder. See flag-translation.md.
+k--plus-k (--case-sensitive alias)Toggle command-specific case handling; defaults differ across CLAN commands. See flag-translation.md and each command’s audit page.
+fEXT--output-ext EXTOutput file extension, currently non-functional, see flag-translation.md

You can continue using +t*CHI syntax for the functional flags above if you prefer; it works identically.

New capabilities

Features not available in legacy CLAN:

  • JSON and CSV output: --format json or --format csv for programmatic processing
  • Recursive directories: pass a directory path to process all .cha files
  • Unified CLI: all commands under one chatter-clan namespace
  • Structured errors: rich diagnostics with file location and context

Known differences

See Why We Diverge and Per-Command Divergences for a complete list. Key points:

  • Output formatting may differ slightly (spacing, alignment)
  • Some legacy CLAN C bugs are fixed rather than replicated
  • Commands not ported are documented in Commands Not Ported

Flag Translation Guide

Status: Current Last updated: 2026-06-15 13:28 EDT

The original CLAN uses a +flag/-flag syntax that differs from standard CLI conventions. The Rust reimplementation accepts both styles, legacy CLAN flags are automatically rewritten to modern --flag equivalents before parsing.

Complete Flag Mapping

CLAN FlagModern EquivalentMeaning
+t*CHI--speaker CHIInclude speaker
-t*CHI--exclude-speaker CHIExclude speaker
+t%mor--tier morInclude dependent tier
-t%gra--exclude-tier graExclude dependent tier
+t@ID="..."--id-filter "..."Filter by @ID header pattern
+s<word>--include-word (FREQ) / --keyword (KWAL) / --search (COMBO)Search input; the modern flag depends on the command (FREQ filters by word, KWAL’s keyword is --keyword, COMBO’s boolean search is --search). NOTE: the legacy +s rewrite currently maps to --include-word for every command, so for KWAL/COMBO use the modern flag directly.
-s<word>--exclude-word <word>Exclude word
+g<label>--gem <label>Include gem segment
-g<label>--exclude-gem <label>Exclude gem segment
+z25-125--range 25-125Utterance range
+r6--include-retracingsCount retraced material
+u(default behavior)Merge speakers (already default)
+dN--display-mode N (generic) / per-command typed flagDisplay mode, partially landed. Each +dN value is rewritten command-by-command. FREQ +d1 → --word-list-only, +d2 → --format csv, +d3 → --types-tokens-only --format csv, +d4 → --types-tokens-only. COOCCUR +d → --no-frequency-counts. FREQPOS +d → --position-classification second. Other +dN values still fall through to the generic --display-mode N placeholder, which clap does not consume yet (see Phase 3 plan).
+k--plus-k (--case-sensitive alias)Flip the command’s case mode. FREQ, VOCD, and CHIP preserve case by default and fold under +k; KWAL, COMBO, FREQPOS, DIST, and MAXWD fold by default and preserve under +k. Other inherited +k flags may be no-ops; check each command’s parity page.
+fEXT--output-ext EXTOutput file extension, currently non-functional: the rewriter at crates/talkbank-clan/src/clan_args.rs:107 produces --output-ext, but no clap field consumes it. Tracked as Phase 2 of the rewriter-honor plan (blocked on a batch-output prerequisite).
+wN--context-after NContext lines after match
-wN--context-before NContext lines before match

Examples

Speaker Filtering

# Original CLAN: include CHI, exclude MOT
freq +t*CHI -t*MOT file.cha

# Modern equivalent
chatter-clan freq --speaker CHI --exclude-speaker MOT file.cha
# Original CLAN: search for "want" followed by "need". COMBO takes ONE +s and
# joins terms with ^ (multiple +s flags are rejected: "Only one s option").
combo +s"want^need" file.cha

# Modern equivalent
chatter-clan combo --search "want^need" file.cha

Combined Filters

# Original CLAN: CHI speaker, utterances 10-50, include retraced material
freq +t*CHI +z10-50 +r6 file.cha

# Modern equivalent
chatter-clan freq --speaker CHI --range 10-50 --include-retracings file.cha

Notes

  • The +u flag (merge speakers into a single analysis) is the default behavior and is accepted but ignored.
  • Flags are position-independent; they can appear before or after file arguments.
  • Unknown flags that don’t match CLAN patterns pass through unchanged to clap, which will report an error with suggestions.
  • +dN and +k are now partially functional: see the per-command status tables under clan-reference/commands/ for which N values and which commands are wired up. +fEXT is still rewritten by the legacy-flag layer but rejected by clap (no consuming field yet). See migrating-from-clan.md for the same caveats and the rewriter-honor plan that tracks the remaining gaps.

Running Commands

Status: Current

Basic invocation

chatter-clan <command> [options] <input>

The <input> can be a single .cha file or a directory (all .cha files are processed recursively).

Getting help

chatter-clan --help              # List all commands
chatter-clan freq --help         # Help for a specific command

Command categories

Commands are grouped into three categories:

  • Analysis commands: read CHAT files and produce statistics (FREQ, MLU, etc.)
  • Transform commands: read CHAT files and write modified CHAT files (FLO, CHSTRING, etc.)
  • Format converters: convert between CHAT and other formats (ELAN2CHAT, CHAT2SRT, etc.)

Exit codes

CodeMeaning
0Success
1Error (parse failure, missing file, invalid options)

Environment variables

VariableEffect
RUST_LOGControl log verbosity (debug, trace, etc.)
NO_COLORDisable colored output

Filtering

Status: Current Last updated: 2026-06-15 12:55 EDT

The framework provides a unified filtering system shared across commands. Filters restrict which utterances, speakers, tiers, and words are processed. Which filters a given command exposes still varies (for example, dependent-tier selection currently lands on FREQ and CHAINS but not yet KWAL/COMBO); each filter page below notes its per-command coverage.

Multiple filters can be combined; they are applied as an AND (all must match for an utterance to be included).

flowchart TD
    utt["Each utterance"]
    speaker{"Speaker\nfilter?"}
    tier{"Tier\nfilter?"}
    word{"Word\nfilter?"}
    gem{"Gem\nfilter?"}
    range{"Range\nfilter?"}
    process["process_utterance()"]
    skip["Skip"]

    utt --> speaker
    speaker -->|pass| tier
    speaker -->|fail| skip
    tier -->|pass| word
    tier -->|fail| skip
    word -->|pass| gem
    word -->|fail| skip
    gem -->|pass| range
    gem -->|fail| skip
    range -->|pass| process
    range -->|fail| skip

Filter types

FilterFlagCLAN equivalentEffect
Speaker--speaker / --exclude-speaker+t* / -t*Include/exclude by speaker code
Tier--tier / --exclude-tier+t% / -t%Include/exclude dependent tiers
Word--include-word / --exclude-word+s / -sFilter by word content
Gem--gem / --exclude-gem+g / -gRestrict to gem segments
Range--range+zUtterance number range
ID--id-filter+t@ID=Filter by @ID header fields

Examples

# Child speaker only, within a gem
chatter-clan freq --speaker CHI --gem "story" file.cha

# All speakers except investigator, utterances 10-50
chatter-clan mlu --exclude-speaker INV --range 10-50 file.cha

# Only utterances containing "the" (KWAL's search is +s, which maps to --keyword)
chatter-clan kwal --keyword "the" file.cha

Speaker Filtering

Status: Current Last updated: 2026-05-11 18:58 EDT

Speaker filters restrict which speakers’ utterances are analyzed. This is one of the most frequently used filters, most CLAN analyses target a specific participant (e.g., the child in a child language study).

Include speakers

Analyze only specific speakers:

chatter-clan freq --speaker CHI file.cha
chatter-clan mlu --speaker CHI --speaker MOT file.cha

CLAN equivalent: +t*CHI, +t*CHI +t*MOT

Multiple --speaker flags use OR logic: utterances from any listed speaker are included.

Exclude speakers

Remove specific speakers from analysis:

chatter-clan freq --exclude-speaker INV file.cha

CLAN equivalent: -t*INV

@ID filtering

Filter speakers by metadata fields in the @ID header. The filter is pipe-delimited, in CHAT @ID column order:

lang|corpus|speaker|age|sex|group|ses|role|education|custom

Each field is either * (wildcard), empty (also wildcard), or a literal exact match. Trailing fields may be omitted entirely.

# All children (role = Target_Child, at position 8)
chatter-clan freq --id-filter "*|*|*|*|*|*|*|Target_Child" file.cha

# English-language speakers only
chatter-clan freq --id-filter "eng|" file.cha

# A specific speaker code (position 3)
chatter-clan freq --id-filter "*|*|CHI" file.cha

CLAN equivalent: +t@ID="*|*|*|*|*|*|*|Target_Child".

Authoritative parser: crates/talkbank-clan/src/framework/id_filter.rs. The language field is a comma-separated list in the underlying @ID; the filter matches if any language in the @ID matches the pattern.

Interaction with other filters

  • Speaker filtering is applied first, before range or word filters
  • Include and exclude can be combined; excludes are applied after includes
  • Speaker codes are case-sensitive and must match the @Participants header exactly (e.g., CHI, not chi)

Tier Filtering

Status: Current Last updated: 2026-06-15 12:54 EDT

Tier filters select which dependent tiers a command operates on, using CLAN’s +t%/-t% flag family. In legacy CLAN this is a shared option (the +t/-t handler in cutt.cpp; +t%X includes a dependent tier, -t%X excludes one), so a single mechanism covers two command styles:

  • Cluster-echo commands (KWAL, COMBO, GEM): +t%X adds dependent tier X to each echoed cluster; -t%X removes it. CLAN’s manual documents this directly for KWAL: the alias kwal +t* +t@ +t% -t%mor +d +f *.cha echoes every cluster but drops the %mor line (CLAN manual, “Using aliases”).
  • Analysis commands (FREQ, CHAINS): +t%X makes the analysis read tier X instead of the main tier (e.g. freq +t%mor counts morphemes).

CLAN semantics, source-grounded: the +t/-t handler routes %-prefixed arguments to maketierchoice(arg, sign, …) (OSX-CLAN/src/clan/cutt.cpp:9749-9758), and the run banner reports ONLY dependent tiers matching: … for +t% and ALL dependent tiers EXCEPT the ones matching: … for -t% (cutt.cpp:12173, cutt.cpp:12199).

chatter coverage

--tier / --exclude-tier (the chatter spelling of +t% / -t%, also reachable via the legacy +t%/-t% forms through the flag rewriter) are currently implemented on FREQ and CHAINS. The cluster-echo commands KWAL and COMBO accept the legacy rewrite target but do not yet expose the flag (it is “Rewriter only”, see the KWAL command page audit table), so dependent-tier display selection on KWAL/COMBO is a known parity gap rather than a finished feature. The runnable examples below therefore use FREQ.

Include a dependent tier

Make the analysis read only the named dependent tier:

chatter-clan freq --tier mor file.cha
chatter-clan freq +t%mor file.cha

CLAN equivalent: +t%mor. On FREQ this counts items on the %mor tier; on a cluster-echo command it would show only the %mor tier with each match.

Exclude a dependent tier

Drop a dependent tier:

chatter-clan freq --exclude-tier gra file.cha
chatter-clan freq -t%gra file.cha

CLAN equivalent: -t%gra.

Common dependent tiers

TierFull nameContent
morMorphologyPOS tags and lemmas: noun|dog-PL
graGrammarDependency relations: 1|3|NSUBJ
phoPhonologyPhonological transcription
floFluent outputSimplified main-tier text
codCodesResearcher-assigned codes
modModelTarget pronunciation
retRetraceCopy of main tier

Notes

  • Tier names are specified without the % prefix on the --tier / --exclude-tier form (mor, not %mor); the legacy +t%mor form keeps the %.
  • Selecting a tier for analysis (FREQ/CHAINS) changes what is counted; selecting a tier for display (KWAL/COMBO, once landed) changes what is echoed.
  • Speaker selection (*CHI:, *MOT:) uses the same +t flag with a * argument; see Speaker Filtering.

Word Filtering

Status: Current Last updated: 2026-06-15 12:31 EDT

Word filters restrict analysis to utterances containing (or not containing) specific words. The generic content filter is --include-word / --exclude-word (CLAN +s / -s), available across the search and frequency family.

Note the per-command split: KWAL and COMBO each have their own primary search, and for those commands CLAN’s +s maps to that search, not to the generic filter. KWAL’s +s is the required keyword (--keyword); COMBO’s +s is the required boolean search expression (--search). On those commands --include-word is still available as an additional content filter on top of the primary search.

Include words

Only process utterances containing a specific word:

chatter-clan freq --include-word "the" file.cha
chatter-clan freq --include-word "dog" --include-word "cat" file.cha

CLAN equivalent (FREQ): +s"the", +s"dog" +s"cat"

Multiple --include-word flags use OR logic by default: utterances containing any listed word are included.

The same --include-word filter works on KWAL and COMBO in addition to their required primary search, for example chatter-clan kwal --keyword "want" --include-word "the" file.cha.

Exclude words

Skip utterances containing specific words:

chatter-clan freq --exclude-word "um" --exclude-word "uh" file.cha

CLAN equivalent: -s"um" -s"uh"

Case sensitivity

By default, word matching is case-insensitive (the matches The, THE, the).

The CLAN +k flag (--plus-k after rewriting) toggles each command’s default case mode. FREQ and VOCD preserve case by default and fold under +k; KWAL, COMBO, FREQPOS, DIST, and MAXWD fold by default and preserve under +k. Other commands (MLU/MLT/WDLEN/WDSIZE/CHAINS/CODES) inherit +k from cutt.cpp::mainusage but it’s a semantic no-op since they don’t word-match. Per-command status lives in each command page under clan-reference/commands/. --case-sensitive remains a compatibility alias. See also flag-translation.md.

What counts as a “word”

Word matching uses the same countable-word logic as other commands:

  • Regular words and proper nouns match
  • Untranscribed markers (xxx, yyy, www) do not match
  • Zero words (0word) do not match
  • Fillers and fragments (&-um, &~frag) do not match
  • Events (&=laughs) do not match

Gem Filtering

Status: Current Gem filters restrict analysis to utterances within @Bg / @Eg (Begin Gem / End Gem) boundaries. Gems are used to mark segments of a transcript, for example, a story retelling, a conversation about a specific topic, or a test activity.

Include gems

Analyze only utterances within a labeled gem segment:

chatter-clan freq --gem "story" file.cha
chatter-clan mlu --gem "frog story" file.cha

CLAN equivalent: +g"story"

Exclude gems

Skip utterances within specific gem segments:

chatter-clan freq --exclude-gem "warmup" file.cha

CLAN equivalent: -g"warmup"

How gems work in CHAT files

Gem boundaries are marked with header lines:

@Bg:	story
*CHI:	once upon a time .
*CHI:	there was a frog .
@Eg:	story

Only utterances between matching @Bg/@Eg pairs with the specified label are included. Utterances outside all gem boundaries are excluded.

  • GEMLIST: list all gem segment labels in a file
  • freq --gem: frequency analysis restricted to gem segments (equivalent to legacy GEMFREQ)

Utterance Range Filtering

Status: Current Range filters restrict analysis to a numbered subset of utterances, useful for analyzing specific portions of a transcript without splitting the file.

Usage

chatter-clan freq --range 10-50 file.cha
chatter-clan mlu --range 1-100 file.cha

CLAN equivalent: +z10-50

Behavior

  • Utterance numbering starts at 1
  • Both endpoints are inclusive (e.g., --range 10-50 includes utterances 10, 11, …, 50)
  • Only main-tier utterances (*SPK: lines) are counted; headers, dependent tiers, and comments are not numbered
  • Range filtering is applied after speaker filtering, if you filter to --speaker CHI, utterance 1 is the first CHI utterance, not the first utterance in the file

Open-ended ranges

To analyze from a point to the end of the file, use a large upper bound:

chatter-clan freq --range 50-9999 file.cha

Combining with other filters

Range composites with all other filters:

# First 50 CHI utterances within a gem segment
chatter-clan mlu --speaker CHI --range 1-50 --gem "story" file.cha

Output Formats

Status: Current Last updated: 2026-05-21 15:35 EDT

Every analysis command produces a typed result that can be rendered in multiple formats.

Text (default)

Human-readable output, designed for terminal display:

chatter-clan freq file.cha

CLAN-compatible text

Legacy CLAN output format, used for parity testing. Activated internally by render_clan().

JSON

Structured output for programmatic consumption:

chatter-clan freq --format json file.cha

JSON output preserves all fields from the typed result struct, including metadata that text format may omit.

CSV

Tabular output for spreadsheet tools:

chatter-clan mlu --format csv file.cha

Transform commands: -o, --output

Transform commands (chstring, combtier, compound, dataclean, dates, delim, fixbullets, fixit, flo, gem, indent, lines, longtier, lowcase, makemod, ort, postmortem, quotes, repeat, retrace, roles, tierorder, trim) and format converters (chat2*, *2chat) accept a shared -o, --output <PATH> flag for choosing where the rewritten CHAT (or target-format) bytes go. The default is stdout.

chatter-clan delim file.cha                       # writes to stdout
chatter-clan delim file.cha -o file-fixed.cha     # writes to a file
chatter-clan delim file.cha --output file-fixed.cha

The --format flag does not apply to transform commands; they emit the full CHAT (or target-format) file, not analysis output.

Notes

  • Transform commands write modified CHAT files, not analysis output, --format flags don’t apply
  • Converters produce the target format (SRT, ELAN XML, etc.) and respect -o, --output

Pipelines and Scripting

Status: Current Last updated: 2026-05-11 18:58 EDT

JSON for Scripting

For programmatic consumption, use --format json and pipe to jq. The schemas are the typed result structs in crates/talkbank-clan/src/commands/<cmd>.rs (each implements Serialize).

# Total token count for the first speaker in a FREQ run
chatter-clan freq --format json file.cha | jq '.speakers[0].total_tokens'

# Get MLU value for CHI (assuming CHI is the only speaker after filtering)
chatter-clan mlu --speaker CHI --format json file.cha | jq '.speakers[0].mlu'

Batch Processing

Process many files and collect results:

# Frequency analysis across an entire corpus
chatter-clan freq --format csv corpus/ > results.csv

# Per-file MLU in JSON
for f in corpus/*.cha; do
    echo "=== $f ==="
    chatter-clan mlu --speaker CHI --format json "$f"
done

Combining with Other Tools

# Find files with low MLU
chatter-clan mlu --format json corpus/ | jq 'select(.speakers[].mlu < 2.0)'

# Top 10 most frequent words per speaker (FreqEntry.count is sorted desc by default)
chatter-clan freq --format json file.cha | jq '.speakers[].entries[0:10]'

Transform Chains

Transforms write the rewritten CHAT to stdout by default, or to a path you pass with --output. To chain them, either redirect each stage to a file and feed it to the next, or pass --output explicitly:

# Clean up a file: lowercase, then compute ages, explicit intermediate files
chatter-clan lowcase file.cha --output file.low.cha
chatter-clan dates   file.low.cha --output file.final.cha

# Or with shell redirection
chatter-clan lowcase file.cha > file.low.cha
chatter-clan dates   file.low.cha > file.final.cha

Transforms do not modify the input file in place; see crates/talkbank-clan/src/framework/transform.rs::run_transform.

Working with Directories

Status: Current Pass a directory path to process all .cha files recursively:

chatter-clan freq corpus/
chatter-clan mlu corpus/English/

Behavior

  • All .cha files under the directory are discovered and processed
  • Subdirectories are traversed recursively
  • Non-.cha files are silently ignored
  • Results are aggregated across all files (same as CLAN’s default behavior)

Per-file output

Some commands support --per-file mode to get separate results for each file:

chatter-clan mlu --per-file corpus/

Combining with filters

Directory processing composes with all filters:

# CHI utterances across an entire corpus
chatter-clan freq --speaker CHI corpus/

# First 100 utterances in each file
chatter-clan mlu --range 1-100 corpus/English/

JSON output for scripting

Combine directory processing with JSON output for batch analysis:

chatter-clan mlu --format json corpus/ > results.json

See Pipelines and Scripting for more advanced workflows.

CHAINS – Clause Chain Analysis

Status: Current Last updated: 2026-05-26 10:20 EDT

Purpose

Analyzes sequences of interactional codes on a single specified coding tier. In the legacy manual, CHAINS is described as tracking hand-entered codes on one coding tier, with %cod, %spa, and %sit given as examples, and with dependent-tier periods used to mark correspondence to [^c] clause units on the main tier.

In talkbank-clan, a “chain” is a run of consecutive utterances by the same speaker that all contain a given code item on the selected coding tier. When the code disappears or the speaker changes, the chain is flushed and its length is recorded.

Reports chain count, average/min/max length, and standard deviation per code and speaker.

See the CLAN manual for the original CHAINS command specification.

Usage

chatter-clan chains file.cha
chatter-clan chains --speaker CHI file.cha
chatter-clan chains --tier cod file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--tier <NAME>+t%X (rewriter target)Tier label to read codes from (default: cod)
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN chains flag. Sources:

  • OSX-CLAN/src/clan/chains.cpp: usage().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() CHAINS branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Chains plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

CHAINS is a required-flag refusal command in chatter, emits the exact CLAN refusal when +t%X (or --tier X) is absent.

CHAINS-specific +-flags (from chains.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+cS / +c@SClause-marker delimiter S (or markers in file @S),MissingClause-unit detection.
+dChange zeroes to spaces in output,MissingPer OSX-CLAN/src/clan/chains.cpp:1089, CLAN sets chains_onlydata = atoi(getfarg(...)) + 1 (range 0-1); +d → level 1. chatter has no --only-data flag. Per-CHAINS arm in clan_args.rs passes the token through so clap reports the literal +d argument rather than the misleading --display-mode rewrite.
+d1+d + display every input line in output,MissingSame onlydata level toggle as +d (CLAN: +d1 → level 2). chatter not implemented; passthrough arm.

Audit summary

BucketCount
Done6
Partial1
Rewriter only3
Missing7

Display Modes (+dN / --display-mode N), DRAFT, awaiting PI review

Status: drafted from CLAN manual; not yet implemented. Rewriter at crates/talkbank-clan/src/clan_args.rs:101 translates +dN → --display-mode N; no clap field consumes it today. Drafted from CLAN manual §7.1.2 (Unique Options, CHAINS) for PI review.

NCLAN behavior (verbatim from manual)
+d (no number)“Use this switch to change zeroes to spaces in the output.” Example: chains +d +t%spa chains.cha +s$nia:%
+d1“Works the same as +d, while also displaying every input line in the output.”

Open questions for PI review

  1. “Change zeroes to spaces” is a CLAN text-formatting artifact, columnar output where 0 marks absence. Does chatter’s typed output already render absence as empty/space? If so, --display-mode 0 may be a no-op in chatter and the flag should error rather than silently accept.
  2. +d1 “displays every input line”: this is a verbose-trace mode, not an output-shape change. Map to --include-input boolean instead of overloading --display-mode?

Output

Per code and speaker:

  • Number of separate chains
  • Average chain length
  • Standard deviation of chain lengths (sample, N-1)
  • Minimum chain length
  • Maximum chain length

Differences from CLAN

  • Manual intent: The legacy manual frames CHAINS as a coding-tier command, not a generic dependent-tier tokenizer.
  • Speaker-change detection: Flushes all open chains for the previous speaker, matching CLAN’s behavior of treating chains as speaker-scoped.
  • Coding-tier semantics: CHAINS operates on %cod-style coding items, not %gra.
  • Code extraction: For %cod, chains now read a clan-local semantic %cod item stream derived from the parsed AST rather than flattening the tier back to whitespace text. For other tiers passed via --tier, extraction remains content-token based.
  • Manual constraint not yet fully enforced: The manual examples all use coding tiers. Non-%cod --tier fallback still tokenizes tier text; this should eventually be restricted to tiers with explicit coding semantics.
  • Standard deviation: Uses the sample (N-1) formula rather than population.
  • Golden test parity: Verified against CLAN C binary output.

CHAT2ELAN – CHAT to ELAN XML Conversion

Status: Current Last updated: 2026-05-27 10:20 EDT

Purpose

Converts CHAT files into ELAN annotation format (.eaf). The output is a valid ELAN XML file with time-aligned tiers and annotations derived from CHAT main tiers and their timing bullets.

See the CLAN manual for the original CHAT2ELAN command documentation.

Usage

chatter-clan chat2elan file.cha
chatter-clan chat2elan --media-extension wav file.cha

CLAN Equivalence

CLAN commandRust equivalent
chat2elan +e.wav file.chachatter-clan chat2elan file.cha

Options

OptionCLAN FlagDescription
--media-extension <EXT>+e.EXTInclude a MEDIA_DESCRIPTOR element referencing a media file with the same basename and the given extension

Without --media-extension, the output omits media references.

CLAN +-flag coverage audit

CHAT2ELAN is a converter: input CHAT, output ELAN XML (.eaf). Sources: OSX-CLAN/src/clan/Chat2Elan.cpp::usage, crates/talkbank-clan/src/converters/chat2elan.rs.

CHAT2ELAN-specific +-flags (from Chat2Elan.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+eSMedia file name extension--media-extension <EXT>DoneCLAN: chat2elan.cpp:117 (case 'e'). Rewriter routes +eEXT → --media-extension EXT via per-chat2elan arm placed BEFORE the generic +e → --error arm (which is check-family-only but currently unscoped). Strips a leading dot if present: +e.wav and +ewav both produce --media-extension wav, because chatter’s --media-extension auto-prepends . whereas CLAN concatenates the user-provided suffix verbatim. Subprocess regression guard: legacy_chat2elan_e_routes_to_media_extension.

Audit summary: 1 Done, 0 Missing. Single-flag surface, mapped one-to-one.

Output

A standard-compliant EAF 3.0 XML file. Each CHAT speaker becomes an ELAN tier (using the full speaker code as tier ID). Utterances with timing bullets become time-aligned annotations. The time slot pool is derived from all utterance start/end timestamps.

Differences from CLAN

  • CLAN requires the +e flag to specify a media extension; the Rust version omits media references by default.
  • Uses typed AST traversal for utterance extraction rather than text parsing.
  • Generates standard-compliant EAF 3.0 XML.
  • Speaker codes are used directly as tier IDs (no truncation).

CHAT2PRAAT – CHAT to Praat TextGrid

Status: Current Last updated: 2026-05-22 13:30 EDT

Purpose

Converts CHAT files to Praat TextGrid format for acoustic/phonetic analysis. Each speaker becomes a separate interval tier, with timed utterances mapped to intervals.

This is the reverse of PRAAT2CHAT. Both conversions are implemented in the same module (praat2chat).

Usage

chatter-clan chat2praat file.cha
chatter-clan chat2praat file.cha -o output.TextGrid

CLAN +-flag coverage audit

CHAT2PRAAT is a converter: input CHAT, output Praat TextGrid. Sources: OSX-CLAN/src/clan/Chat2Praat.cpp::usage, crates/talkbank-clan/src/converters/chat2praat.rs.

CHAT2PRAAT-specific +-flags (from Chat2Praat.cpp::usage)

CLAN flagMeaningChatterStatus
+eSMedia file name extension,Missing

Audit summary: 1 Done (default conversion), 1 Missing. The +eS media-extension flag is a hint for TextGrid’s sound-association header; chatter omits this metadata today. Filed as a Phase 1.7 follow-up.

Behavior

  • Each speaker in the CHAT file becomes a separate interval tier
  • Only timed utterances (those with bullet timing) are included
  • Timing bullets are converted from milliseconds to seconds
  • Speaker codes become tier names
  • Utterance text is extracted with annotations stripped
  • If no timed utterances exist, an empty string is returned

Output format

Produces standard Praat TextGrid long format:

File type = "ooTextFile"
Object class = "TextGrid"

xmin = 0
xmax = 5.042652
tiers? <exists>
size = 2
item []:
    item [1]:
        class = "IntervalTier"
        name = "CHI"
        ...

Differences from CLAN

  • Uses the typed AST to extract timing and text, rather than string scanning
  • Bidirectional conversion in one module (CLAN has separate praat2chat and chat2praat binaries)
  • Deterministic speaker tier ordering via BTreeMap

CHAT2SRT – CHAT to Subtitle Conversion

Status: Current Last updated: 2026-05-27 10:28 EDT

Purpose

Converts CHAT files to subtitle format for captioned video. The legacy manual describes CHAT2SRT as converting a CHAT file to SRT for video captioning and then walks through a GUI workflow using external subtitle software.

This book focuses on the CLI semantics only: talkbank-clan converts timed CHAT utterances to SRT or WebVTT subtitle entries.

Usage

chatter-clan chat2srt input.cha

Output Formats

FormatFunctionTimestamp style
SRTchat_to_srt()HH:MM:SS,mmm
WebVTTchat_to_vtt()HH:MM:SS.mmm

Options

OptionDefaultDescription
(none)This converter operates on a parsed ChatFile and has no additional configuration options.

CLAN +-flag coverage audit

CHAT2SRT is a converter: input CHAT, output SRT or WebVTT. Sources: OSX-CLAN/src/clan/Chat2Srt.cpp::usage, crates/talkbank-clan/src/converters/chat2srt.rs (paired with chat2vtt.rs).

CHAT2SRT-specific +-flags (from Chat2Srt.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+dClean output without codes/replacements (default: keep all)(default in chatter)Partialchatter’s converter strips most CHAT annotations by default. The exact CLAN “everything” vs “clean” distinction is not user-toggleable.
+vCreate WebVTT instead of SRTchat2vtt subcommand (auto-switched)DoneCLAN: chat2srt.cpp:108 (case 'v'). Different shape: chatter splits SRT vs WebVTT into two subcommands, each with its own clap surface; CLAN unifies them with +v. The resolve_subcommand_alias pre-pass in clan_args.rs swaps the subcommand token (chat2srt → chat2vtt) and drops +v before the per-arg rewriter runs, so legacy chatter-clan chat2srt +v file.cha invocations work transparently. Subprocess regression guard: legacy_chat2srt_v_switches_to_chat2vtt.

Audit summary

BucketCount
Done1 (default + WebVTT split)
Partial1
Missing0

CHAT2SRT’s CLAN flag for VTT-vs-SRT is replaced by chatter’s two-subcommand split. +d clean-output toggle is a UI gap; chatter’s default is “clean” with no opt-out to “include everything.”

Input Format

Standard CHAT (.cha) files with timing bullets on utterances. Utterances without timing bullets are excluded from the output.

Output

Numbered subtitle blocks with timestamps derived from CHAT timing bullets and cleaned text content (no CHAT markers, annotations, or speaker codes).

Example SRT output:

1
00:00:01,000 --> 00:00:03,500
hello world

2
00:00:04,200 --> 00:00:06,800
how are you

Differences from CLAN

  • GUI material intentionally omitted here: The legacy manual’s Subtitle Writer walkthrough belongs in the TalkBank VS Code extension docs, not in this CLI command chapter.
  • Uses typed AST for subtitle text extraction
  • Produces valid, well-formed SRT/WebVTT output
  • Additionally supports WebVTT output format
  • Manual feature not yet mirrored: The legacy manual documents using +t%glo to caption from the gloss tier. This chapter should not imply that arbitrary dependent-tier caption sourcing is available unless explicitly implemented.

Reference

See the CLAN manual for the original CHAT2SRT command documentation.

CHAT2TEXT, CHAT to Plain Text

Status: Current Last updated: 2026-05-22 13:32 EDT

Purpose

Converts CHAT files into plain text lines suitable for downstream text analysis. The legacy manual describes CHAT2TEXT as converting a CHAT file to text lines for concordance programs such as AntConc, and says it is implemented as an alias of FLO with +cr +t*.

talkbank-clan implements the same broad intent directly by extracting plain spoken text from the parsed CHAT AST.

Usage

chatter-clan chat2text file.cha
chatter-clan chat2text --include-speaker file.cha

Options

OptionDescription
--include-speakerPrefix each line with speaker code (e.g., “CHI: hello world”)

CLAN +-flag coverage audit

CHAT2TEXT has no dedicated .cpp in CLAN’s source tree, the manual describes it as an alias for flo +cr +t*. chatter exposes it as a first-class converter with a chatter-only --include-speaker toggle (CLAN’s +cr strips speaker codes; chatter’s default also strips, with --include-speaker as the opt-in).

CLAN flagMeaningChatterStatus
(none; aliased to flo +cr +t*),default plain-text extractionDone

Audit summary: 1 Done, 0 Missing. Chatter’s --include-speaker is a UI nicety with no direct CLAN counterpart.

Output

Plain text with one utterance per line. All CHAT annotations are stripped:

  • Bracketed annotations ([/], [: replacement], [*])
  • Timing bullets
  • Terminators (., ?, !)
  • Fillers (&-um), fragments (&+fr), events (&=laughs)
  • Untranscribed markers (xxx, yyy, www)
  • Omitted words (0word)

Differences from CLAN

  • Manual intent: the CLAN manual does have a dedicated CHAT2TEXT section, and it describes the command as a FLO-based alias rather than as a separate semantic engine.
  • Uses AST-based content extraction for reliable annotation stripping.
  • Does not model the legacy implementation literally as flo +cr +t*; it performs the plain-text extraction directly.

CHAT2VTT – CHAT to WebVTT Subtitle Conversion

Status: Current Last updated: 2026-05-22 13:33 EDT

Purpose

Converts a CHAT file to WebVTT subtitle format for captioned video. WebVTT (.vtt) is the W3C-standard subtitle format used by HTML5 <track> elements; it is closely related to SRT but uses . instead of , as the millisecond separator and includes a WEBVTT header.

Internally, chat2vtt is a thin CLI surface over the same converter crate as chat2srt: both subcommands take a CHAT file with timing bullets and emit numbered subtitle blocks, just in different file formats. The shared infrastructure lives at crates/talkbank-clan/src/converters/chat2srt.rs (chat_to_vtt() for this subcommand, chat_to_srt() for SRT).

Usage

# Write WebVTT to stdout
chatter-clan chat2vtt input.cha

# Write to a file
chatter-clan chat2vtt input.cha -o input.vtt

Options

OptionDefaultDescription
-o, --output <PATH>stdoutDestination file. Omit to print to stdout.

The subcommand takes a single positional <PATH> argument (one CHAT file at a time). It does not accept directory inputs, file lists, or the CommonAnalysisArgs filtering flags (--speaker, --gem, etc.), WebVTT conversion is structural, not analytic.

CLAN +-flag coverage audit

CHAT2VTT does not exist as a separate CLAN command: CLAN’s WebVTT output is selected via chat2srt +v. chatter splits the two outputs into separate subcommands (chat2srt produces SRT, chat2vtt produces WebVTT). See CHAT2SRT for the shared audit.

Audit summary: chatter extension. No CLAN flag surface for this subcommand specifically.

Input Format

Standard CHAT (.cha) files with timing bullets (•start_end•) on utterances. Utterances without timing bullets are excluded from the output, since WebVTT requires every cue to carry a timestamp.

Output

Numbered subtitle cues with HH:MM:SS.mmm --> HH:MM:SS.mmm timestamps and cleaned text content (no CHAT markers, annotations, or speaker codes). The output begins with the WEBVTT header line that the WebVTT specification requires.

WEBVTT

1
00:00:01.000 --> 00:00:03.500
hello world

2
00:00:04.200 --> 00:00:06.800
how are you

Difference from chat2srt

The two converters share extraction logic and only differ in the output formatting layer:

SubcommandOutput formatTimestamp separatorHeader
chat2srtSRT (.srt), (e.g. 00:00:01,000)none
chat2vttWebVTT (.vtt). (e.g. 00:00:01.000)WEBVTT

For the rationale on which utterances are emitted vs skipped, the shape of cleaned text, and what’s intentionally not included from CLAN’s GUI-driven Subtitle Writer flow, see chat2srt. Everything documented there about extraction also applies here; only the serialization differs.

Reference

The CLAN manual section CHAT2SRT covers the original SRT-conversion workflow. WebVTT is an extension on the Rust side; the manual does not document a separate CHAT2VTT binary.

CHECK, CHAT File Validation

Status: Current Last modified: 2026-05-29 17:32 EDT

CHECK validates CHAT files for structural correctness, checking headers, tier formatting, bracket matching, bullet consistency, speaker declarations, and more.

Usage

chatter-clan check file.cha
chatter-clan check +c0 file.cha          # Full bullet check
chatter-clan check +e file.cha           # List all error numbers
chatter-clan check +e6 file.cha          # Only report error 6
chatter-clan check -e6 file.cha          # Exclude error 6
chatter-clan check +g2 file.cha          # Check CHI has Target_Child
chatter-clan check +g5 file.cha          # Check for unused speakers
chatter-clan check +u file.cha           # Check UD features on %mor

Options

CLAN flagModern flagDescription
+c0--bullets 0Full bullet consistency check
+c1--bullets 1Check for missing bullets only
+e--list-errorsList all 161 error numbers and exit
+eN--error NOnly report error number N (repeatable)
-eN--exclude-error NExclude error number N (repeatable)
+g1(no-op)Prosodic delimiters (always recognized)
+g2--check-targetVerify CHI has Target_Child role
+g3(partial)Word detail checks (via parser)
+g4--check-idCheck for missing @ID tiers (on by default)
+g5--check-unusedCheck for unused speakers
+u--check-udValidate UD features on %mor tier

CLAN +-flag coverage audit

CHECK is a validator: and the audit shape differs from every other command by design. Per the chatter-clan-check-is-exception memory rule (saved 2026-05-21):

chatter check deliberately improves on CLAN’s CHECK; track divergences as documented improvements, not regressions. Use CLAN check as a find-missing-rules oracle, not a byte-level reference.

The Options table above is therefore the authoritative mapping for chatter’s CHECK surface, not a parity scorecard. Where CLAN’s flag has a chatter equivalent, the row says so. Where CLAN’s behaviour is a documented improvement target (e.g. 161 named error codes vs CLAN’s smaller fixed set), chatter leads. Where chatter validates something CLAN does not (e.g. UD-grade %mor features, expansive header-coherence checks), those validations are chatter extensions with no CLAN counterpart.

Audit summary (CHECK is exempt from parity buckets)

CHECK is exempted from the “Done / Partial / Rewriter only / Missing” buckets used elsewhere in this catalog. The CLAN-bug divergence ledger (framework.md) is the canonical home for CHECK-specific divergences when chatter improves on the legacy behaviour.

The one CLAN +-flag explicitly not mapped here is +dN warning-suppression (see Display Modes section below), which is semantically distinct from FREQ/KWAL/COMBO’s +d output-format selector and would need its own warning-tagging infrastructure. CHECK has no local case 'd'; consumption is via the shared maingetflag path at OSX-CLAN/src/clan/cutt.cpp:9382 with the CHECK-specific per-program body at cutt.cpp:9422 (onlydata == 3 → puredata = 2; else puredata = 0), and an additional short-circuit at check.cpp:852 (check_adderror returns early when onlydata == 0 || 3, skipping the error). chatter’s per-CHECK passthrough arm in clan_args.rs keeps +d/+dN literal so clap names the actual flag rather than the catch-all’s misleading --display-mode rewrite.

Display Modes (+dN / --display-mode N), DRAFT, awaiting PI review

Status: drafted from CLAN manual; not yet implemented. Rewriter at crates/talkbank-clan/src/clan_args.rs:101 translates +dN → --display-mode N; no clap field consumes it today. Drafted from CLAN manual §7.3.5 (Unique Options, CHECK) for PI review. Note: CHECK’s +d is warning-suppression, not output formatting, semantically very different from FREQ/KWAL/COMBO’s +d.

NCLAN behavior (verbatim from manual)
+d (no number)“Attempts to suppress repeated warnings of the same type.”
+d1“Suppress ALL repeated warnings of the same type.”

Open questions for PI review

  1. CHECK’s +d shape is orthogonal to the other commands’ --display-mode. Mapping CHECK’s +d to --suppress-repeats (boolean) or --max-per-error N (numeric) would be more honest than overloading --display-mode.
  2. The main chatter validate command already exposes --max-errors N (stop after N errors total, across files). That’s different from CLAN’s “suppress repeats of the same type” semantics. Should --display-mode 1 for CHECK be a new flag, or a variant of --max-errors?
  3. Both +d and +d1 are about suppression, the manual text doesn’t distinguish their behaviors clearly. “Attempts to suppress” (+d) vs “Suppress ALL” (+d1), is the former rate-limited or heuristic? PI input needed on what CLAN actually does at runtime.

Output Format

CHECK output matches CLAN’s format:

*** File "sample.cha": line 12.
*CHI:	doggy wanna play .
[E501] Illegal word character in 'wanna' (47)

Each error shows the file path and line number, the offending tier text, and the error message with CHECK’s numbered error code in parentheses.

Errors that don’t map to a CHECK number show our internal code in brackets instead:

*** File "sample.cha": line 5.
@Participants:	CHI Child
Missing role for CHI, expected format: CODE Name Role [E312]

CHECK vs chatter validate

See CHECK vs chatter validate for a detailed comparison of these two validation tools.

Differences from CLAN

  • Parsing: Uses tree-sitter grammar instead of CLAN’s character-by-character parser. More rigorous and consistent; catches structural errors that CHECK sometimes misses.
  • Error numbering: CLAN CHECK uses flat numbers 1-161. We map our typed error codes to CHECK numbers where correspondence exists; unmapped errors get number 0.
  • Two-pass vs single-pass: CLAN runs check_OverAll then check_CheckRest. Our parser combines both into a single streaming parse+validate pipeline.
  • depfile.cut: CLAN reads depfile.cut for tier/code templates. We validate against the CHAT specification directly.
  • Bug fixes: Several CHECK errors in the original are unreachable or duplicate (e.g., errors 51, 96 are commented out). We skip those.
  • +g1: Always a no-op, our parser recognizes prosodic delimiters by default.
  • +g3: Partially implemented through existing word validation.

CHIP — Child Language Interaction Profile

Status: implementation resumed; CLAN parity is not verified Last updated: 2026-10-31

CHIP scores child/adult and self-repetition interactions over a rolling utterance window. The implementation is in crates/talkbank-clan/src/commands/chip/; its inputs and options are wired through the talkbank-clan service and chatter-clan CLI.

Options

CLAN optionMeaningStatus
+bSAssign speaker S the adult roleImplemented
+cSAssign speaker S the child roleImplemented
+gInclude substitution-class scoringImplemented
+kFold case for word-stem comparisons (default preserves case)Implemented
-n[b|c|s]Disable adult/child, child/adult, or self scoringImplemented
+qNSet rolling-window size (2–7)Implemented
+wNSet minimum source-utterance word countImplemented
+xNSet minimum repetition indexImplemented
-t%morScore words aligned with the %mor tierImplemented
-hFILEExclude words listed in a filePartial; exact and * wildcard patterns
+dNSelect CLAN display modeNot implemented

The audit rows below track option implementation separately from golden evidence. CLAN’s option definitions are in OSX-CLAN/src/clan/chip.cpp:94-103, 1340-1401.

CLAN flagMeaningChatterStatusNotes
+bSAssign adult speaker(s)--adult CODEDoneNo flag-specific golden yet
+cSAssign child speaker(s)--child CODEDoneNo flag-specific golden yet
+gEnable substitution-class scoring--substitutionDoneNo flag-specific golden yet
+kFold case when comparing stems; default preserves case--plus-kDoneCommand-specific polarity; no flag-specific golden yet
-nb / -nc / -nsDisable adult, child, or self scoring--disable-scoring b/c/sDoneNo flag-specific golden yet
+qNSet utterance window (2–7)--window NDoneNo flag-specific golden yet
+wNSet minimum source word count--min-words NDoneNo flag-specific golden yet
+xNSet minimum repetition index--min-index NDoneNo flag-specific golden yet
-t%morUse main-tier words instead of %mor--main-tierDoneNo flag-specific golden yet
-hFILEExclude words matching patterns in a file--exclusion-list FILEPartialExact and * patterns match either paired surface or %mor form; unsupported selectors are rejected
+dNSelect display mode—MissingNo CHIP display-mode consumer

Unassigned speakers are not presumed to be adults or children. Conflicting speaker-role assignments, invalid window sizes, and incompatible scoring options are rejected during request construction.

The default word source is %mor. Chatter v0.33.0 provides UD morphology, not legacy CLAN morphology. CHIP uses typed morphology values and checks main-tier/%mor alignment; a mismatch rejects the file rather than producing fabricated scores. -t%mor selects main-tier words instead. Main-tier words are treated as opaque lexical items, not parsed for morphology-like strings. The default preserves stem case; +k folds only the typed comparison key. Original stem spelling remains available for generated CHIP codes. -hFILE currently supports exact words and * wildcards only. In %mor mode it excludes a paired word when either its surface form or joined morphology stem matches; substitution mode removes all clitics of that word. Main-tier-only mode does not apply the merged-tier exclusion rule. Unsupported selector syntax is rejected rather than approximated.

Scoring and output

For each utterance, CHIP considers the nearest prior qualifying utterance from the opposite speaker role and the nearest qualifying utterance by the same speaker within the configured window. It does not limit comparisons to adjacent utterances. Default mode reports the base measure matrix; substitution mode adds substitution-class rows. Files with no scorable utterances do not receive zero-filled matrices.

The transcript echo retains main tiers and %mor tiers, then appends the generated CHIP tiers. Other dependent tiers are not echoed.

Parity status

This implementation has focused unit tests, but no current CHIP-specific golden covers the newly implemented options. The existing CHIP_MOR_GRA golden covers only bare invocation (crates/talkbank-clan/tests/clan_golden/golden_parity.rs:876-884), so it does not establish option parity. In particular, -hFILE supports only the documented subset above and +dN remains unsupported. Do not treat implementation coverage or unit tests as evidence of full CLAN parity. See book/src/divergences/per-command.md for the command-level status.

CHSTRING – String Replacement Using a Changes File

Status: Current Last updated: 2026-05-27 10:06 EDT

Purpose

Reimplements CLAN’s chstring command, which reads a changes file containing find/replace pairs (alternating lines) and applies text substitutions to main-tier words. Replacements are applied to all word nodes, including words inside annotated groups, replacement forms, and bracketed groups.

See the CLAN manual for the original command documentation.

Usage

chatter-clan chstring --changes changes.cut file.cha

Options

OptionTypeDefaultDescription
-c, --changespath(required)Path to the changes file containing find/replace pairs
-o, --outputpathstdoutOutput CHAT file path

CLAN +-flag coverage audit

CHSTRING is a transform: it mutates CHAT input and writes CHAT output. It does not emit a banner and does not share CommonAnalysisArgs (no speaker/role/gem/range filters apply). The flag set is entirely command-specific.

Sources: OSX-CLAN/src/clan/chstring.cpp::usage, crates/talkbank-clan/src/transforms/chstring.rs, crates/talkbank-cli/src/cli/args/clan_commands.rs::Chstring.

(Status legend: same as FREQ.)

CHSTRING-specific +-flags (from chstring.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+bWork only on text right of the colon (CHAT format)(default)DoneCLAN: chstring.cpp:1120 (case 'b': lineonly = TRUE; no_arg_option(f)). chatter’s chstring already mutates only main-tier word content (never speaker codes or dependent-tier text), so +b is semantically a no-op. Per-CHSTRING rewriter arm in clan_args.rs consumes-and-drops +b so it doesn’t fall through to the positional <PATH> slot.
+cF / -cDictionary file path / do not change inside [...] codes--changes <PATH> (file form only)Partialchatter requires the path explicitly (no changes.cut-in-cwd default). The -c inside-codes guard is implicit, chatter’s AST-based replacement only touches word leaves, never code-bracket content.
+dDo not re-wrap tiers,MissingBare-only per OSX-CLAN/src/clan/chstring.cpp:1087 (NO_CHANGE = TRUE + no_arg_option(f)). chatter never wraps on output, so semantically a no-op. Per-CHSTRING rewriter arm in clan_args.rs passes the token through so clap reports the literal +d argument rather than the misleading --display-mode rewrite.
+lWork only on codes left of colon (speaker tag),Missing
+lxDo not show the list of changes(default)DoneCLAN: chstring.cpp:1108-1111 (case 'l': if (*f == 'x') DispChanges = FALSE). chatter never prints a changes-list (silent by design), so +lx is semantically a no-op. Per-CHSTRING rewriter arm in clan_args.rs consumes-and-drops the specific lx form so it doesn’t fall through to the positional <PATH> slot. Bare +l (headeronly = TRUE) is genuinely unimplemented and falls through to clap.
+qClean up tiers (add tabs after colons, remove blank spaces),MissingTier-cleanup pass.
+q1Clean up tiers for CORELEX,Missing
+sS SInline find/replace pair,MissingAll replacements must come via --changes.
-wString-oriented search and replacement(default)DoneCLAN: chstring.cpp:1145-1147 (case 'w': if (*f == EOS) stringOriented = 1). chatter’s word-leaf replacement is already string-oriented by default, so -w is semantically a no-op. Per-CHSTRING rewriter arm in clan_args.rs consumes-and-drops bare -w so it doesn’t fall through to clap as an unknown short flag. CLAN’s -w1 (stringOriented = 2) is not documented in this audit and is left to fall through.
+xInterpret *, _, \ as literal characters,Missingchatter’s matcher does not yet expose wildcard-vs-literal switching.

Audit summary

BucketCount
Done3
Partial1
Missing6

CHSTRING is intentionally a thin transform in chatter, the typed-AST design eliminates several CLAN flags by construction (+b, -c inside-codes guard, +lx). The remaining gaps are mostly orthogonal niceties (+q tier-cleanup, +sS inline pair, +x literal-character mode); none change correctness of the default file → file transform.

Changes File Format

The changes file contains alternating lines of find and replace strings:

find_text1
replace_text1
find_text2
replace_text2

The file must have an even number of non-empty lines. CLAN looks for changes.cut in the current directory by default; chatter-clan chstring requires the path to be passed explicitly via --changes.

Behavior

For each utterance in the file, the transform walks all word nodes on the main tier – including words inside annotated groups, replacement forms, and bracketed groups – and applies find/replace substitutions from the changes file.

Differences from CLAN

  • Operates on the parsed AST rather than raw text, ensuring structural integrity of the CHAT file after substitution.
  • Does not support CLAN’s regex-based pattern matching in the changes file.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).
  • Golden test parity: Verified against CLAN C binary output.

CODES – Code Frequency Table

Status: Current Last updated: 2026-05-22 09:46 EDT

Purpose

Tabulates the frequency and distribution of coding annotations found on %cod: dependent tiers, organized by speaker. This is useful for analyzing hand-coded behavioral or discourse annotations attached to transcripts.

Codes on %cod: tiers typically use colon-separated hierarchical structure (e.g., AC:DI:PP), but this implementation treats each whitespace-delimited token as a single code string without parsing the internal hierarchy.

The CLAN manual does not appear to contain a standalone CODES section. The closest direct evidence is the CHAINS section, which documents coding tiers and the codes.ord file used to order $-prefixed codes.

Usage

chatter-clan codes file.cha
chatter-clan codes --speaker CHI file.cha
chatter-clan codes --format json file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--max-depth <N>,Maximum depth of code parsing (chatter extension)
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

CODES has no command-specific +-flags in CLAN’s usage() (its getflag() is a default-only delegate to maingetflag). The entire flag surface is the inherited general set; chatter’s --max-depth is a chatter extension with no CLAN analog.

Inherited general flags: same as FREQ. Audit summary: 6 Done / 1 Partial / 4 Rewriter only / 3 Missing.

Output

Per-speaker frequency tables listing each code and its count, plus a per-speaker total and a grand total across all speakers.

Differences from CLAN

  • Manual coverage gap: the CLAN manual has no standalone CODES section, so this chapter is based on implemented behavior, golden tests, and nearby coding-tier documentation such as CHAINS.
  • Code extraction: Codes are extracted from a clan-local semantic %cod layer built from the parsed AST, not from raw line text.
  • Selector handling: %cod extraction preserves optional selectors like <w4> or <w4-5> as item scope rather than counting them as standalone codes.
  • Hierarchy handling: Each whitespace-delimited token is treated as a single code string; colon-separated hierarchy is preserved but not parsed into sublevels.
  • Output formats: Supports text, JSON, and CSV formats (CLAN produces text only).
  • Deterministic ordering: BTreeMap ordering ensures deterministic output across runs.
  • Golden test parity: Verified against CLAN C binary output.

COMBO – Boolean Keyword Search

Status: Current Last updated: 2026-05-27 10:36 EDT

Purpose

Searches for utterances matching boolean combinations of keywords. Supports AND (+) and OR (,) logic with case-insensitive substring matching. This is the primary search tool for finding utterances containing specific words or word combinations.

See the CLAN manual for the original COMBO command specification.

Usage

chatter-clan combo -S "want+cookie" file.cha
chatter-clan combo -S "want,milk" file.cha
chatter-clan combo -S "want+cookie" --speaker CHI file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
-S, --search <EXPR>+s"EXPR"Search expression (required, repeatable; multiple --search flags combined with OR)
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN combo flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/combo.cpp: usage() and getflag().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() COMBO branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Combo plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

COMBO-specific +-flags (from combo.cpp::getflag)

CLAN flagMeaningChatterStatusNotes
+bNSearch an N number-cluster unit,MissingMulti-utterance match.
+g1String-oriented search on the whole tier (default: word-oriented),Missingchatter does not yet implement string-oriented whole-tier search. Per-COMBO rewriter arm in clan_args.rs returns None so the literal +g1 token passes through to clap (which rejects it) rather than silently mis-routing to --gem 1 via the generic +g → rewrite_gem arm.
+g2String-oriented search on a single word,Missingchatter does not yet implement string-oriented single-word search. Same passthrough pattern as +g1.
+g3Find only the first match per utterance--first-match-onlyDoneLanded 2026-05-22. When set, the per-expression matcher short-circuits after the first hit per utterance, expr_hits records only the first matching expression. Default behaviour reports every matching expression.
+g4Exclude utterance delimiters from the search(no-op accept)DoneLanded 2026-05-23. chatter’s COMBO calls countable_words on the main tier, which iterates UtteranceContent::Word/AnnotatedWord/ReplacedWord (and recursively into groups) but never reaches Terminator, terminators live at a separate AST level. So +g4’s effect (exclude delimiters) is the chatter default; the rewriter consumes the flag, clap never sees it. Without the arm, +g4 would fall through to the generic gem-segment branch and mis-route to --gem 4. Pinned by combo_g4_is_silently_consumed_as_noop.
+g5Use ^ as AND operator instead of “followed-by”(no-op accept)DoneLanded 2026-05-22. chatter’s combo already uses + as AND (matching +g5’s semantic), so +g5 is consumed by the rewriter as a no-op; no clap field is needed; the flag is silently dropped.
+g6Include the tier’s code name in the search,Missingchatter’s search does not include the tier code name. Same passthrough pattern as +g1/+g2.
+g7Do not count duplicate matches--dedupe-matchesDoneLanded 2026-05-22. Repeated word forms within a single utterance contribute at most one entry to each expression’s matched_words; first-encounter order preserved. Mainly affects OR expressions (cookie,milk) over utterances with repeated tokens.
+sS / -sSPattern (required), output tiers matching / not matching-S / --search plus --exclude-searchDoneBoth polarities mapped 2026-05-22. The rewriter routes +sS → --search S and -sS → --exclude-search S for COMBO specifically (other commands keep the per-word +s/-s semantic). Utterances matching any --exclude-search expression are dropped even if they match an --search expression.
+s@F / -s@FLoad search expressions from file F (one per line)--search-file / --exclude-search-fileDoneLanded 2026-05-22. Each surviving line is parsed by SearchExpr::parse, so AND (+) and OR (,) operators work per line, just like inline --search. File format matches cutt.cpp::rdexclf: blank lines, # -comments, ;%* -annotation lines skipped; UTF-8 BOM stripped. Repeatable. Pinned by combo_search_at_sigil_routes_to_search_file and combo_exclude_search_at_sigil_routes_to_exclude_search_file in clan_args.rs.
+dvDisplay all parsed individual parts of the search pattern,MissingSearch-debug output.
+d, +d1..+d5Display modes (CHAT, line numbers, file names, matched-only, etc.),MissingFull local handler at OSX-CLAN/src/clan/combo.cpp:2858: +dv → search-debug echo (separate +dv row above); +d7 → linkDep2Other cross-tier linkage; +d8 → onlydata = 9 override; +d/+d0..+d6 → onlydata = atoi+1 with +d2 (onlydata==3) also resetting puredata = 0. Per-COMBO passthrough arm lands the literal-flag error rather than the misleading --display-mode rewrite.

General +-flags COMBO inherits (from cutt.cpp::mainusage)

CLAN flagMeaningChatterStatusNotes
+t*X / -t*XInclude/exclude speaker--speaker / --exclude-speakerDone+tX accepted post-2026-05-21.
+t%X / -t%XInclude/exclude dependent tier--tier / --exclude-tier (rewriter target)Rewriter only
+t@ID="..."Filter by @ID pattern--id-filterDone
+gXGem filter--gemDoneDistinct from +g1..+g7 (no S suffix).
+zN-MUtterance range--rangeDone
+rNRetrace / clitic / prosodic controls--include-retracings (+r6)Partial
+uCombine across files(default)Done
+reRecurse(default)Done
+pSWord delimiter,Missing
+kCase-sensitive--case-sensitiveDoneLanded 2026-05-23. Reads CommonAnalysisArgs::case_sensitive. Two-layer fix: SearchExpr::parse_with_case preserves case in the stored terms (default parse() lowercases), and process_utterance populates words via cleaned_text() instead of NormalizedWord::from_word. Both sides must agree, so ComboConfig::case_sensitive is the single switch threaded into both. Pinned by combo_case_sensitive_uppercase_keyword_misses_lowercase_word and combo_case_sensitive_matches_when_case_aligned.
+wN / -wNContext window--context-after N / --context-before NDoneLanded 2026-05-23. Same shape as KWAL: ComboState carries a VecDeque ring buffer for pre-context plus an awaiting_after Vec for post-context. process_utterance interleaves the bookkeeping with match-detection. Exclude (-sS) utterances still feed the windows (they count as non-matches), so context bookkeeping is correct around excluded utterances. Pinned by combo_context_after_captures_post_match_lines, combo_context_before_captures_pre_match_lines, combo_default_no_context_window.
+f / +fEXTOutput to file--output-ext (rewriter target)Rewriter onlyPhase 1.1.

Audit summary

BucketCount
Done13
Partial2
Rewriter only6
Missing8

COMBO has the second-largest “Rewriter only” bucket after KWAL, driven by the same +dN display-mode story. The COMBO-specific +g1..+g7 search-mode switches are also load-bearing: they each change the matching semantic, and a researcher pasting combo +g1 +s"want milk" file.cha into chatter today gets chatter’s word-oriented match (no analog for +g1).

Search Syntax

  • + between terms means AND (all terms must be present in the utterance)
  • , between terms means OR (at least one term must be present)
  • Terms are case-insensitive substring matches against countable words
  • Multiple --search flags are combined with OR (any expression matching counts)
  • AND takes precedence if both + and , appear in one expression

CLAN Equivalence

CLAN commandRust equivalent
combo +s"want^cookie" file.chachatter-clan combo file.cha -S "want+cookie"
combo +s"want|milk" file.chachatter-clan combo file.cha -S "want,milk"
combo +s"want^cookie" +t*CHI file.chachatter-clan combo file.cha -S "want+cookie" --speaker CHI

Display Modes (+dN / --display-mode N), DRAFT, awaiting PI review

Status: drafted from CLAN manual; not yet implemented. Rewriter at crates/talkbank-clan/src/clan_args.rs:101 translates +dN → --display-mode N; no clap field consumes it today. Drafted from CLAN manual §7.7.10 (Unique Options, COMBO) for PI review.

NCLAN behavior (verbatim from manual)
+d (no number)“Normally, combo outputs the location of the tier where the match occurs. When the +d switch is turned on you can output only each matched sentence in a simple legal chat format.”
+d1“Outputs legal chat format along with line numbers and file names.”
+d2“Outputs files names once per file only.”
+d3“Outputs legal chat format, but with only the actual words matched by the search string, along with @Comment headers that are ignored by other programs.”
+d4“Use of the +d4 switch was described in the previous section.” (Manual cross-reference; resolution pending.)
+d7“Search for words linked between two tiers.”

Open questions for PI review

  1. +d/+d1/+d2 parallel KWAL’s +d/+d1/+d2 almost exactly. Worth defining a shared --display-mode enum across search-style commands (KWAL + COMBO) with the same variant names?
  2. +d3 “matched words plus @Comment headers” is COMBO-specific. Probably a separate enum variant.
  3. +d4: manual cross-references the “previous section”. This needs PI clarification, the immediately-previous section is general COMBO description, not a +d-table.
  4. +d7 (cross-tier linkage) overlaps with FREQ +d7. If both commands’ +d7 is “compare two tiers”, the enum variant name should match.

Output

Each matching utterance with:

  • Source filename
  • Speaker code
  • Full utterance text (CHAT format)
  • Summary counts of matching vs. total utterances

Differences from CLAN

  • Operator syntax: CLAN uses ^ for AND and \| for OR; this implementation uses + and , respectively for shell-friendliness.

COMBTIER – Combine Duplicate Dependent Tiers

Status: Current Last updated: 2026-05-26 09:15 EDT

Purpose

Combines duplicate dependent tiers within an utterance. The legacy manual describes COMBTIER narrowly: it corrects the case where transcribers create several %com lines, combining two %com lines into one by removing the second header and moving its material onto the first %com line.

talkbank-clan generalizes that behavior to any selected dependent-tier label, while preserving the underlying tier variant whenever the selected tier has a supported AST model.

This is useful for cleaning up files where duplicate tiers were introduced during manual editing or automated annotation.

Usage

chatter-clan combtier --tier com file.cha

Options

OptionTypeDefaultDescription
--tierstring(required)The tier label to combine (e.g., com for %com:, spa for %spa:)
--separatorstring" "Separator between combined tier contents

CLAN +-flag coverage audit

COMBTIER is a transform. Sources: OSX-CLAN/src/clan/combtier.cpp::usage, crates/talkbank-clan/src/transforms/combtier.rs.

COMBTIER-specific +-flags (from combtier.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+tSTier to combine (required)--tier <NAME> (required; rewriter intercept)DoneSame required-flag refusal shape, CLAN exits with “Please specify tier to combine with +t option.” Rewriter routes both +tcom (bare prefix) and +t%com (percent prefix) to --tier com via a per-Combtier intercept in clan_args.rs (combtier overrides the analysis-command convention where +tS means “speaker filter”).
--separator (chatter extension)Separator between combined contents--separatorChatter-onlyNo CLAN analog, CLAN’s default is a space, hard-coded.

Audit summary

BucketCount
Done1
Chatter extension1
Missing0

COMBTIER’s surface is byte-parity complete. --separator is a chatter convenience.

Behavior

For each utterance, the transform finds all dependent tiers matching the specified label. If two or more matching tiers exist, their text content is concatenated using the configured separator and the result replaces the first occurrence. All subsequent duplicates are removed.

Utterances with zero or one matching tier are left unchanged.

Differences from CLAN

  • Manual intent is narrower: the legacy manual only documents %com combination explicitly. talkbank-clan supports other selected tier labels too.
  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).
  • Tier-kind preservation: Combining bullet/text dependent tiers such as %cod: and %com: preserves their actual tier variants instead of degrading them to user-defined tiers.

COMPLEXITY, Syntactic Complexity Ratio

Status: Current Last updated: 2026-05-22 09:47 EDT

Computes syntactic complexity by counting subordinating dependency relations in the %gra tier.

Usage

chatter-clan complexity file.cha
chatter-clan complexity corpus/ --speaker PAR
chatter-clan complexity file.cha --format json

What It Measures

COMPLEXITY reads the %gra dependency tier and counts clause-embedding relations that indicate syntactic subordination. The complexity ratio is the number of subordinating relations divided by total tokens (non-punctuation).

UD Relations (auto-detected)

Per crates/talkbank-clan/src/commands/complexity.rs:10:

RelationDescription
CSUBJClausal subject
CCOMPClausal complement
XCOMPOpen clausal complement
ACLAdnominal clause
ADVCLAdverbial clause modifier
APPOSApposition
EXPLExpletive

Legacy CLAN Relations (auto-detected)

RelationDescription
CSUBJClausal subject
COMPComplement
CPREDClausal predicate
CPOBJClausal object of preposition
COBJClausal object
CJCTClausal adjunct
XJCTNon-finite clausal adjunct
NJCTNominal adjunct
CMODClausal modifier
XMODNon-finite clausal modifier

Output

Per speaker:

  • Count of each subordinating relation
  • Tokens: total matched complexity relations
  • TotalTokens: all non-PUNCT tokens
  • Ratio: Tokens / TotalTokens

Requirements

Requires a %gra dependent tier. Utterances without %gra are skipped.

CLAN +-flag coverage audit

COMPLEXITY has no command-specific +-flags in CLAN’s usage(), the entire flag surface is the inherited general set, except that COMPLEXITY’s getflag() has special handling for +s patterns containing bracket-prefixed postcodes ([+ ...] / [~+ ...] / [+ +...]).

Inherited general flags: same as FREQ. chatter’s Complexity clap struct uses the standard CommonAnalysisArgs. Audit summary: 6 Done / 1 Partial / 4 Rewriter only / 3 Missing.

Differences from CLAN

  • Auto-detects UD vs legacy relation names (CLAN requires compile-time config)
  • Uses typed AST GraTier with GrammaticalRelation entries
  • Supports JSON and CSV output
  • Sub-relations (e.g., CSUBJ:pass) are properly matched to their base relation

COMPOUND – Normalize Compound Word Formatting

Status: Current Last updated: 2026-05-22 12:55 EDT

Purpose

Reimplements CLAN’s COMPOUND command, which normalizes compound word notation in CHAT files. In CHAT, compound words are joined with + (e.g., ice+cream). This command converts dash-joined compounds to the canonical plus notation.

Usage

chatter-clan compound file.cha

Options

COMPOUND has no command-specific flags, only the input path positional and the optional shared -o/--output (default: stdout). The dash→plus normalization is unconditional: there is no --dash-to-plus switch in the current CLI.

CLAN +-flag coverage audit

COMPOUND is a transform. CLAN’s compound.cpp::usage is an empty stub (void usage() {}), and the command-specific getflag is #pragma unused (f, f1, i), i.e. CLAN itself exposes no +-flags for this command. Surface byte-parity is trivially complete.

CLAN flagMeaningChatterStatus
(none),default transformDone

Audit summary

BucketCount
Done1
Missing0

Behavior

The transform walks all main-tier word nodes and converts dash-joined compounds to plus notation (e.g., ice-cream becomes ice+cream).

Operations performed:

  • Normalize dash-joined compounds to plus notation: ice-cream -> ice+cream
  • Preserves filler prefixes (&-uh) and omission prefixes (0word)
  • Only converts when all parts are purely alphabetic

The transform recurses into annotated words, replacement forms, groups, and annotated groups.

Differences from CLAN

  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).

COOCCUR, Word Co-occurrence (Bigram) Counting

Status: Current Last updated: 2026-05-26 08:47 EDT

Purpose

Counts adjacent word pairs (bigrams) across utterances. For each utterance, every pair of consecutive countable words is recorded as a directed bigram. Pairs are directional: (“put”, “the”) and (“the”, “put”) are counted separately.

COOCCUR is part of the FREQ family of commands and is useful for studying word collocations and sequential patterns in speech.

Usage

chatter-clan cooccur file.cha
chatter-clan cooccur file.cha --speaker CHI

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN cooccur flag. Sources:

  • OSX-CLAN/src/clan/cooccur.cpp: usage().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() COOCCUR branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Cooccur plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

COOCCUR-specific +-flags (from cooccur.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+b / -bMatch +s words only at beginning / end of cluster,MissingBoundary-sensitive matching.
+nNCluster size of N words (default 2)--cluster-size NDoneLanded 2026-05-23. Rewriter +nN → --cluster-size N. CooccurConfig gains cluster_size: u8 (default 2). WordPair generalized to WordCluster(Vec<NormalizedWord>); PairDisplay flattened to displays: Vec<String>; CooccurPair JSON shape replaced with CooccurCluster { words, displays, count }. process_utterance uses windows(cluster_size) instead of windows(2); utterances shorter than N produce no clusters. Pinned by cooccur_cluster_size_three_emits_trigrams, cooccur_cluster_size_larger_than_utterance_is_skipped, and the rewriter test cooccur_cluster_size. End-to-end smoke verified for N=2/3/4. JSON schema breaking change: pairs/unique_pairs/total_pair_instances renamed to clusters/unique_clusters/total_cluster_instances; per-row fields word1/word2/display1/display2 collapsed into words: Vec<String> and displays: Vec<String>.
+oSort output by descending frequency(default; no-op rewriter arm)Done (no-op per CLAN)CLAN’s cooccur.cpp toggles isSort = TRUE, switching to a BST whose larger num_occ goes left invariant makes in-order traversal emit clusters by descending count. chatter’s finalize step at commands/cooccur.rs:292 already sorts by count descending unconditionally, so the flag is no-op on the chatter side. Rewriter drops the token (clan_args.rs).
+dStrip frequency counts from output--no-frequency-countsDoneRewriter intercepts bare +d.

Audit summary

BucketCount
Done8
Partial1
Rewriter only3
Missing3

COOCCUR’s largest practical gap is +nN: chatter is fixed-bigram while CLAN allows arbitrary N-gram clusters. A --cluster-size N field would close this.

Display Modes (+d)

Bare +d (no following digits) is intercepted by the rewriter and mapped to --no-frequency-counts. The CLAN manual §7.8.1 (Unique Options, COOCUR) describes it as: “Strip the numbers from the output data that indicate how often a certain cluster occurred.” The chatter implementation drops the leading count column from CLAN-format output and is captured in CooccurConfig::no_frequency_counts.

No +d1/+d2/… forms are documented for COOCUR.

Output

  • Table of adjacent word pairs with co-occurrence counts
  • Default sort: by frequency descending, then alphabetically
  • CLAN output: sorted alphabetically by pair display form
  • Summary: unique pair count, total pair instances, total utterances

Differences from CLAN

  • Word identification uses AST-based is_countable_word() instead of CLAN’s string-prefix matching
  • Bigram extraction operates on parsed AST content rather than raw text
  • Output supports text, JSON, and CSV formats (CLAN produces text only)
  • Deterministic output ordering via sorted collections
  • Golden test parity: Verified against CLAN C binary output

CORELEX, Core Vocabulary

Status: Current Last updated: 2026-05-22 09:47 EDT

Purpose

Identifies “core” vocabulary items that appear above a frequency threshold. Core vocabulary analysis is used in clinical assessment to evaluate whether a child’s lexicon includes expected high-frequency words.

Usage

chatter-clan corelex file.cha
chatter-clan corelex --speaker CHI file.cha
chatter-clan corelex --threshold 5 file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--threshold <N>,Minimum frequency for core classification (default: 3), chatter extension
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

CORELEX-specific +-flags (from corelex.cpp::usage)

CLAN flagMeaningChatterStatusNotes
-gDo not look for GEMs,MissingDisables gem-filtering.
+lFSpecify words group name F (with .cut extension; abbreviation rules around -),MissingCORELEX’s primary input. chatter operates on the file’s own vocabulary, not a curated group list.
+n / -nGem termination semantics,Missing
+o3Combine selected speakers per filepartial via --per-file inversePartial
+wFind first-time values for words from +l group,MissingFirst-appearance tracking.

Audit summary

BucketCount
Done5
Partial1
Rewriter only4
Missing8

CORELEX’s biggest gap is +lF: CLAN’s CORELEX is fundamentally a curated-word-list comparison tool (compare a transcript’s vocabulary against a clinical or research word group). chatter’s CORELEX uses the file’s own vocabulary, which is a different question. Filed as a high-priority Phase 1.7 follow-up.

Output

  • Core word list (frequency >= threshold) sorted by frequency descending
  • Non-core word list
  • Core/total ratio and percentage
  • Per-word speaker count (how many speakers used each word)

Differences from CLAN

  • Word identification uses AST-based is_countable_word().
  • Output supports text, JSON, and CSV formats.
  • Core/non-core classification uses shared NormalizedWord for consistency.

DATACLEAN – Fix Common CHAT Formatting Errors

Status: Current Last updated: 2026-05-22 13:01 EDT

Purpose

Reimplements CLAN’s DataCleanUp command, which fixes spacing and formatting issues in CHAT files. Because these are text-level formatting concerns that operate below the AST level, the AST transform is a no-op; the actual logic operates on serialized CHAT text via clean_chat_text() and the end-to-end run_dataclean() function.

Usage

chatter-clan dataclean file.cha

Options

DATACLEAN has no command-specific flags. It accepts a single positional input path plus the optional shared -o/--output from CommonAnalysisArgs (default: stdout). The full set of fixes always runs together; there is no --spacing-only switch, to apply only the text-spacing repairs you would have to pre-filter the input or post-edit the output.

CLAN +-flag coverage audit

DATACLEAN is a transform. Sources: OSX-CLAN/src/clan/DataCleanUp.cpp::usage, crates/talkbank-clan/src/transforms/dataclean.rs.

DATACLEAN-specific +-flags (from DataCleanUp.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+bWork on the BOLD problem only,MissingCLAN isolates one fix-class at a time; chatter always runs the full set.
+cWork on the ++/+, problem only,Missing
+oWork on all other problems only,Missing

Audit summary

BucketCount
Done1 (default full-set)
Missing3

DATACLEAN’s +b/+c/+o partition the fix set into three classes that CLAN lets the user run in isolation. chatter collapses them into “run everything”; partitioning would require splitting the fix passes into named groups with per-flag gating. Filed as a Phase 1.7 follow-up; not load-bearing for typical use.

Behavior

The following fixes are applied to non-header lines:

  • Missing space before [ brackets
  • Missing space after ] brackets
  • Tab characters inside lines (converted to spaces)
  • Bare ... without + prefix (converted to +...)
  • #long converted to ##
  • Header lines (@-prefixed) are left untouched

Differences from CLAN

  • Operates on serialized text (post-parse) rather than raw input, since these are formatting concerns below the AST level.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> text fixups -> write).

DATES – Age Computation from Birth and Date Headers

Status: Current Last updated: 2026-05-22 13:02 EDT

Purpose

Reimplements CLAN’s dates command, which computes the age of each participant at the time of transcription by subtracting @Birth dates from the file-level @Date header. Computed ages are inserted as @Comment: Age of CHI is Y;M.D headers after the @ID/@Birth block.

See the CLAN manual for the original command documentation.

The computed age uses CHAT format: years;months.days (e.g., 2;6.15 for two years, six months, and fifteen days).

Usage

chatter-clan dates file.cha

Options

This command has no command-specific flags beyond the shared -o, --output <PATH> (default: stdout). See Output Formats for the transform output flag.

CLAN +-flag coverage audit

DATES is a transform. Sources: OSX-CLAN/src/clan/dates.cpp::usage, crates/talkbank-clan/src/transforms/dates.rs.

DATES-specific +-flags (from dates.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aC SSpecify age of participant C (default CHI) as Y;M.D,MissingOverrides the computed age with a literal value.
+bC SSpecify birth of participant C as 12-JAN-1962 or 01/12/62,MissingOverrides the @Birth header for the participant.
+d SSpecify date of transcript as 12-JAN-1962 or 01/12/62,MissingOverrides the @Date header.

Audit summary

BucketCount
Done1 (compute-from-headers)
Missing3

DATES’s three +-flags are command-line overrides for the file’s @Birth/@Date headers, useful when the file is missing those headers or when the user wants to override them for a one- off computation. chatter operates strictly on the parsed headers; adding a --age / --birth / --date override family would close the gap. Filed as a Phase 1.7 follow-up.

Behavior

  1. Collects the @Date header value and all @Birth headers with their participant codes.
  2. Computes each participant’s age by subtracting the birth date from the file date.
  3. Inserts @Comment: Age of <PARTICIPANT> is <age> headers into the file.
  4. If no @Date header is present, the file is left unchanged.

Differences from CLAN

  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).

DELIM – Add Missing Utterance Terminators

Status: Current Last updated: 2026-05-22 12:51 EDT

Purpose

Reimplements CLAN’s delim command, which ensures every main tier has a terminator. Utterances missing a terminator (., ?, !) receive a default period (.). This is typically used as a repair step for files imported from external formats that lack CHAT punctuation conventions.

Usage

chatter-clan delim file.cha

Options

This command has no command-specific flags beyond the shared -o, --output <PATH> (default: stdout). See Output Formats for the transform output flag.

CLAN +-flag coverage audit

DELIM is a transform. Sources: OSX-CLAN/src/clan/delim.cpp::usage, crates/talkbank-clan/src/transforms/delim.rs.

DELIM-specific +-flags (from delim.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aChange default terminator from . to ++.,MissingInserts an “interrupted” marker. chatter only inserts . today.

Audit summary

BucketCount
Done1 (default terminator insertion)
Missing1

DELIM’s surface is genuinely minimal. The +a interrupted- terminator option would be a one-line config addition: a Terminator choice on DelimConfig. Filed as a Phase 1.7 follow-up.

Behavior

For each utterance in the file, if the main tier lacks a terminator, a period (.) is inserted as the default terminator.

Utterances that already have a terminator (., ?, or !) are left unchanged.

Differences from CLAN

  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).
  • 4 accepted divergences: CLAN writes an empty file when no changes are needed; we always write the full file. This is intentional – the output is always a valid CHAT file.
  • Golden test parity: 4 accepted divergences (empty-file behavior).

DIST – Word Distribution Across Turns

Status: Current Last updated: 2026-05-26 10:59 EDT

Purpose

Counts turns and tracks for each word the first and last turn in which it appears. DIST is part of the FREQ family of commands and is useful for studying when words first appear and how their usage is distributed across a conversation.

Usage

chatter-clan dist file.cha
chatter-clan dist --speaker CHI file.cha
chatter-clan dist --format json file.cha

Options (chatter-native)

OptionCLAN FlagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN dist flag. Sources:

  • OSX-CLAN/src/clan/dist.cpp: usage() and getflag().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() DIST branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Dist plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

DIST-specific +-flags (from dist.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+bCBreak apart words at character C,MissingWord-segmentation customization.
+gCount only one occurrence of each word per turn--once-per-turnDoneLanded 2026-05-23. Per-turn word dedup via HashSet; first_turn / last_turn are unaffected (they only ever update on first/most-recent encounter). The +g overload (bare = once-per-turn, +gLABEL = gem filter) matches CLAN’s: rewriter checks for empty rest before falling through to the gem branch. Pinned by dist_g_bare_routes_to_once_per_turn and dist_g_with_label_still_routes_to_gem.
+oOnly consider words containing the character C given in +bC,Missing
+dOutput sdata in form suitable for statistical analysis,MissingDIST routes +d through the shared maingetflag path at OSX-CLAN/src/clan/cutt.cpp:9382 (via dist.cpp::getflag default: at line 545); DIST appears with empty per-program body at cutt.cpp:9437, confirming it consumes +d for an onlydata output-detail level. chatter has no --only-data flag for DIST. Per-DIST rewriter arm in clan_args.rs passes the token through so clap reports the literal +d/+dN argument rather than the misleading --display-mode rewrite.

General +-flags DIST inherits (from cutt.cpp::mainusage)

CLAN flagMeaningChatterStatusNotes
+kCase-sensitive--case-sensitiveDoneLanded 2026-05-23. Reads CommonAnalysisArgs::case_sensitive. process_utterance picks the key derivation: default uses NormalizedWord::from_word (lowercased), +k uses NormalizedWord(cleaned_text().to_owned()) (case-preserving) so Want/want/WANT get distinct distribution rows. Pinned by dist_case_sensitive_splits_case_variants and dist_default_collapses_case_variants.

Audit summary

BucketCount
Done8
Partial1
Rewriter only3
Missing6

DIST’s +g is another instance of the +g overload pattern documented in MLU/MLT/FREQPOS. Researchers pasting dist +g file.cha (count once per turn) into chatter get chatter’s gem-segment filter requirement (and an “empty”-style output for files with no matching gem).

Display Modes (+dN / --display-mode N), DRAFT, awaiting PI review

Status: drafted from CLAN manual; not yet implemented. Rewriter at crates/talkbank-clan/src/clan_args.rs:101 translates +dN → --display-mode N; no clap field consumes it today. Drafted from CLAN manual §7.9.1 (Unique Options, DIST) for PI review.

NCLAN behavior (verbatim from manual)
+d (no number)“Output data in a form suitable for statistical analysis.”

DIST’s +d7 is mentioned in passing in the manual as part of the FREQ-family +d7 cross-tier comparison.

Open questions for PI review

  1. “Form suitable for statistical analysis” maps cleanly to --format csv in chatter. Should +d translate directly to --format csv at rewrite time (drop the --display-mode translation entirely for DIST), or honour both?
  2. The DIST +d7 mention is a stub, is DIST genuinely a +d7 user, or is the manual cross-referencing FREQ’s +d7?

Output

Global word list (sorted alphabetically by display form) with:

  • Occurrence count across all turns
  • First turn number (1-based) in which the word occurs
  • Last turn number (omitted if same as first)
  • Total number of turns in the transcript

Turn Definition

Every utterance is its own turn, regardless of whether the speaker changed. This matches CLAN’s behavior, which was verified during parity testing. There is no speaker-continuity grouping – each utterance increments the turn counter.

This is different from how turns are defined in MLT (where consecutive utterances by the same speaker form a single turn).

Differences from CLAN

Turn counting

Every utterance = one turn (no speaker-continuity grouping), matching CLAN exactly.

Word identification

Uses AST-based is_countable_word() instead of CLAN’s string-prefix matching.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

100% parity with CLAN C binary output.

DSS – Developmental Sentence Scoring

Status: Current Last updated: 2026-05-27 10:41 EDT

Purpose

Assigns point values to utterances based on grammatical complexity, using a configurable rule file that defines pattern-matching rules for morphosyntactic categories. DSS is a clinical tool developed by Laura Lee and Susan Canter for evaluating children’s grammatical development by scoring complete sentences on eight grammatical categories.

Scoring requires a %mor dependent tier on each utterance. Utterances without %mor are silently skipped.

See the CLAN manual for the original DSS command specification and the full rule set.

Usage

chatter-clan dss --speaker CHI file.cha
chatter-clan dss --rules english.scr file.cha
chatter-clan dss --max-utterances 100 file.cha
chatter-clan dss --format json file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--rules <PATH>+lFCustom DSS rules file (.scr)
--max-utterances <N>+cNMaximum utterances to score (default: 50)
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN dss flag. Sources:

  • OSX-CLAN/src/clan/dss.cpp: usage().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() DSS branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Dss plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

DSS is a required-flag refusal command in chatter, same refusal byte-parity as EVAL/KIDEVAL/IPSYN/SUGAR.

DSS-specific +-flags (from dss.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aNDebug DSS rules level N (1-3),MissingRule-tracing diagnostic.
+cNAnalyse N complete unique utterances (default 50)--max-utterances NDoneRewriter routes +cN → --max-utterances N via the shared (b'+', b'c') if matches!(subcommand, Ipsyn | Dss) arm in clan_args.rs (the existing IPSYN routing covers DSS too). Audit row flipped from Partial → Done 2026-05-27.
+dOutput in spreadsheet format,MissingOSX-CLAN/src/clan/dss.cpp:2520 sets IsOutputSpreadsheet = 1 for bare +d. chatter has no --format csv for DSS. Per-DSS rewriter arm in clan_args.rs passes the token through so clap reports the literal +d argument rather than the misleading --display-mode rewrite.
+d1Spreadsheet format with one TOTAL line per file,MissingSame dss.cpp:2520 switch sets IsOutputSpreadsheet = 2 for +d1. Per-DSS rewriter arm passes the token through.
+lFSpecify language script file F (eng, engu, bss, jpn)--rules <PATH>DoneSame rewriter-routing gap as IPSYN.

Audit summary

BucketCount
Done6
Partial2
Rewriter only2
Missing7

DSS’s gap pattern mirrors IPSYN’s. The two cleanest one-line follow-ups: rewriter routing of +cN → --max-utterances N and +lF → --rules F for the DSS subcommand specifically. Both filed as Phase 1.7 follow-ups, batched with IPSYN’s equivalents and the existing MAXWD +cN → --limit N precedent.

Scoring Categories

DSS scores utterances on eight grammatical categories:

  1. Indefinite pronouns / noun modifiers (it, this, that)
  2. Personal pronouns (I, me, my, mine, you, your)
  3. Main verbs (uninflected, copula, auxiliary)
  4. Secondary verbs (non-finite: infinitives, gerunds, participles)
  5. Negation (no, not, can’t, don’t)
  6. Conjunctions (and, but, or, if, because)
  7. Interrogative reversals (is he, can you, do they)
  8. Wh-questions (who, what, where, when, why, how)

Each category earns 1-8 points based on developmental complexity. A sentence point is awarded if the utterance is a complete grammatical sentence.

Algorithm

  1. Parse each utterance’s %mor tier for POS-tagged morphemes
  2. Match morpheme patterns against category rules
  3. For each category, award points for the highest-scoring matched pattern
  4. Award sentence point for complete sentences (heuristic: subject + verb POS)
  5. Sum across categories + sentence point = utterance score
  6. DSS = mean score across scored utterances

Output

Per-speaker DSS total with per-category breakdown and per-utterance scores.

Differences from CLAN

Built-in rules

The default rules are a simplified subset of the canonical DSS rule set (10 categories). For full clinical scoring, supply a complete .scr rules file via --rules. When a rules file is not provided, DSS produces approximate scores suitable for screening but not clinical reporting.

Sentence-point assignment

Uses a heuristic (presence of subject + verb POS tags in %mor) rather than full syntactic analysis. This may under-award sentence points for syntactically complex but structurally unusual utterances.

Maximum utterances

Defaults to 50 per speaker (configurable via --max-utterances). CLAN also defaults to 50 but the implementation differs in how utterances are selected when the sample exceeds the maximum.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

Verified against CLAN C binary output.

ELAN2CHAT – ELAN XML to CHAT Conversion

Status: Current Last updated: 2026-05-22 13:40 EDT

Purpose

Converts ELAN annotation files (.eaf) into CHAT format. ELAN uses a time-aligned annotation format stored as XML, with time slots referenced by alignable annotations within tiers.

Usage

chatter-clan elan2chat input.eaf

Options

OptionDefaultDescription
-l, --language"eng"ISO 639 language code for the @Languages header
-o, --outputstdoutOutput CHAT file path

The corpus name in @ID headers is hardcoded to "elan_corpus" (crates/talkbank-clan/src/converters/elan2chat.rs:230); there is no CLI flag to override it.

Conversion Details

  • ELAN tier IDs are mapped to CHAT speaker codes (first 3 characters, uppercased)
  • Time slots are resolved to millisecond timing bullets
  • Annotations are merged across tiers and sorted by start time
  • All speakers are assigned the Unidentified participant role

Input Format

ELAN XML (.eaf) files containing <TIER> elements with <ALIGNABLE_ANNOTATION> entries referencing <TIME_SLOT> elements for timing.

Output

A well-formed CHAT file with @UTF8, @Begin/@End headers, @Languages, @Participants, and @ID headers for each discovered speaker. Each ELAN annotation becomes a timed utterance.

Implementation Note

Uses simple string-based XML parsing to avoid adding a quick-xml dependency. Sufficient for well-formed ELAN files.

Differences from CLAN

  • Uses typed AST for CHAT generation
  • Produces valid, well-formed CHAT output

Reference

See the CLAN manual for the original ELAN2CHAT command documentation.

CLAN +-flag coverage audit

ELAN2CHAT is a converter: input ELAN .eaf XML, output CHAT. Sources: OSX-CLAN/src/clan/Elan2Chat.cpp::usage, crates/talkbank-clan/src/converters/elan2chat.rs.

ELAN2CHAT-specific +-flags (from Elan2Chat.cpp::usage)

CLAN flagMeaningChatterStatus
+aOutput tiers as found in .eaf (default: sort by utterance delimiter),Missing
+bMultiple bullets per line (default: one per line),Missing

Audit summary: 1 Done (default conversion), 2 Missing. Both gaps are output-shape policy switches; chatter’s default follows CLAN’s default in both cases.

EVAL-D – Language Sample Evaluation (DementiaBank)

Status: Current Last updated: 2026-05-22 09:21 EDT

Purpose

EVAL-D is a variant of EVAL used for data collected with the DementiaBank protocol. The analysis logic is identical – only the normative comparison database differs.

EVAL uses AphasiaBank norms; EVAL-D uses DementiaBank norms.

Usage

chatter-clan eval-d file.cha
chatter-clan eval-d --speaker PAR file.cha
chatter-clan eval-d --format json file.cha

Options

All options are identical to EVAL.

CLAN +-flag coverage audit

EVAL-D’s +-flag surface is byte-identical to EVAL’s. The only divergence is the normative-comparison database name embedded in +dS choices (DementiaBank cohorts instead of AphasiaBank cohorts). The coverage matrix, status counts, and audit conclusions for EVAL-D are the same as EVAL.

EVAL-D is a required-flag refusal command in chatter, same as EVAL, emitting the exact CLAN refusal message when +t*X is absent.

The DementiaBank database-comparison engine is missing for the same reason EVAL’s AphasiaBank engine is missing: chatter does not bundle the .cut normative databases.

Differences from CLAN

  • Same as EVAL – see EVAL differences.
  • The EvalVariant::Dialect config flag selects DementiaBank norms automatically.

Implementation

EVAL-D is not a separate command module. It reuses EvalCommand with EvalConfig { variant: EvalVariant::Dialect, .. }. The variant determines which .cut database directory to use for normative comparison.

EVAL – Language Sample Evaluation

Status: Current Last updated: 2026-05-22 09:21 EDT

Purpose

Comprehensive morphosyntactic analysis computing lexical diversity, grammatical category counts, error rates, and MLU. EVAL was originally designed for clinical evaluation of adult aphasic speech samples (Saffran, Berndt & Schwartz, 1989) and produces a detailed profile of morphosyntactic abilities.

Requires a %mor dependent tier for morpheme-level metrics. Word-level metrics are computed from the main tier regardless.

See the CLAN manual for the original EVAL command specification.

Usage

chatter-clan eval file.cha
chatter-clan eval --speaker CHI file.cha
chatter-clan eval --format json file.cha

Options (chatter-native)

OptionCLAN FlagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN eval flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/eval.cpp: usage() and getflag().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() EVAL branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Eval plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

EVAL is a required-flag refusal command in chatter, invoking without +t*X (or --speaker X) emits CLAN’s exact Please specify at least one speaker tier code with "+t" option on command line. to stderr and exits 1. That refusal byte-parity is verified.

EVAL-specific +-flags (from eval.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+bS / -bSMorpheme-delimiter customization,MissingShared with WDLEN/MAXWD/KIDEVAL.
+dSDatabase keyword (Anomic, Global, Broca, Wernicke, control, Fluent, Nonfluent, AllAphasia, …),MissingEVAL’s whole reason for existing, AphasiaBank normative comparison.
+e1Create list of database files used,MissingDatabase-side.
+e2Create proposition word list per file,Missing
+g (no S)Gem tier should contain all words specified by +gS,MissingEVAL-specific override of the inherited gem semantic.
-gLook for gems in database only,Missing
+gSSelect gems labelled S--gemDone
+lFLanguage database file (eng, fra),Missing
+n / -nGem termination semantics,Missing
+o4Output raw values instead of percentages,Rewriter onlyFalls to --display-mode rewrite.

Audit summary

BucketCount
Done5
Partial0
Rewriter only5
Missing14

EVAL’s largest gap is the AphasiaBank database-comparison engine (+dS, +lF, +e1, +e2). Without +dS filters, chatter’s EVAL produces a self-contained morphosyntactic profile without the clinical-norm overlay that is EVAL’s purpose. Filed as a Phase 1.7 follow-up alongside KIDEVAL’s database engine.

EVAL has no command-specific flags beyond the shared CommonAnalysisArgs set; the per-speaker normative-comparison aspect lives in EVAL-D (DementiaBank norms) and KIDEVAL (child norms), invoked as separate subcommands.

Metrics

EVAL produces a comprehensive profile per speaker:

Lexical measures

  • Utterances: Total utterance count
  • Total words: All countable words
  • NDW: Number of different words (types)
  • TTR: Type-token ratio (types / tokens)

MLU

  • MLU-w: Mean length of utterance in words
  • MLU-m: Mean length of utterance in morphemes (from %mor)

Part-of-speech counts (from %mor)

  • Nouns, verbs, auxiliaries, modals
  • Prepositions, adjectives, adverbs
  • Conjunctions, determiners, pronouns

Inflectional morphology (from %mor)

  • Plurals (PL)
  • Past tense (PAST)
  • Present participle (PRESP)
  • Past participle (PASTP)

Error and ratio measures

  • Word errors: Count of [*] markers
  • Open/closed class ratio: Content words vs function words

Differences from CLAN

Word and morpheme identification

Uses AST-based is_countable_word() and typed POS categories instead of CLAN’s string-prefix matching. POS classification operates on structured MorWord types rather than parsing POS tag strings at analysis time.

Error extraction

[*] error markers are extracted from parsed AST annotations (the ErrorMarker node type) rather than raw text pattern matching. This ensures accurate counting even with complex nested annotations.

Output formats

Supports text, JSON, and CSV. CLAN produces text only. JSON output provides structured access to all metrics for programmatic use.

Golden test parity

Verified against CLAN C binary output.

EVAL-D variant

chatter-clan eval-d is identical to EVAL but uses DementiaBank protocol norms instead of AphasiaBank norms for normative comparison. See EVAL-D for details.

FIXBULLETS – Fix Timing Bullet Consistency

Status: Current Last updated: 2026-05-27 10:12 EDT

Purpose

Repairs timing bullets that link CHAT to audio or video. The legacy manual describes FIXBULLETS more broadly: converting old-format bullets to new format, inserting @Media, merging multiple bullets, adding language tags, and shifting global timing offsets.

talkbank-clan now supports the AST-safe subset of that behavior: main-tier monotonic bullet repair, global millisecond offsets on parsed bullet timings, and tier-scoped bullet repair using parsed tier kinds.

Usage

chatter-clan fixbullets file.cha
chatter-clan fixbullets file.cha --offset 800
chatter-clan fixbullets file.cha --tier cod
chatter-clan fixbullets file.cha --exclude-tier com

Options

  • --offset N Shift parsed bullet timings by N milliseconds. Negative offsets fail if they would move a parsed bullet before 0.
  • --tier S Restrict processing to selected tier kinds such as cod, %cod, or * for main tiers.
  • --exclude-tier S Exclude selected tier kinds from processing.

CLAN +-flag coverage audit

FIXBULLETS is a transform. Sources: OSX-CLAN/src/clan/fixbullets.cpp::usage, crates/talkbank-clan/src/transforms/fixbullets.rs.

FIXBULLETS-specific +-flags (from fixbullets.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+bMerge multiple bullets per line into one bullet per tier(default)Partialchatter’s monotonic-bullet repair already collapses overlapping ranges on the main tier. The semantics differ slightly, file a follow-up if a round-trip test surfaces a discrepancy.
+gZero out first bullet and offset the rest (per-file gem),MissingGem-based offset reset.
+mMerge all files into one file with offsets progressively offset,MissingMulti-file merge with timing chaining.
+oNAdd N ms to all bullet timings--offset=NDoneDirect mapping. Rewriter routes +oN → --offset=N (= syntax, symmetric with the negative form below). The numeric-only guard prevents +oS non-numeric from accidentally matching.
-oNSubtract N ms--offset=-N (negative)DoneNegative-value form. Rewriter routes -oN → --offset=-N (= syntax mandatory: clap parses a free-standing -N as a short-flag attempt and rejects it before reading it as the value of --offset). Subprocess regression guard: legacy_fixbullets_negative_offset_runs_via_subprocess.

Audit summary

BucketCount
Done2
Partial1
Missing2

FIXBULLETS’s +g/+m multi-file workflows are out of scope for the AST-safe subset; the audit notes them as legacy batch-processing workflows. The +oN ↔ --offset N mapping should get a rewriter route (same shape as the recent MAXWD +cN → --limit N fix); filed as a Phase 1.7 follow-up.

Behavior

The transform iterates through the parsed AST and:

  1. Shifts parsed bullet timings on supported AST locations: main-tier terminal bullets, main-tier inline word/internal bullets, bullet-content dependent tiers such as %act/%cod/%com, and %wor inline bullets.
  2. Enforces non-overlapping, monotonic timing windows on main-tier terminal bullets.
  3. Preserves duration when repairing an overlapping main-tier terminal bullet, using a minimum duration of 1 ms.

Utterances without main-tier terminal bullets are skipped for monotonic tracking.

Differences from CLAN

  • Current supported scope: FIXBULLETS supports global offsets and tier-scoped AST-native bullet repair on parsed bullet locations, including bullet-bearing @Comment headers.
  • Scope reduction remains: the CLAN manual documents a broader repair tool than the current implementation provides.
  • Not yet implemented: old-to-new bullet conversion, @Media insertion, multi-bullet merge (+b), and +l language-tag insertion described in the manual.
  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).

FIXIT – Normalize CHAT Formatting

Status: Current Last updated: 2026-05-22 13:05 EDT

Purpose

Normalizes CHAT file formatting by re-serializing through the parser. Fixes inconsistent spacing, malformed tier prefixes, and other formatting issues.

Usage

chatter-clan fixit file.cha
chatter-clan fixit file.cha -o normalized.cha

Behavior

Since the parse-serialize pipeline produces canonically formatted output, FIXIT is effectively a roundtrip: parse the file, then serialize the resulting AST. Any formatting inconsistencies are corrected during serialization.

Differences from CLAN

  • Uses full AST roundtrip rather than heuristic text manipulation.
  • Files that fail to parse produce an error rather than attempting partial text-level fixes.

CLAN +-flag coverage audit

FIXIT is a transform. CLAN’s fixit.cpp::usage shows [c ...] in its Usage: shape but documents no +-flag entries. chatter’s FIXIT exposes only the input path + -o output.

CLAN flagMeaningChatterStatus
(none documented)default re-serializedefaultDone

Audit summary: 1 Done, 0 Missing. Byte-parity complete for the documented surface.

  • Output is the canonical CHAT serialization, which may reorder some whitespace or normalize header formatting.

FLO – Simplified Fluent Output

Status: Current Last updated: 2026-11-13

Purpose

Reimplements CLAN’s flo command, which generates a %flo: dependent tier containing a simplified, “fluent” version of each utterance’s main line.

See the CLAN manual for the original command documentation.

Usage

chatter-clan flo file.cha

Options

The upstream changelog dated October 30, 2026 adds +d3 for LDC-formatted text output. This implementation has no +d3 output mode. The CLI rejects the option invocation. Its default CHAT transform remains the supported path.

This command has no command-specific flags beyond the shared -o, --output <PATH> (default: stdout). See Output Formats for the transform output flag.

CLAN +-flag coverage audit

FLO is a transform: input CHAT in, output CHAT (with the new %flo: tier) out. No banner; no shared CommonAnalysisArgs.

Sources: OSX-CLAN/src/clan/flo.cpp::usage, crates/talkbank-clan/src/transforms/flo.rs.

FLO-specific +-flags (from flo.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aDo not strip @… suffixes (default strips word@s → word),Missingchatter currently always strips.
+cmFilter main tier the way mor does,MissingMor-grade pre-cleanup.
+crFilter main tier + remove speaker codes and delimiters,MissingStripped output.
+cjCFilter main tier for JSON comparison (C-/p-/s- strip variants),MissingPipeline-internal mode.
+caCreate output for MFA aligner,MissingNiche format.
+cbKeep bullets in output,MissingBullet-preservation toggle.
+dReplace main tier with simplified %flo in output,MissingOSX-CLAN/src/clan/flo.cpp:197: bare +d (or +d0) sets substitute_flag = 1 (flo line replaces main line). chatter emits %flo: as a new dependent tier alongside the original main tier, no substitute-flag consumer. Per-FLO rewriter arm in clan_args.rs passes the token through so clap reports the literal +d argument rather than the misleading --display-mode rewrite.
+d1FAVE-formatted output,MissingSame flo.cpp:197 switch sets substitute_flag = 2. Per-FLO rewriter arm passes the token through.
+d2AntConc-formatted .txt with BOM,MissingSame flo.cpp:197 switch, +d2 is an empty branch (no substitute_flag change). Per-FLO rewriter arm passes the token through.
+d3LDC-formatted .txt,MissingAdded by upstream on 2026-10-30. No output mode is implemented here.

Audit summary

BucketCount
Done0
Partial0
Missing10

FLO has the largest “Missing” bucket relative to surface size of any audited command, the chatter implementation supports only the default flo file.cha invocation (emit %flo tier, keep main). Every variant flag is missing. Most of the variants are niche output-format selectors (FAVE, MFA, AntConc) rather than analysis- shape changes; defer until a researcher requests one.

Behavior

Processing steps:

  1. Strips all header lines (no @UTF8, @Begin, @End, etc.)
  2. Adds a %flo: dependent tier to each utterance containing the simplified main line: just countable words plus the terminator
  3. Strips retrace targets (words/groups before [/], [//], [///], [/-], the four RetraceKind variants per crates/talkbank-model/src/model/content/retrace.rs)
  4. Strips non-countable words (xxx/yyy/www, 0word, &~frag, &-um)
  5. Strips events (&=thing) and pauses
  6. For replaced words ([: form]), uses the replacement (corrected form)
  7. Keeps existing dependent tiers (%mor, %gra, etc.)

The %flo: tier is inserted at position 0 (before other dependent tiers).

Differences from CLAN

  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).

FLUCALC – Fluency Calculation

Status: Current Last updated: 2026-05-27 10:42 EDT

Purpose

Detects and quantifies disfluencies in speech transcripts, producing per-speaker counts of stuttering-like disfluencies (SLD) and typical disfluencies (TD). FLUCALC is the standard tool in CLAN for analyzing fluency in stuttering research.

See the CLAN manual for the original FLUCALC command specification.

Usage

chatter-clan flucalc file.cha
chatter-clan flucalc --speaker CHI file.cha
chatter-clan flucalc --format json file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN flucalc flag. Sources:

  • OSX-CLAN/src/clan/flucalc.cpp: usage() and getflag().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() FLUCALC branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Flucalc plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

FLUCALC-specific +-flags (from flucalc.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aGet pause durations from %wor tier,Missingchatter ignores %wor for pauses.
+bWord-mode analyses (default: syllable mode),Missingchatter is word-mode only.
+b1Word mode with repetition/retraces,Missing
+cCompute pause duration from (2.4) notation,MissingInline pause-time parsing.
+c1Add phonological fragment to SLD instead of TD,MissingCounting policy switch.
+c5With +p: reverse source/target tier priority,Missing
+dNSample size N (s, w), e.g. +d100s for 100 syllables,Rewriter only--display-mode N; no consuming clap field.
+e1..+e5Side-effect file creation (syllable counts, fluent utterances, disfluencies),Missing
+uCompute output per utterancepartial via --per-filePartialCLAN (flucalc.cpp:778-781, isUttList = TRUE) enables per-utterance output. chatter has only --per-file (file granularity), not per-utterance. Per-FLUCALC rewriter arm in clan_args.rs returns None for honest rejection: clap reports the literal +u argument rather than the global +u arm silently dropping it (which would let chatter run with default aggregated output while the user expected per-utterance results).
+pS / +p@FSearch word S and match POS,Missing
+g / -g / +gSGem semantics (same overload as EVAL)--gem (S form only)Partial
+n / -nGem termination semantics,Missing

Audit summary

BucketCount
Done4
Partial2
Rewriter only5
Missing13

FLUCALC’s largest gap is the syllable-vs-word mode (+b vs default syllable). chatter operates exclusively in word mode, which produces different counts from CLAN’s default. This is a silent wrong for researchers expecting CLAN-default syllable-mode output. Filed as a Phase 1.7 high-priority follow-up.

Disfluency Categories

Stuttering-Like Disfluencies (SLD)

TypeCHAT notationExampleStatus
Prolongation: within wordwa:ntImplemented
Broken word^ notationbase^ballImplemented
Whole-word repetitionConsecutive identical wordsI I wantImplemented
Part-word repetition––Partial
Block––Partial

Typical Disfluencies (TD)

TypeCHAT notationExampleStatus
Phrase repetition[/]I want [/] I wantImplemented
Revision[//]I want [//] I needImplemented
Filled pause&- prefix&-uh, &-umImplemented
Phonological fragment&+ prefix&+frImplemented

Output measures

All counts are reported as:

  • Raw values: Total count per disfluency type
  • Percentages: Per 100 words

Algorithm

  1. For each utterance, walk the AST content nodes
  2. Identify disfluency markers:
    • Retrace groups ([/], [//]) from parsed AST annotations
    • Fillers and fragments from word category annotations
    • Prolongations and broken words from within-word notation
    • Whole-word repetitions from consecutive identical countable words
  3. Accumulate per-speaker counts by disfluency category
  4. Compute percentages relative to total words (or syllables)

Differences from CLAN

Detection method

Some categories (specifically [/] and [//] retrace markers) are currently counted via substring matching on the serialized CHAT text rather than fully through the parsed AST. This produces equivalent results but is a known area for future improvement.

Part-word repetitions and blocks

Counted via CHAT notation markers rather than acoustic analysis. Full detection of these categories requires audio-linked analysis that is beyond the scope of text-based transcript processing.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

Verified against CLAN C binary output.

FREQ – Word Frequency

Status: Current Last updated: 2026-06-04 21:40 EDT

Purpose

Counts word tokens and types and computes type-token ratio (TTR). The legacy manual describes FREQ as one of CLAN’s most powerful and easiest-to-use programs, producing word-frequency counts and lexical-diversity measures over selected files and speakers.

In talkbank-clan, FREQ counts words on the main tier by default, or morphemes from the %mor tier when --mor is set.

See the CLAN manual for the original FREQ command specification.

Usage

chatter-clan freq file.cha
chatter-clan freq --speaker CHI file.cha
chatter-clan freq --format json corpus/
chatter-clan freq --mor file.cha
chatter-clan freq --include-word "the" file.cha

+k / --plus-k (--case-sensitive alias) is wired as of 2026-05-22 (pattern matching) + 2026-05-23 (frequency-table keying). FREQ preserves case by default, matching CLAN’s nomap=TRUE default. CLAN’s +k toggles that mode to case-folding; the rewritten --plus-k flag carries the legacy toggle’s presence for FREQ:

  • +s/--include-word patterns and searched words are lower-cased under +k, so case variants match;
  • the frequency-table key is also folded, so Want, want, and WANT collapse to one entry instead of producing three.

Options (chatter-native)

OptionCLAN FlagDescription
--speaker <CODE>+t*CHIInclude speaker
--exclude-speaker <CODE>-t*CHIExclude speaker
--include-word <WORD>+s"word"Only count matching word
--exclude-word <WORD>-s"word"Skip matching word
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting (a retracing retraces the single preceding word; default drops it). Byte-parity golden freq_r6_retrace.
--plus-k (--case-sensitive alias)+kCarry CLAN’s case-handling toggle; FREQ preserves case by default and folds under +k
--format <FMT>–Output format: clan (default), text, json, csv
--mor–Count morphemes from %mor tier instead of words from main tier

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN freq flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/freq.cpp: usage() at line 152 and the command-specific getflag() intercept at line 621.
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() at line 9090 (program-keyed FREQ branches throughout).
  • crates/talkbank-clan/src/clan_args.rs: chatter’s +flag to --flag rewriter.
  • crates/talkbank-cli/src/cli/args/clan_common.rs and crates/talkbank-cli/src/cli/args/clan_commands.rs::Freq, chatter’s clap field surface for FREQ.

Status legend

  • Done: chatter accepts the flag and the semantic is implemented.
  • Partial: chatter accepts a related abstraction with non-identical semantics; gap noted in the Notes column.
  • Rewriter only: clan_args.rs rewrites the +flag to a chatter flag, but no clap field on Freq consumes that token; passing the flag errors out at parse time.
  • Missing: neither rewriter nor clap field handles it.

Freq-specific +-flags (from freq.cpp::getflag)

CLAN flagMeaningChatterStatusNotes
+a(FREQ typeForms),Deferred (design + manual-clarity, MOR-interacting)FREQ’s +a sets typeForms = TRUE (freq.cpp:768, a no-arg toggle) and is then woven through ~10 output sites (freq.cpp:439, 1064, 1077, 1179, 1202, 1209, 1507, 1530, 1794, 1852), gating on nonSpTierSpecified (dependent-tier) and the onlydata/%mor output paths, so it is not a localized main-tier flag. The CLAN manual has no FREQ-specific +a entry (its +a sections at CLAN.txt:6532 and 9454 document OTHER commands, MAXWD “unique-length only” and a %wor pause flag), so the INTENT is unclear from the manual, and the behaviour is %mor/dependent-tier-coupled. Per the bug-localization rule this is a manual-clarity + design + MOR question, not a solo implementation; deferred to the FREQ porting report. chatter rejects +a at the fail-closed boundary (correct interim).
+bNFrame size for MATTR (Moving-Average TTR)--mattr NDoneLanded 2026-06-02. Per-speaker Moving-Average TTR: the mean over every length-N sliding window of that window’s TTR (distinct_types / N), across all T - N + 1 windows (comute_MATTR, freq.cpp:1742-1781; manual CLAN.txt:5473-5479). N must be a positive integer (FrameSize newtype rejects +b0, matching freq.cpp:777-780). Rendered per speaker after the TTR caveat as %5.3f MATTR, or - MATTR when T < N (NMATTRs == 0, freq.cpp:1542-1547). The windowed average is the shared framework::moving_average_ttr primitive (reusable by VOCD and future diversity measures). Golden-proven by freq_b_mattr_eng (CLAN +b3 on the 15-token *SPE = 1.000 MATTR); the T<N - path and +b0 rejection are pinned by the freq_mattr_tests subprocess tests. With +d2/+d3 a trailing MATTR column is appended to the spreadsheet (header + per-row %.3f Number cell, - when undefined; freq.cpp:3303, 1558-1562), pinned by freq_d2_with_mattr_appends_mattr_column and verified byte-for-byte against CLAN’s +b3 +d2.
+c / +c0Find capitalised words only--capitalization initialDoneLanded 2026-05-22. Skips any countable word whose first character is not uppercase before frequency accumulation. Both +c and +c0 are accepted as aliases (CLAN treats them identically); subcommand-guarded so MAXWD/CHECK/IPSYN/DSS keep their existing +cN meaning. Shares the CapitalizationFilter enum with VOCD.
+c1Find words with upper-case letters in the middle--capitalization midDone (diverges, CLAN-DIV-003)Landed 2026-05-22. Keeps only words whose surface form contains an uppercase letter AFTER position 0 (e.g. McDonald, iPhone). Initial-capital words like Cookie are dropped. Shares the CapitalizationFilter::MidUpper predicate with VOCD. Deliberate CLAN-bug divergence (CLAN-DIV-003): CLAN’s +c1 (freq.cpp isRightUpper, capwd == 2) loops from position 0 and keeps initial-caps too, identical to +c, contradicting the manual’s “middle only”; chatter implements the documented semantic. Pinned by the freq_c1_mid_capitalization_eng DivergesFromClan golden.
+c2Count a word once per matching +s pattern (not just once)--search-multiplicity per-patternDoneLanded 2026-06-02. Correction: this is a SINGLE-word +s multiplicity flag, NOT a multi-word search variant (the prior note was wrong). capwd == 3 (freq.cpp:432-438): a word that matches several +s patterns is counted once per matching pattern, where the default counts it once regardless (manual CLAN.txt:5485-5486). CLAN requires the +s patterns to carry wildcards (isFoundWildCard) and rejects +c2 combined with a multi-word +s group (freq.cpp:455-459); chatter reproduces both errors at dispatch. Implemented via WordFilter::count_matching_includes + the IncludeMultiplicity enum. Golden-proven by freq_c2_perpattern_eng (CLAN +c2 +s"t*" +s"*p" on *SPE: “top” matches both patterns -> counted 2); the default-once contrast and both guard errors are pinned by freq_c2_multiplicity_tests.
+c3Match multi-word groups in any order on a tier--multiword-order anyDoneLanded 2026-06-02 (Phase 2 of the multi-word cluster). Relaxes multi-word +s matching from the default adjacent in-order sequence to “anywhere and in any order” (anyMultiOrder, freq.cpp:792, 2389-2464; manual CLAN.txt:5488): each token fills the first unfilled slot it matches; the group counts once when every slot is filled, then resets. The item is still displayed as the search pattern, not the matched data order. Implemented as the MatchOrder::AnyOrder mode on the shared framework::multiword matcher. Golden-proven by freq_c3_anyorder_eng (CLAN +c3 +s"going Triangle" on *SPE = 1 going Triangle, reversed and non-adjacent); contrast with the without-+c3 0-match pinned by freq_c3_anyorder_tests.
+c4Match only if tier is solely the multi-word group--multiword-scope soleDoneLanded 2026-06-02 (Phase 3 of the multi-word cluster). A multi-word +s match counts only when the utterance consists solely of the group: its word count must equal the group’s slot count (onlySpecWsFound, freq.cpp:794, 2381-2388; manual CLAN.txt:5490-5491). Implemented as MatchScope::SoleContent on the shared framework::multiword matcher; composes with +c3 (+c3 +c4 = any-order sole-content). Golden-proven by freq_c4_sole_eng (CLAN +c4 +s"Triangle kept going" on the 3-word *SPE utterance = 1); subset/contrast pinned by freq_c4_sole_content_tests. No-match presentation re-probed 2026-10-31: CLAN still emits the selected speaker section with zero totals for a 26-word search group on core/basic-conversation.cha, matching chatter’s section presence. The numeric prefix CLAN prints before Speaker: also appears in the ordinary FREQ case, so this probe does not establish a +c4-specific output gap.
+c5With +d7, reverse source/target tier priority,Deferred (gated on +d7)CLAN itself refuses +c5 without +d7: freq.cpp:561-563 errors "The +c5 option can only be used with +d7 option" (isMorTierFirst). +d7 is the PI-gated source/target linked-tier (%mor cross-tier) row, so +c5 cannot be implemented before it; both go in the FREQ porting report. chatter rejects +c5 at the fail-closed boundary (correct interim).
+c6Count only repeat segments,Deferred (CA repeat-segment, needs parser support)CLAN’s isRepeatSegment (freq.cpp:153, 798) filters the main tier to the CA repeat-segment spans delimited by ↫ (U+21AB), via separateRepeatSegments/filterRepeatSegs (freq.cpp:1857-1992), and is meant to combine with a +s search (“count only repeat segments when searching”). chatter’s typed AST treats ↫ as a satellite delimiter (not word content; see CLAN-DIV-006 in the +r7 row), so it has no structural repeat-segment span to restrict to: implementing +c6 needs a parser/model addition (a repeat-segment span type) plus the +s-search coupling, i.e. a CA-data/parser question, not a FREQ-command-only change. Deferred to the FREQ porting report; chatter rejects +c6 at the fail-closed boundary (correct interim). Single fixture with ↫: corpus/reference/ca/nonvocal-and-long-features.cha.
+c7For multi-word searches output actual words matched--multiword-display matchedDoneLanded 2026-06-03 (Phase 5, last implementable multi-word mode). For a multi-word +s group, display the words that actually matched rather than the search pattern (isMultiWordsActual, freq.cpp:800, 2444; manual CLAN.txt:5498-5500): +s"the *" collapses every match into one the * entry by default, while +c7 reveals each (the hill, the top). The shared framework::multiword matcher now returns a Match carrying the token index per slot (reusable by KWAL context / COMBO), and FREQ keys each match by Match::matched_words under +c7. Golden-proven by freq_c7_matched_eng; the default-pattern contrast pinned by freq_c7_matched_words_tests.
+o / +o0Sort by descending frequency--sort frequencyDonechatter’s default per-word order is alphabetical (CLAN’s default, its BST in-order traversal); +o/+o0 map to --sort frequency, switching to descending count with an alphabetical tiebreak (freq.cpp:176; freq.cpp:815-817: *f == EOS || *f == '0' sets isSort). Pinned by the freq_o_descending_frequency_eng byte-parity golden. The 2026-06-01 golden probe corrected the earlier mis-audit that called +o a no-op: chatter was actually rendering alphabetical while CLAN +o is frequency-descending, so the sort mode was implemented (the FreqSort enum replaced the reverse_concordance bool).
+o1Sort by reverse concordance--sort reverse-concordanceDoneLanded 2026-05-23. Replaces the default frequency-descending sort with a sort by the reversed character sequence of each word, groups words sharing a suffix. Pinned by freq_reverse_concordance_groups_by_suffix (with cat/bat/dog/log input, the sorted result reflects reversed-string comparison) and freq_default_sort_is_alphabetical_when_freqs_equal (regression companion). End-to-end smoke: cat bat dog log apple maple with +o1 clusters maple/apple, dog/log, bat/cat. +o2 (reverse concordance + non-CHAT output) is a separate Missing item.
+o2Sort by reverse concordance of first word, preserve full line,DeferredCLAN +o2 sets chatmode = 0 (freq.cpp:820-830), reinterpreting the CHAT file as plain text and counting whole input lines as tokens, %mor:/%gra:/@ID:/@Begin lines included (verified by live probe). This is antithetical to chatter’s AST-first model: reproducing it requires bypassing the parser to count raw lines, which chatter deliberately does not do. Deferred with this source-grounded reason; revisit only if a plain-text input mode is ever added.
+o3Combine all speakers into one list--combine-speakersDoneLanded 2026-06-03. CLAN isCombineSpeakers (freq.cpp:832): pool ALL speakers’ counts into one frequency table with no per-speaker Speaker: header (freq.cpp:1451 prints the banner only when !isCombineSpeakers), summed counts, combined Types/Tokens/TTR. On eng-conversation (*SPE + *GES), the = 4 (2+2), Types=14, Tokens=28, TTR=0.500 (live CLAN probe). Golden-proven by freq_o3_combine_eng; the rewrite + header suppression + pooling are pinned by freq_o3_combine_tests. Completes the +o sort sub-cluster (+o/+o0/+o1/+o3 Done, +o2 Deferred).
+dAll selected words + freq + line numbers,MissingBare +d reaches maingetflag (freq.cpp:838 -> cutt.cpp:9402) and sets onlydata = atoi("")+1 = 1, i.e. CLAN source treats +d IDENTICALLY to +d0; the manual calls +d the no-flag default but +d0 a concordance. That manual-vs-source discrepancy (and any getfarg next-arg consumption) must be reconciled before implementing. No rewriter arm consumes it, so it now ERRORS fail-closed at the file-discovery boundary (DiscoveredChatFiles), no longer silently swallowed as a bogus file.
+d0Concordance with frequencies and line text,MissingPI-gated (concordance, overlaps KWAL); onlydata = 1 (freq.cpp:838 -> cutt.cpp:9402, same as bare +d). Now ERRORS fail-closed at the boundary; do not implement solo.
+d1One word per line, no frequencies--word-list-onlyDoneRewriter maps bare +d1. Emits an alphabetized deduped word list merged across all speakers, suitable as kwal +s@FILE input.
+d2Spreadsheet output (Excel-ready)--spreadsheet per-wordDoneRewriter maps bare +d2 to --spreadsheet per-word (un-squatted from --format csv). Writes an aggregate SpreadsheetML file (stat.frq.xls), one row per (file x speaker) keyed by @ID, with per-word columns + Types/Token/TTR. Golden-proven (freq_d2_spreadsheet_manchester) as a documented divergence: byte-identical to CLAN’s cells except the %%mor->%mor caveat fix (CLAN-DIV-004). +d20 (one-row-per-speaker+word variant) is a separate Rewriter-only item.
+d20Spreadsheet with one row per speaker+word--spreadsheet per-speaker-wordDoneLanded 2026-06-04. CLAN isSpreadsheetOnePerRow + onlydata = 3 (freq.cpp:881-887): a flat stat.frq.xls with one row per (file, speaker, word), columns `File
+d3Spreadsheet, types/tokens/TTR only--spreadsheet summaryDoneRewriter maps bare +d3 to --spreadsheet summary (un-squatted from --types-tokens-only --format csv). Same SpreadsheetML file output as +d2 (stat.frq0.xls) restricted to Types/Token/TTR (no per-word or speaker pseudo-word columns). Golden-proven (freq_d3_spreadsheet_manchester), CLAN-DIV-004 divergence.
+d4Type/token info only--types-tokens-onlyDoneRewriter maps bare +d4. Per-speaker banner + separator + totals + TTR note all kept; per-word frequency lines dropped. +d3 (same content, CSV/spreadsheet form) is a separate item.
+d5Output +s words including those with 0 freq--include-zero-frequencyDoneLanded 2026-06-03. CLAN zeroMatch (freq.cpp:894): each LITERAL +s word is injected into every output speaker’s table at count 0 when it never matched (freq.cpp:1473-1491 via freq_tree_add_zeros, freq.cpp:1259, which adds only when absent). The zero word is DISPLAYED but excluded from types/tokens/TTR: +d5 +skept +szzz +t*SPE on *SPE shows 1 kept + 0 zzz yet Types=1, Tokens=1, TTR=1.000 (live CLAN probe). Single- and multi-word +s both inject (0 big dog). CLAN rejects wildcards (* % _) or duplicate +s words (freq.cpp:444, isFoundWildCard(TRUE)) and requires at least one +s word (freq.cpp:449); both guards are enforced at the FREQ dispatch (analysis.rs), mirroring +c2. Golden-proven by freq_d5_zerofreq_eng; the error and CLI paths are pinned by freq_d5_zerofreq_tests.
+d6Limited search-word surrounding context,MissingPI-gated (%mor replaced/error/POS tabulation per manual); freq.cpp:900-901 sets R5_1 when mwdptr == NULL. Now ERRORS fail-closed at the boundary; do not implement solo.
+d7Frequencies linked between dependent tier and speaker,MissingPI-gated (links a source tier to a target tier; overlaps KWAL/freqpos); freq.cpp:902-903 sets linkDep2Other. Now ERRORS fail-closed at the boundary; do not implement solo.
+d8Cross-tabulation of one dependent tier with another,MissingPI-gated (%mor cross-tab, overlaps mortable/freqpos); freq.cpp:895-896 sets isCrossTabulation. Now ERRORS fail-closed at the boundary; do not implement solo.
+dCNOutput words used by <, <=, =, =>, > than N percent of speakers (the spellings +d<N/+d<=N/+d=N/+d>=N/+d>N, plus the =</=> aliases)--speaker-percentage <spec>DoneLanded 2026-06-04. CLAN onlydata = 4, the percent-of-speakers filter (freq.cpp:841-878 parse; statfreq_percent_result at freq.cpp:2841 emits). The manual’s C (CLAN.html “+dCN”) is the comparator metavariable, not a literal C: percentC 1..5 for </<=(=<)/=/>=(=>)/> (freq.cpp:841-861); percent = atoi(N) (freq.cpp:876). Output shape (live-probed, NOT the +d2 per-word sheet the prior audit guessed): the +d3-shaped SUMMARY (no per-word columns), but each speaker’s Types/Token/TTR is recomputed over ONLY the kept words; written to words.frq.xls (a distinct filename from +d2’s stat.frq.xls / +d3’s stat.frq0.xls); and the fourth column header is Speaker, NOT +d2/+d3’s Code (freq.cpp:2874 vs the +d2/+d3 path). A word is kept iff its DISTINCT-SPEAKER count (number of (file x speaker) rows that used it, CLAN statfreq_AddWords p->count, freq.cpp:2756-2762) compares against percentNum = floor(num_rows * N / 100) (findPercentNum, freq.cpp:2664-2678). Rewritten from +d<=50 -> --speaker-percentage <=50 (a chatter-only flag name carrying the CLAN slot; faithfulness rule); the value parser rejects a missing/non-digit N (CLAN “Please specify percentage value”, freq.cpp:871-874); the +d5-combination and --spreadsheet-combination guards live at the FREQ dispatch (freq.cpp:867-870/890-893). Modeled as a typed FreqSpreadsheetMode::PercentOfSpeakers(SpeakerPercentFilter { comparison, percent }) (commands/freq/spreadsheet.rs), so the exhaustive-match discipline forced every spreadsheet consumer (renderer, filename, service) to handle it. DivergesFromClan (CLAN-DIV-004): the percent path re-emits the SAME %%mor TTR caveat as +d2/+d3 (the only difference); every data cell (the @ID columns, the Speaker header, the filtered Types/Token/TTR for both CHI and MOT) is byte-identical to CLAN’s words.frq.xls (live diff over all five comparators on manchester-anne +t*CHI +t*MOT). Golden freq_d_percent_lt_eq_manchester (+d<=50: CHI 0/0/- since all its words are shared with MOT; MOT 5/5/1.000); CLI paths pinned by freq_d_percent_lt_eq_writes_speaker_filtered_summary / freq_d_percent_gt_keeps_shared_words / freq_d_percent_rejects_d5_combination_and_missing_number; rewriter by freq_d_percent_maps_to_speaker_percentage; logic by percent_* unit tests.

General +-flags FREQ inherits (from cutt.cpp::mainusage)

CLAN flagMeaningChatterStatusNotes
+t*XInclude speaker *X--speaker XDone
-t*XExclude speaker *X--exclude-speaker XDone
+t%XInclude dependent tier %X--tier XDoneCounts the whitespace-delimited tokens of dependent tier %X (freq.cpp:914-938 case 't': nomain=TRUE, fDepTierName), modeled as CountSource::DependentTierTokens. A clitic `v
-t%XExclude dependent tier %X--exclude-tier XDoneThe EXCLUDE form flips FREQ to count the main tier PLUS every present dependent tier EXCEPT %X (freq.cpp case 't' tier-selection; manual “Limiting by including or excluding dependent tiers”; banner “ALL speaker tiers / and those speakers’ ALL dependent tiers EXCEPT …”), modeled as CountSource::MainPlusDependentTiersExcept and pooled into one table. A composition of the main-tier count and the +t%X per-tier count over all present tier kinds (each kind counted once); repeatable (-t%X -t%Y). The “%mor line forms” TTR advisory STAYS ON even when %mor is swept in: CLAN sets isMorUsed only for the explicit +t%mor include, not the -t sweep. Golden-proven by freq_neg_t_gra_eng (main + %mor) + freq_neg_t_mor_eng (main + %gra); CLI/guard by freq_t_tier_tests. Deferred as separate rows: the +t/-t combination state machine (an include and exclude together) and -t* (main-line exclusion); any --mor/--tier/--exclude-tier mix errors at dispatch.
+t@ID="..."Filter by @ID pattern--id-filterDoneWhole-string, case-insensitive *-wildcard glob over the raw @ID line (CLAN uS.patmat), NOT a field-by-field match: `*
+t#ROLEFilter by role--roleDoneFixed 2026-05-22. Rewriter routes +t#ROLE → --role ROLE; the per-utterance filter checks the speaker’s @ID: role field case-insensitively; banner-scope renders ONLY speaker main tiers with role(s): ROLE;.
+s"word" / +swordSearch for word (single or multi-word group)--include-wordDoneSingle-word per-word count golden-proven by freq_s_word_eng. Multi-word groups (a +s value with more than one word, e.g. +s"the hill") landed 2026-06-02 as Phase 1 of the multi-word search cluster: matched as an adjacent, in-order, non-overlapping sequence on the main tier (freq.cpp:2465-2548), counted once per occurrence under the search pattern. Built on the shared framework::multiword::MultiWordGroup primitive (whose matches() returns spans, so KWAL/COMBO reuse the same engine). Golden-proven by freq_s_multiword_eng; reversed/non-adjacent negatives pinned by freq_multiword_tests. The +c2..+c7 multi-word modes (any-order, sole-content, multiplicity, literal-wildcard) are the remaining phases.
-s"word" / -swordExclude word--exclude-wordDone
+s@F / -s@FSearch / exclude words listed in file F--include-word-file / --exclude-word-fileDoneLanded 2026-05-22. Universal across non-SCRIPT, non-COMBO commands. File format matches CLAN’s cutt.cpp::rdexclf: one pattern per line; blank lines, # -comments, and ;%* -annotation lines skipped; UTF-8 BOM stripped. Repeatable. Golden-proven by freq_s_include_word_file_eng / freq_neg_s_exclude_word_file_eng (byte-parity with CLAN’s +s@/-s@, including identical #-comment / blank-line skipping).
+gXInclude gem labelled X– (errors)Rewriter onlyCLAN FREQ has NO +g gem flag: freq +gX returns “Invalid option” (no case 'g' in freq.cpp). Gem-limiting in CLAN is the separate GEM program (gem +sX +d +f -> freq). chatter errors +gX/-gX as inapplicable (talkbank-clan/AGENTS.md), routing them to a reject sentinel. chatter’s --gem / --exclude-gem remain a chatter-only convenience (limit FREQ to a gem directly), reachable via the -- flag only, never via the CLAN +gX slot (faithfulness rule). (CLAN MLU/MLT DO accept +g, mapped to --exclude-solo-word.)
-gXExclude gem labelled X– (errors)Rewriter onlySee +gX: same inapplicable-flag rejection.
+rN (N=1..8, +r50)Word-form treatment for counting: parentheses / prosodic symbols / [: text] replacement / retracings / %mor-combine (NOT output formatting)--parenthesis-mode (+r1/+r2/+r3); --include-retracings (+r6); --replacement-mode (+r5); --prosody-mode (+r7)Partial (parens + retracings + replacement + prosody done)+r is a word-normalization parity cluster, not a cheap flag tail. Parsed at cutt.cpp:9530-9583 (needs R_OPTION); bare +r = +r1; CLAN errors “Choose N … between 1-7” for out-of-range N. Per sub-flag (manual §14.5 @ line 12379; source cutt.cpp): +r1/+r2/+r3 (omitted-material parentheses, Parans 1/2/3) DONE (landed 2026-06-04), with a default-parity FIX: CLAN’s DEFAULT is +r1 = remove parens, KEEP the omitted letters (bein(g) → being); +r2 keeps the parens literally (bein(g)); +r3 drops the omitted letters (bein). Live-probed on 1082.cha. chatter’s default previously diverged AND was internally inconsistent: the grouping key (cleaned_text(), Text+Shortening) was already +r1-correct (being), but the DISPLAY (framework::clan_display_form → Word::raw_text()) kept the parens (bein(g), i.e. +r2). Now a typed framework::ParenthesisMode (RemoveParens default / KeepParens / RemoveMaterial) drives BOTH the key (parans_normalized_key) and the display (parans_display), rendered AST-first from Word::content (only words containing a Shortening take the new path, so zero blast radius elsewhere, and no freq golden changed). Rewritten from +r1/+r2/+r3 via `–parenthesis-mode remove-parens
+zN-MUtterance range--rangeDone
+pSAdd S to word delimiters--word-delimiters SDoneLanded 2026-06-04. CLAN appends each non-space character of S to its global word-delimiter set and re-tokenizes (cutt.cpp:9798-9818; manual cutt.cpp:9204 “add S to word delimiters. (+p_ will break New_York into two words)”); FREQ enables P_OPTION (option_flags[FREQ] includes ALL_OPTIONS, cutt.cpp:8648). A counted word containing a delimiter is split at it and each piece is counted on its own; a trailing word-form marker (@o) stays on the FINAL segment (CLAN re-tokenizes the cleaned text, so the suffix rides its piece). Modeled as a reusable typed framework::WordDelimiters newtype (whitespace dropped on construction, !isSpace), threaded onto FreqConfig.word_delimiters and applied in count_main_tier AFTER the +r word-form treatment: when non-empty, the rendered display form is split on the delimiter chars and each non-empty segment is recorded (key + display), leaving the default path byte-identical (no existing golden moved). Rewritten from +pS -> --word-delimiters S (a chatter-only flag name; faithfulness rule); the empty form +p errors at the FREQ dispatch with CLAN’s “specify word delimiter characters” message (cutt.cpp:9802). MatchesClan: on word-features/000829.cha *MOT with +p_, choo_choo (x3) -> choo (6) and chup_chup_chup_chup@o (x2) -> chup (6) + chup@o (2); chatter’s full 79-line per-speaker output is byte-identical to CLAN’s (live diff). Golden freq_p_word_delimiter_mot; CLI paths pinned by freq_p_underscore_splits_joined_words / freq_default_keeps_underscore_joined_words / freq_p_empty_delimiters_errors; rewriter by freq_p_maps_to_word_delimiters; the split primitive by word_delimiters_split_behaviour. Scope: the +s/+c per-word filters still gate on the whole (pre-split) word, so +p combined with +s/+c is a documented deferral; dependent-tier (+t%X) splitting under +p is also not yet wired.
+f / +fEXTOutput to file with extension--output-ext (rewriter target)Rewriter onlychatter writes to stdout by default; sidecar-file pattern is Phase 1.1.
+uCombine across files (no per-file split)(default)Donechatter combines by default; --per-file opts in to per-file output. Inverse default vs CLAN: explicit +u is a faithful no-op. Proven by freq_combines_across_files_by_default_and_plus_u_is_a_noop; the combined CHI table is byte-identical to CLAN’s +0 +u (verified against OSX-CLAN/src/clan/freq.cpp). Structural flag (multi-file orchestration), so the proof is a subprocess test, not a single-file render golden.
+reRecurse subdirectories(default for directory args)Donechatter’s path argument accepts a directory and recurses by default; explicit +re is a faithful no-op. Proven by freq_recurses_subdirectories_by_default_and_plus_re_is_a_noop (a file in a nested subdir lifts the combined total from 4 to 8 tokens). Structural flag (directory traversal), so the proof is a subprocess test, not a single-file render golden.
+oS / -oSInclude / exclude extra output tier S– (errors)Done (rejects, matching CLAN)The “inherited” description is wrong for FREQ. FREQ OWNS case 'o' (freq.cpp:815-836): it is the SORT/output-mode flag (+o/+o0 -> --sort frequency, +o1 -> --sort reverse-concordance, +o3 -> --combine-speakers), and any other +o<x> falls into its else branch -> "Invalid argument for option" (freq.cpp:834). There is no “extra output tier” +oS form in FREQ; +o2 (reverse-concordance, documented “non-CHAT”, manual 5604) and +oCHA both error. chatter rejects every non-sort +o form at the fail-closed boundary, matching CLAN’s rejection. Pinned by freq_rejects_non_sort_o_forms (inapplicable_flag_tests.rs).
+x C N UInclude only utterances whose length is C (>/</=) than N items of unit U--utterance-length (rewritten from +x…w/+x…c/+x…m)PartialWord (w), char (c), and morpheme (m) units done (manual 6405; cutt.cpp:16508 word, cutt.cpp:16343 char, cutt.cpp:16409 morpheme). +x>3w keeps utterances with >3 countable words; +x>20c keeps those with >20 main-tier characters; +x=5m keeps those with exactly 5 traced morphemes. All three are the reusable FilterConfig::utterance_length gate carrying a typed CountUnit axis (w/c/m), not a scalar suffix. The morpheme unit counts §7.21-traced morphemes via the shared framework::count_traced_morphemes_in_utterance (the SAME counter MLU uses), so it is correct on UD %mor including the present participle -Ger. DivergesFromClan (two CLAN defects, see field guide): CLAN’s +x…m (CntFUttLen==2) over-counts (its raw ismorfchar delimiter walk treats UD features like Past/S3 as separate morphemes) AND doubles FREQ’s output (it leaks the %mor tier into the harvest, +x>0m makes *SPE 15→30, emitting both Triangle and noun|triangle), neither sanctioned by manual 6405. chatter filters by the correct count and emits normal FREQ output. Pinned by freq_x_morpheme_filter_keeps_matching_utterances (-Ger-sensitive); word/char by freq_x_wordlen_eng/freq_x_charlen_eng. The shared counter also corrected MLU’s matching -Ger undercount. Content-specification forms +xS/-xS (manual 6405; wdUttLen/filterwords/excludeUttLen, cutt.cpp:5380,5421,16340): probe-confirmed that they tune only the +x LENGTH count, not FREQ’s word output (+x>0w +xxxx makes a 2-word xxx utterance count 3 yet xxx stays out of the output). -xS (exclude) DONE for word/char units: removes word S from the length count, modeled as UtteranceLengthFilter::exclude_from_count (WordPattern/word_pattern_matches, the +s matcher); rewritten from -x<word> via --utterance-length-exclude. Pinned by freq_x_exclude_word_from_length_count (+x>3w -xup drops *GES’s “twirled up the hill”, GES 10→6). +xxxx/+xyyy/+xwww (unintelligible-marker restore) DONE as a third DivergesFromClan (CLAN-DIV-005): by default the count strips xxx/yyy/www; these flags re-include them in the length count (rewritten to --utterance-length-restore <marker>, folded into a typed RestoreMarkers set on the filter). chatter restores UNCONDITIONALLY through the shared AST walker framework::words_for_utterance_length, so restored markers obey the same group-recursion / retrace rules as countable words. CLAN’s restore is a byte-position bug: correctForXXXYYYWWW (cutt.cpp:16260-16311) advances its scan index i += 2 once per marker check (xxx, then yyy, then www) plus the for-loop’s i++ = a stride of 7, so it only ever inspects xxx at byte offsets ≡ 0 (mod 7), yyy at ≡ 2, www at ≡ 4. Whether a marker restores therefore depends on its byte position in the cleaned line, contradicting manual 6405’s unconditional-restore intent (verified by a 7-utterance probe: xxx restored only at offset 7, not at offsets 2-6 or 8). On 1082.cha +x=4w +xxxx, chatter’s correct restore lifts <we xxx bein(g) in Rochester> [?] from 4 to 5 words and drops it (*CHI 94 tokens); CLAN’s stride bug leaves that xxx un-restored and keeps the utterance (*CHI 98). Pinned by freq_x_restore_xxx_into_length_count + freq_x_restore_xxx_diverges_from_clan_byte_stride_bug; the default-strip control is freq_x_default_strips_xxx_from_length_count. -x@FILE (exclude-from-file) DONE: loads the exclude word list from a file (rdexclfUttLen('e', …), cutt.cpp:5384; same @FILE idiom as -s@F), folded into the same exclude_from_count; rewritten via --utterance-length-exclude-file. Pinned by freq_x_exclude_words_from_file (a one-line up list reproduces -xup, GES 10→6). +xWORD/+x@FILE (general include) ESCALATED (maintainer-report item), fail-closed: the manual (cutt.cpp:9886 usage text) calls +xWORD “count only this word”, but the binary’s excludeUttLen (cutt.cpp:5421) default-counts every unmatched word, so the include list is a near-no-op that only bites as an exception to an overlapping exclude pattern, with an arbitrary descending-alphabetical precedence (InsertUttLenWord, cutt.cpp:5326). The manual intent contradicts the binary’s behavior, so the correct semantic needs a maintainer call (bucket-3 escalation); kept fail-closed (freq_x_include_forms_fail_closed) pending it. The row stays Partial only on this one escalated sub-form; everything else implementable is done.
+kCase-fold toggle: FREQ preserves case by default, +k folds to lowercase--plus-k (carries +k)DoneFREQ is in CLAN’s mmaininit nomap=TRUE set (cutt.cpp:7845), so it PRESERVES case by default; +k TOGGLES nomap (cutt.cpp:13816) to fold to lowercase, so Want/want/WANT collapse to one entry and the displayed word is lowercased (freq.cpp:1892-1909). This is the INVERSE of the fold-by-default commands (KWAL/COMBO/FREQPOS/DIST/MAXWD); chatter sets FREQ’s keying preserve-state to !(+k present). Pinned by freq_default_preserves_case_variants, freq_plus_k_folds_case_variants, and the freq_k_folds_case_eng golden.
+wN / -wNContext window (KWAL/COMBO keyword-context)–Rewriter onlyInapplicable to FREQ (per-word frequency totals, no per-match context to surround). The rewriter maps +wN/-wN to --context-after/--context-before, but FREQ has no such clap field, so it errors at parse time, the correct outcome for an inapplicable flag (talkbank-clan/AGENTS.md). CLAN’s binary instead empties the output (a context-machinery artifact).
+y / +yNTreat input as NON-CHAT plain text (so FREQ “sees” header / non-tier lines)– (errors)Done (rejects, inapplicable)The audit’s “include all utterances including non-tier” gloss was imprecise. CLAN’s +y sets chatmode = 0 (cutt.cpp:9834), switching FREQ to analyze the input as raw plain text rather than parsed CHAT (manual 5044-5047: freq +y +s"\**:" *.cha to count header lines); +yN (N=0/1) picks line-vs-utterance granularity for that raw mode (cutt.cpp:9848) and only fires when !chatmode. On a CHAT file this empties the normal FREQ output (verified: freq +y +t*MOT yields no per-speaker body), exactly the +w shape, a flag whose machinery makes FREQ produce nothing useful for the typed-CHAT case. chatter is CHAT-only with no raw-text mode, so +y is inapplicable; per the inapplicable-flags rule (talkbank-clan/AGENTS.md) chatter rejects it rather than fabricate a non-CHAT mode or reproduce empty output. CLAN also errors +y with +/-t (if -t precedes it), -u, or +d2/+d3 (cutt.cpp:9822-9833). Pinned by freq_rejects_non_chat_mode_y_flag.

Audit summary

BucketCount
Done (byte-parity or in scope)27
Partial (chatter abstraction differs, MOR/cross-tier sub-flags deferred)3
Rewriter only (would error at parse time)12
Deferred (scope-gated: MOR / cross-tier / non-CHAT / escalated / infra)6
Missing (no rewriter, no source-grounded reason yet)0

FREQ is depth-complete (2026-06-04). Every FREQ flag-row is now in one of: Done (byte-parity, or rejects-matching-CLAN for inapplicable flags), Partial (a chatter abstraction differs, with the residual sub-flags themselves deferred-with-reason), Rewriter only (errors at parse, the correct outcome for an inapplicable flag), or Deferred (scope-gated with a source-grounded reason: PI / %mor / cross-tier decisions, flags that switch CLAN to a non-CHAT raw-text mode chatter has no analog for, a manual-vs-binary contradiction escalated to the maintainer, or output-routing infra). There are zero rows left “Missing” without a source-grounded reason. The deferred rows are consolidated for the maintainers in the FREQ porting report. The deferred set: +d0/+d6/+d7/+d8 and bare +d (concordance / %mor / cross-tabulation), +r8/+r50 (%mor / linked-tier), +c5 (gated on +d7), +c6 (CA repeat-segment, needs a parser span type), +a (typeForms, manual-unclear + MOR-coupled), +xWORD/+x@FILE (manual-vs-binary contradiction), +f/+fEXT (sidecar-file output infra).

Resolved 2026-06-04 (fail-closed boundary). The former “Rewriter only” hazard, a CLAN user pasting freq +d20 file.cha getting silent default output, is closed. Any +/- token that no rewriter arm consumes (+d20, +d8, +QQQ, …) now ERRORS at the shared file-discovery boundary (DiscoveredChatFiles::into_files, talkbank-clan/src/framework/input.rs) with Error: unrecognized option(s): '+d20' (a '+'/'-' argument is a CLAN flag, not a file), rather than being collected as a bogus positional file and warn-skipped to a default-output exit 0. This fixed a systemic fail-open hole across every chatter-clan command at once; see the parity field guide. The remaining +d rows above are tracked individually for per-row TDD implementation (several PI-gated). The per-category counts above are hand-maintained and superseded by the generated golden-parity metric on the parity status page.

Confirmed-broken invocations (2026-05-21)

These were exercised end-to-end during the audit and produced wrong output for a CLAN-equivalent invocation:

InvocationWhat chatter doesWhat CLAN does
chatter-clan freq +d2 file.chafixed 2026-06-02: +d2 writes an aggregate SpreadsheetML file (stat.frq.xls); see the +d2/+d3 rows abovespreadsheet output
chatter-clan freq +k file.chafixed: +k rewrites to --plus-k (case-fold toggle; see the +k row above)case-sensitive search
chatter-clan freq +t%mor file.chafixed 2026-06-03: +t%mor rewrites to --tier mor and counts the %mor tier’s tokens (see the +t%X row above)analyses %mor dependent tier
chatter-clan freq +tCHI file.cha (no *)fixed 2026-05-21: +tCHI and -tMOT now rewrite identically to +t*CHI / -t*MOTidentical to +t*CHI (silently prepends the *)

The +tCHI case was a clan_args.rs::rewrite_tier_speaker gap: the function required the first byte of rest to be *, %, or @, and fell through to None otherwise. The default branch now treats +t<word> as an implicit speaker code, matching CLAN’s behaviour exactly. Closed in commit landed alongside this audit, with two new unit tests (speaker_include_no_asterisk, speaker_exclude_no_asterisk) in clan_args::tests.

CLAN Equivalence

CLAN commandRust equivalent
freq file.chachatter-clan freq file.cha
freq +t*CHI file.chachatter-clan freq file.cha --speaker CHI
freq +s"the" file.chachatter-clan freq file.cha --include-word "the" (case-sensitive by default; +k folds matching and keys, see the +k row above)
freq *.chachatter-clan freq corpus/

Display Modes (+dN / --display-mode N), DRAFT, awaiting PI review

Status: partially implemented. +d is not a single scalar “display mode”: CLAN’s case 'd' (freq.cpp:838-913) overloads the prefix onto several independent state variables (onlydata, zeroMatch, isCrossTabulation, isSpreadsheetOnePerRow, the percentC/percent filter, …). Each is rewritten to its own chatter flag, NOT a generic --display-mode N. Done: +d1 (--word-list-only), +d2/+d3 (--spreadsheet per-word/summary), +d4 (--types-tokens-only), +d5 (--include-zero-frequency, zeroMatch), +d20 (--spreadsheet per-speaker-word), and the +dCN percent-of-speakers filters (--speaker-percentage <spec>, e.g. +d<=50; see the +dCN row above). Remaining: +d0 (concordance), +d6/+d7/+d8 (%mor / cross-tier), and bare +d. The per-N table below quotes CLAN manual §7.10.15 verbatim; the open questions that follow are the genuinely PI-gated scope decisions for the remaining rows. As of 2026-06-04 every not-yet-implemented +d form (bare +d, +d0, +d6/+d7/+d8) ERRORS fail-closed at the file-discovery boundary rather than silently producing default output; implementing each is its own per-row TDD. Note CLAN source treats bare +d identically to +d0 (onlydata = 1, cutt.cpp:9402), which the manual’s “+d = no-flag default” line below contradicts: reconcile before implementing either.

FREQ uses +d to switch output format, not to vary verbosity. Each value of N selects a different report shape. Quoted from CLAN manual §7.10.15:

NCLAN behavior (verbatim from manual)
+d (no number)“Perform a particular level of data analysis. By default, the output consists of all selected words found in the input data file(s) and their corresponding frequencies.” (Equivalent to no-flag default.)
+d0“Output provides a concordance with the frequencies of each word, the files and line numbers where each word, and the text in the line that matches.”
+d1“Outputs each of the words found in the input data file(s) one word per line with no further information about frequency. Later this output could be used as a word list file for kwal or combo programs.”
+d2“Output is sent to a file in a form that can be opened directly in Excel. To do this, you must include information about the speaker roles you wish to include in the output spreadsheet.” (Manual example: `freq +d2 +t@ID=“*
+d3“Essentially the same as that for +d2, but with only the statistics on types, tokens, and the type-token ratio. Word frequencies are not placed into the output.” (Note: +d2 and +d3 assume +f; no need to pass it explicitly.)
+d4“Allows you to output just the type-token information.”
+d5“Output all words you are searching for, including those that occur with zero frequency. … Can be combined with other +d switches.”
+d6“When used for searches on the main line, outputs matched forms with a separate tabulation of replaced forms, errors, partial omissions, and full forms.” Also +d6 +sm|n*,o% on %mor line: produces separate counts per part-of-speech instantiation.
+d7“Links forms on a ‘source’ tier with their corresponding words on a ‘target’ tier.” Default source is %mor; pass a tier name to change source. Items on the two tiers must be in one-to-one correspondence. +c5 swaps source ↔ target.
+d8“Outputs words and frequencies of cross tabulation of one dependent tier with another.”

Open questions for PI review

  1. +d0: emits a concordance, overlaps with KWAL semantically. Should chatter’s freq --display-mode 0 reuse the kwal output path internally, or produce its own concordance shape?
  2. +d1: word-list output suitable as input to kwal +s@file. Should the file be auto-named (<basename>.fre?) or printed to stdout by default?
  3. +d2/+d3: “form that can be opened directly in Excel” maps to --format csv in chatter. Is this duplication acceptable, or should --display-mode 2 imply --format csv (and conflict-error otherwise)?
  4. +d4: “type-token information only”, same content as the existing text/json default, minus the word frequencies. Add a new Truncated variant to the output struct, or emit a CSV row with just types/tokens/TTR?
  5. +d5: combinable with other +d values. How should this combine in clap, a Vec<DisplayMode> rather than scalar Option<u8>?
  6. +d6/+d7/+d8: deeply specific to %mor and cross-tier tabulation. Are these in scope for chatter’s freq, or are they future work (probably alongside or instead of mortable / freqpos)?

The +dCN form (“output only words used by <, <=, =, => or > than N percent of speakers”) is implemented (2026-06-04; see the +dCN row in the flag table above). The manual’s C is the comparator metavariable (</<=/=/>=/>), not a literal capital C: CLAN’s source has no case 'C', only the </=/> parse at freq.cpp:841-861. The rewriter maps +d<=50 -> --speaker-percentage <=50 (its own clap field, not an overload of --display-mode).

Output

Per-speaker frequency tables with:

  • Word frequency counts (sorted by count descending, then alphabetically)
  • Total types (unique words) and tokens (total words)
  • TTR (type-token ratio = types / tokens)

Example output (text)

Speaker: CHI
  the       12
  I         8
  want      6
  a         5
  go        4
  ...
Types: 45
Tokens: 127
TTR: 0.354

Example output (JSON)

{
  "speakers": {
    "CHI": {
      "words": { "the": 12, "I": 8, "want": 6, ... },
      "types": 45,
      "tokens": 127,
      "ttr": 0.354
    }
  }
}

Word Normalization

Words are grouped using NormalizedWord, which lowercases and strips compound markers (+) for counting purposes, while preserving the original CLAN display form (with +) for output. This means wanna+go and Wanna+Go are counted as the same word.

Differences from CLAN

Word identification

The legacy manual says FREQ ignores xxx, www, and words beginning with 0, &, +, -, or # by default, and also ignores header and code tiers unless selected. CLAN implements much of this with character-level string-prefix matching:

if (word[0] == '0') continue;     // omitted words
if (word[0] == '&') continue;     // fillers/nonwords
if (word[0] == '+') continue;     // terminators

Our implementation uses AST-based is_countable_word(), which checks semantic type rather than string prefixes. This is more precise – a filler (&-um) and a phonological fragment (&+fr) have distinct semantic types in our model, even though CLAN lumps them together under the & prefix.

Manual features not yet mirrored directly

The legacy manual documents several advanced FREQ workflows, including +s@file lexical-group lists, %mor/%gra combined search with +d7, and multilingual searches. Some of those behaviors are covered in talkbank-clan through broader filtering infrastructure, but the command chapter should not imply one-for-one flag parity unless explicitly implemented.

Output ordering

Output is deterministic via sorted collections (count descending, then alphabetically). CLAN’s ordering can vary across runs.

Output formats

Supports text, JSON, and CSV formats. CLAN produces text only. Use --format clan for character-level CLAN-compatible output.

Multi-file behavior

Results are merged across files by default (+u behavior). CLAN requires explicit +u flag. Use chatter-clan freq dir/ for recursive directory traversal (CLAN uses shell globs).

Golden test parity

Verified against CLAN C binary output. 100% parity.

FREQPOS, Word Frequency by Position

Status: Current Last updated: 2026-05-26 08:21 EDT

Purpose

Counts how often each word appears in initial, final, other (middle), or one-word positions within utterances. FREQPOS is part of the FREQ family of commands and is useful for studying positional word preferences – for example, whether a child tends to place certain words at the beginning or end of utterances.

Position Classification

  • Initial: first word of a multi-word utterance
  • Final: last word of a multi-word utterance
  • Other: any middle word of a multi-word utterance (3+ words)
  • One-word: the sole word in a single-word utterance

Usage

chatter-clan freqpos file.cha
chatter-clan freqpos file.cha --speaker CHI

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN freqpos flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/freqpos.cpp: usage() and getflag().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() FREQPOS branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Freqpos plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

FREQPOS has the narrowest command-specific flag set of any CLAN analysis tool: just two flags beyond the general inherited set.

FREQPOS-specific +-flags (from freqpos.cpp::getflag)

CLAN flagMeaningChatterStatusNotes
+dUse first / second / other classification instead of first / last / other--position-classification <last|second>DoneLanded 2026-05-23. FreqposConfig::position_classification (enum FirstLastOther / FirstSecondOther) gates the per-utterance classification: with +d, position 1 becomes the “second” slot and positions ≥ 2 go to “other”; without +d, position len-1 is “final” and middle positions are “other”. render_clan swaps the column header (final = ↔ second =) and footer label to match. Pinned by freqpos_second_mode_reclassifies_position_one, freqpos_default_mode_keeps_final_label, and rewriter tests freqpos_second_mode_classification + freq_d_bare_does_not_match_position_classification (scope-narrowing). The generic +dN rewrites for FREQPOS are tracked separately under “Display Modes”.
+gS / +g@SDisplay only word(s) S (or words in file @S)--gemPartialThe FREQPOS +g flag means display only certain words, a vocabulary filter, whereas the inherited --gem is the gem-segment filter. Identical syntax, different semantics, like the +g overload in MLU / MLT.

General +-flags FREQPOS inherits (from cutt.cpp::mainusage)

CLAN flagMeaningChatterStatusNotes
+t*X / -t*XInclude/exclude speaker--speaker / --exclude-speakerDone+tX accepted post-2026-05-21.
+t%X / -t%XInclude/exclude dependent tier--tier / --exclude-tier (rewriter target)Rewriter only
+t@ID="..."Filter by @ID pattern--id-filterDone
+t#ROLEFilter by role--roleDoneFixed 2026-05-22; see FREQ for the shared implementation.
+s"word" / -s"word"Include/exclude word--include-word / --exclude-wordDonexxx/yyy/www are excluded by default (init-time addword).
+s@F / -s@FSearch / exclude words from file--include-word-file / --exclude-word-fileDoneLanded 2026-05-22. File format: one pattern per line; blank lines, # -comments, and ;%* -annotation lines skipped. Repeatable.
+gX(in FREQPOS: vocabulary filter, see above)--gemPartialOverloaded.
+zN-MUtterance range--rangeDone
+rNRetrace / clitic / prosodic controls--include-retracings (+r6)Partial
+uCombine across files(default)DoneInverse default vs CLAN.
+reRecurse(default)Done
+pSWord delimiter,Missing
+kCase-sensitive--case-sensitiveDoneLanded 2026-05-23. Reads CommonAnalysisArgs::case_sensitive. process_utterance picks the key derivation: default uses NormalizedWord::from_word (lowercased), +k uses NormalizedWord(cleaned_text().to_owned()) (case-preserving) so Want/want/WANT land in separate by-word entries. Pinned by freqpos_case_sensitive_splits_case_variants and freqpos_default_collapses_case_variants.
+wN / -wNContext window (KWAL/COMBO keyword-context)–Rewriter onlyInapplicable to FREQPOS (positional frequency tables, no per-match context to surround). The rewriter maps +wN/-wN to --context-after/--context-before, but FREQPOS has no such clap field, so it errors at parse time, the correct outcome for an inapplicable flag (talkbank-clan/AGENTS.md). CLAN’s binary instead empties the output (a context-machinery artifact).
+f / +fEXTOutput to file--output-ext (rewriter target)Rewriter onlyPhase 1.1.

Audit summary

BucketCount
Done (byte-parity or in scope)10
Partial2
Rewriter only2
Missing3

The +gS overload (FREQPOS: vocabulary filter; inherited: gem filter) deserves the most attention before this command’s body parity can be claimed complete. Same overload as MLU and MLT, tracked as a Phase 1.7 follow-up.

Display Modes (+dN / --display-mode N), DRAFT, awaiting PI review

Status: drafted from CLAN manual; not yet implemented. Rewriter at crates/talkbank-clan/src/clan_args.rs:101 translates +dN → --display-mode N; no clap field consumes it today. Drafted from CLAN manual §7.12.1 (Unique Options, FREQPOS) for PI review.

NCLAN behavior (verbatim from manual)
+d (no number)“Count words in either first, second, or other positions. The default is to count by first, last, and other positions.”

Open questions for PI review

  1. FREQPOS’s +d switches the position-classification scheme from “first / last / other / one-word” (default) to “first / second / other”. That’s not a display change; it’s a bucketing change. Map to --positions <first-last|first-second> enum rather than --display-mode.
  2. If we keep the --display-mode translation, +d (no number) corresponds to a single behavior (the alternative bucketing), so --display-mode 0 is the only valid value. The clap field should probably be an enum with two variants (Default, FirstSecondOther), not a numeric Option<u8>.

Output

Global word list (sorted alphabetically by display form) with positional breakdown (initial/final/other/one-word counts per word), followed by aggregate position totals.

Differences from CLAN

  • Word identification uses AST-based is_countable_word() instead of CLAN’s string-prefix matching
  • Position classification operates on parsed AST word lists rather than raw text token splitting
  • Output supports text, JSON, and CSV formats (CLAN produces text only)
  • Deterministic output ordering via sorted collections
  • Golden test parity: Verified against CLAN C binary output

GEM – Extract Gem Segments

Status: Current Last updated: 2026-05-26 11:24 EDT

Purpose

Extracts material within gem boundaries. The legacy manual gives GEM a dedicated section; in talkbank-clan, it extracts utterances and their dependent tiers that fall within @Bg/@Eg gem boundaries, producing a new CHAT file containing only the gem-scoped content.

See the CLAN manual for the original GEM command specification.

Usage

chatter-clan gem file.cha
chatter-clan gem --gem story file.cha

CLAN Equivalence

CLAN commandRust equivalent
gem file.chachatter-clan gem file.cha
gem +g"story" file.chachatter-clan gem --gem story file.cha

Options

OptionCLAN FlagDescription
--gem <LABEL>+g"label"Extract only gem segments matching this label

Without --gem, all gem segments in the file are extracted.

CLAN +-flag coverage audit

GEM is a transform (input CHAT → output CHAT containing only gem segments). Sources: OSX-CLAN/src/clan/gem.cpp::usage, crates/talkbank-clan/src/transforms/gem.rs.

GEM-specific +-flags (from gem.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aOutput all tiers but the gems themselves (default: gem-only),MissingInverse extraction mode.
+bOutput beg-bullet value of first speaker utterance in gem,MissingBullet-output addition.
+eDo not output nested gems with the matched one,MissingSame +e semantic as in GEMFREQ.
+g (no S)Marker tier should contain all words specified by +s,MissingEVAL-style +g overload.
+gSRestrict to gem labelled S--gem <LABEL>Done
+nEach gem terminated by next @G,MissingSame gem-termination semantic as in EVAL/COREELEX/FLUCALC.
+dNOutput-format variants (from manual §7.13),MissingHybrid consumption per OSX-CLAN/src/clan/gem.cpp:130: +d2 is a local override (onlySelectedBG_EGHeaders = TRUE); every other +dN value delegates to maingetflag at cutt.cpp:9382 (empty per-program body at cutt.cpp:9470) setting the shared onlydata output-detail level. chatter has neither consumer. Per-GEM rewriter arm in clan_args.rs passes the token through so clap reports the literal +dN argument rather than the misleading --display-mode rewrite.

Audit summary

BucketCount
Done1
Rewriter only3
Missing7

GEM’s command-specific gaps overlap heavily with GEMFREQ’s: both the +e nested-gem and +n termination toggles are missing in both. A shared “gem-segment scoping” config could close both commands’ gaps at once; filed as a Phase 1.7 follow-up.

Display Modes (+dN / --display-mode N), DRAFT, awaiting PI review

Status: drafted from CLAN manual; not yet implemented. Rewriter at crates/talkbank-clan/src/clan_args.rs:101 translates +dN → --display-mode N; no clap field consumes it today. Drafted from CLAN manual §7.13 (GEM, in-section +d note) for PI review.

NCLAN behavior (verbatim from manual)
+d0“Produces simple output that is in legal chat format.”
+d1“Adds information to the legal chat output regarding file names, line numbers, and @ID codes.”

Open questions for PI review

  1. GEM is a transform command in chatter (writes a new CHAT file). +d0 “legal CHAT format” is GEM’s default behavior in chatter , so --display-mode 0 would be a no-op. Should the flag error on --display-mode 0 (already-default), accept it silently, or simply not be plumbed for GEM at all?
  2. +d1 adds filenames/line numbers/@ID codes, that’s annotation metadata not normally in a CHAT file. Map to a separate --annotate boolean rather than --display-mode 1?

Behavior

The transform scans for @Bg: (begin gem) and @Eg: (end gem) header boundaries. All utterances between a matching @Bg/@Eg pair are included in the output, along with their dependent tiers. The gem boundary headers themselves are preserved. File-level headers and participant metadata are carried through unchanged.

Differences from CLAN

  • Gem boundary detection operates on parsed Header variants from the AST rather than raw text line matching for @BG:/@EG:.
  • Handles both @Bg:/@Eg: (mixed case) and @BG:/@EG: (uppercase).
  • Without --gem filter, extracts all gem segments. With --gem, extracts only matching labels.

GEMFREQ – Word Frequency Within Gem Segments

Status: Current Last updated: 2026-05-27 10:45 EDT

Purpose

Computes word frequency restricted to utterances inside @G:-labeled gem segments. gemfreq is a CLAN compatibility alias for the more general freq --gem. The behavior is identical to running freq with a required --gem filter; the alias exists so legacy CLAN scripts that invoke gemfreq directly keep working.

The legacy CLAN manual entry is at GEMFREQ.

Usage

gemfreq requires the --gem/-g option; there is no implicit “all gems” mode (unlike freq, where --gem is optional).

chatter-clan gemfreq --gem story file.cha
chatter-clan gemfreq -g story file.cha               # short form
chatter-clan gemfreq --gem story --gem retell file.cha   # multiple gems

Options

The flag set is identical to freq: --mor, --speaker / --exclude-speaker, --include-word / --exclude-word, --exclude-gem, --range, --per-file, --include-retracings, --format, plus the universal verbosity / TUI / theme flags.

The only behavioral difference is that gemfreq rejects invocations without at least one --gem/-g argument; freq treats --gem as an optional restriction.

For full per-flag descriptions, output formats, word-normalization rules, and CLAN-equivalence tables, see freq.md.

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN gemfreq flag. Sources:

  • OSX-CLAN/src/clan/gemfreq.cpp: usage().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() GEMFREQ branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • chatter’s gemfreq is wired as an alias for freq --gem, the clap field surface is FREQ’s.

(Status legend: same as FREQ.)

GEMFREQ-specific +-flags (from gemfreq.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+eDo not output nested gems along with the matched one,MissingGem-nesting handling.
+g (no S)Marker tier should contain all words specified by +s,MissingEVAL-style +g overload.
+nEach gem terminated by the next @G,MissingGem-termination semantic switch.
+oSort output by descending frequency(default)DoneCLAN: gemfreq.cpp:260 (isSort = TRUE; no_arg_option(f)). chatter’s gemfreq (compatibility alias for freq --gem) already sorts by descending frequency by default, so +o is semantically a no-op. Per-GEMFREQ rewriter arm in clan_args.rs consumes-and-drops +o so it doesn’t fall through to the positional <PATH> slot.
+wS / +w@SSearch for word S (or words in file @S)--include-wordPartialFile-list form missing.
-wSExclude word S--exclude-wordDoneCLAN: gemfreq.cpp:296 (case 'w': *(f-1) = 's' rewrites the flag from w to s then calls maingetflag, so CLAN’s -wS is the standard exclude-word semantic). Per-GEMFREQ rewriter arm in clan_args.rs routes -wS → --exclude-word S to match CLAN’s polarity. Without this arm, chatter’s clap -w short (--include-word) would silently mis-route the flag to include-word (OPPOSITE polarity from CLAN). Pinned by gemfreq_minus_w_routes_to_exclude_word.
+yNDisplay whole tier unchanged (1) or cleaned up (0),Missing
+dNonlydata output-detail level (manual lists +d0 legal CHAT, +d1 with line/file/@ID info),MissingOSX-CLAN/src/clan/gemfreq.cpp has no local case 'd'; consumption is entirely via the shared maingetflag path at cutt.cpp:9382 (empty per-program body at cutt.cpp:9471) setting the onlydata level. chatter’s gemfreq clap surface has no --display-mode consumer. Per-GEMFREQ rewriter arm in clan_args.rs passes the token through so clap reports the literal +dN argument rather than the misleading --display-mode rewrite.

Audit summary

BucketCount
Done6
Partial2
Rewriter only4
Missing9

The +g / +n / +yN cluster are GEMFREQ’s most distinctive gaps: they control gem-segment scoping (nested gems, termination semantic, raw-vs-cleaned text output) and have no chatter analog. Most users will be served by the simple gemfreq --gem LABEL form already wired through the FREQ alias.

Display Modes (+dN / --display-mode N), DRAFT, awaiting PI review

Status: drafted from CLAN manual; not yet implemented. Rewriter at crates/talkbank-clan/src/clan_args.rs:101 translates +dN → --display-mode N; no clap field consumes it today. Drafted from CLAN manual §7.14 (Unique Options, GEMFREQ) for PI review.

Important divergence flag. In CLAN, GEMFREQ’s +d table is identical to GEM’s (legal CHAT format + annotation), not identical to FREQ’s (output format selector with 9 values). chatter’s gemfreq currently inherits the freq common-args, so any --display-mode N implementation has to decide which semantics apply, and that’s worth pulling apart before clap touches it.

NCLAN behavior (verbatim from manual)
+d0“Produces simple output that is in legal chat format.”
+d1“Adds information to the legal chat output regarding file names, line numbers, and @ID codes.”

Open questions for PI review

  1. GEMFREQ in CLAN borrows GEM’s +d, not FREQ’s. Should chatter follow CLAN’s CLAN-faithful behavior (treat --display-mode 0 as the GEM-style legal-CHAT output), or should the chatter gemfreq inherit FREQ’s --display-mode table (since they share common-args)?
  2. If we honor CLAN’s split, gemfreq is the only analyze command whose +d differs from its lexically-similar parent. That feels like a CLAN historical accident worth deviating from in chatter, but it’s a deviation, not a faithful port.

When to use gemfreq vs freq --gem

Functionally these are the same call. Pick gemfreq when:

  • you are porting a legacy CLAN script that invokes gemfreq and want byte-compatible-looking command lines, or
  • you want the command name to surface “gem-restricted” intent immediately to readers of the script.

Pick freq --gem story when:

  • you are writing new scripts that may need to mix gem-restricted and unrestricted analysis under the same command, or
  • you want to omit --gem to fall back to whole-file frequency.

Reference

Implementation: Gemfreq is a separate clap subcommand variant in the ClanCommands enum (not a #[command(alias = "...")]); the required --gem constraint is enforced via a clap ArgGroup with required(true). The dispatcher at crates/talkbank-cli/src/commands/clan/compatibility.rs::96 routes the parsed arguments to run_analysis_and_print with AnalysisCommandName::Freq, so behavior past the parse boundary is identical to a freq --gem … invocation. See freq.md for the complete reference.

GEMLIST, List Gem Segments

Status: Current Last updated: 2026-05-22 13:45 EDT

Purpose

Lists all gem segments (@Bg/@Eg bracketed regions) found in CHAT files, reporting the label, utterance count, and participating speakers for each gem.

See the CLAN manual for the original GEM command specification.

Usage

chatter-clan gemlist file.cha
chatter-clan gemlist file.cha --speaker CHI

Options

OptionCLAN flagDescription
--speaker <code>+t*CODERestrict to specific speaker
--format <fmt>,Output format: text, json, csv

CLAN +-flag coverage audit

GEMLIST is an analysis command. Sources: OSX-CLAN/src/clan/gemlist.cpp::usage, crates/talkbank-clan/src/commands/gemlist.rs.

GEMLIST-specific +-flags (from gemlist.cpp::usage)

CLAN flagMeaningChatterStatus
-wSExclude tiers with postcodes S,Missing

Audit summary: 1 Done (default gem listing), 1 Missing. chatter’s GEMLIST surfaces gem labels and per-gem statistics without a postcode-exclusion filter. The general CommonAnalysisArgs set is inherited.

Output

Per gem label:

  • Number of utterances within the gem scope
  • Number of occurrences (how many @Bg/@Eg pairs with this label)
  • Speakers who produced utterances within the gem
  • Source files containing this gem

Implementation Note

Gem boundaries (@Bg/@Eg) are interleaved headers in ChatFile.lines. Since the parser does not populate Utterance.preceding_headers, this command scans the full line array in end_file() rather than relying on per-utterance callbacks.

Differences from CLAN

  • Gem boundary detection operates on parsed Header variants from the AST rather than raw text line matching
  • Output supports text, JSON, and CSV formats (CLAN produces text only)
  • Deterministic output ordering via sorted collections
  • Golden test parity: Verified against CLAN C binary output

INDENT – Align CA Overlap Markers

Status: Current Last updated: 2026-05-22 13:03 EDT

Purpose

Aligns overlap markers in Conversation Analysis (CA) transcripts. The legacy manual describes INDENT simply as a program for realigning overlap marks in CA files, and notes that the files must use a fixed-width font such as CAFont.

talkbank-clan aligns closing overlap markers (⌊, U+230A) by column position with their matching opening overlap markers (⌈, U+2308) on a preceding speaker tier.

Usage

chatter-clan indent file.cha
chatter-clan indent file.cha -o aligned.cha

CLAN +-flag coverage audit

INDENT is a transform. Sources: OSX-CLAN/src/clan/indent.cpp::usage, crates/talkbank-clan/src/transforms/indent.rs.

CLAN’s indent.cpp::usage exposes no command-specific +-flags the surface is just the inherited general flag set (none of which apply to a pure CA-overlap aligner).

Audit summary

BucketCount
Done1 (default align)
Missing0

INDENT is byte-parity complete by virtue of having no command-specific surface. The only legitimate concern is the fixed-width-font dependency CLAN mentions, chatter doesn’t care about font metrics since it aligns by column count, not visual width.

Algorithm

  1. Parse the file into tiers (speaker prefix + content text)
  2. For each main tier (*SPK:), scan for opening overlap markers ⌈ and record their column positions and optional numeric suffixes
  3. Scan up to 30 subsequent tiers from different speakers for closing overlap markers ⌊
  4. Match open/close pairs by numeric suffix (or sequentially if unnumbered)
  5. Insert or remove spaces before the closing marker to align columns
  6. Report unmatched markers as warnings

Example

Before:

*CHI:	I want ⌈ cookies ⌉ .
*MOT:	⌊ yeah ⌋ okay .

After:

*CHI:	I want ⌈ cookies ⌉ .
*MOT:	       ⌊ yeah ⌋ okay .

Numbered overlaps (⌈1, ⌈2, etc.) are matched by their numeric suffix, allowing multiple simultaneous overlaps to be aligned independently.

Differences from CLAN

  • Manual intent: INDENT is a layout command, not a semantic CHAT analysis command.
  • Operates on UTF-8 text using Rust’s char-based column counting rather than C byte-level scanning.
  • Uses the text-based transform pattern (no AST round-trip) to preserve original formatting outside of overlap alignment.
  • Maximum 10 alignment passes (CLAN’s goto beginAgain loop has no bound, causing infinite loops on some inputs).
  • Column counting treats each Unicode scalar value as width 1.

IPSYN – Index of Productive Syntax

Status: Current Last updated: 2026-05-26 10:20 EDT

Purpose

Computes a syntactic complexity score by awarding points for distinct syntactic structures observed in a child’s utterances. Each structure type (rule) can earn at most 2 points – one per distinct utterance in which the structure appears. The total across all rules yields the IPSyn score.

See the CLAN manual for the original IPSYN command specification.

Usage

chatter-clan ipsyn file.cha
chatter-clan ipsyn --speaker CHI file.cha
chatter-clan ipsyn --rules ipsyn.rules file.cha
chatter-clan ipsyn --max-utterances 100 file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--rules <PATH>+lFCustom IPSYN rules file
--max-utterances <N>+cNMaximum utterances to analyze (default: 100)
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN ipsyn flag. Sources:

  • OSX-CLAN/src/clan/ipsyn.cpp: usage().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() IPSYN branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Ipsyn plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

IPSYN is a required-flag refusal command in chatter, same refusal byte-parity as EVAL/KIDEVAL/DSS/SUGAR. The rules file is also required for non-default analysis.

IPSYN-specific +-flags (from ipsyn.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+cNAnalyse N complete unique utterances (default 100)--max-utterances NDoneDirect mapping; rewriter routes +cN → --max-utterances N for IPSYN (since the per-subcommand routing batch).
+dDo not show file and line number where points are found,MissingPer OSX-CLAN/src/clan/ipsyn.cpp:3945, CLAN sets onlydata = atoi(getfarg(...)) + 1 (bounded by OnlydataLimit); +d → level 1. chatter has no --only-data flag. Per-IPSYN arm in clan_args.rs passes the token through so clap reports the literal +d argument rather than the misleading --display-mode rewrite.
+d1Output in spreadsheet format,MissingSame onlydata toggle as +d (CLAN: +d1 → level 2). chatter not implemented; passthrough arm.
+lFSpecify IPSYN rules file name F--rules <PATH>DoneDirect mapping; rewriter routes +lF → --rules F for IPSYN (since the per-subcommand routing batch).
+oUse the original rule set (100 utterances),Missing
-sSIgnore [+ ip] / [+ ipe] postcodespartial via --exclude-wordPartialDifferent semantic, chatter filters by word, CLAN’s IPSYN -sS skips postcoded utterances.

Audit summary

BucketCount
Done6
Partial3
Rewriter only2
Missing7

IPSYN’s two cleanest one-line follow-ups (rewriter routing of +cN → --max-utterances N and +lF → --rules F) landed together with the per-subcommand flag-routing batch (commit 9d34a10b).

Rule Categories

Rules are organized into four categories:

CategoryCodeDescriptionExample structures
Noun PhraseNNoun phrase complexityTwo-word NP, article+noun, possessive
Verb PhraseVVerb phrase complexityCopula, auxiliary, modal, infinitive
QuestionQQuestion formationYes/no, wh-question, tag question
SentenceSSentence structureConjoined, embedded, relative clause

The full English IPSyn has ~56 rules. The built-in default set provides a representative subset.

Algorithm

  1. For each utterance, serialize the %mor tier to text
  2. Match each rule pattern against the serialized %mor content
  3. For each rule, record the first two distinct utterances that match (max 2 points per rule)
  4. Sum all rule scores across categories
  5. Report total score and per-category subtotals

Scoring example

If rule N1 (“Two-word NP”) matches in utterances 3 and 7, it earns 2 points. If it only matches in utterance 3, it earns 1 point. If it never matches, 0 points.

Output

Per-speaker IPSyn total score with per-category subtotals (N, V, Q, S) and optional per-rule detail.

Differences from CLAN

Rule set

The built-in rule set is a simplified subset. For full 56-rule coverage, supply the official IPSYN rules file via --rules.

Pattern matching

Uses substring-based matching on the serialized %mor tier text rather than structured POS/morpheme matching. This produces equivalent results for most patterns but may differ for edge cases involving complex morphological structures.

Maximum utterances

Defaults to 100 (matching CLAN). Configurable via --max-utterances.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

Verified against CLAN C binary output.

KEYMAP, Contingency Tables for Coded Data

Status: Current Last updated: 2026-05-26 10:36 EDT

Purpose

Builds contingency tables for coded interactional data. The legacy manual describes KEYMAP as choosing initiating or beginning codes on a specific coding tier, then examining all codes on that same tier in the next utterance.

In talkbank-clan, given a set of keyword codes, KEYMAP tracks each keyword occurrence on a specified coding tier and records what code items appear in the immediately following utterance, broken down by speaker.

See the CLAN manual for the original KEYMAP command specification.

Usage

chatter-clan keymap file.cha --keyword code1 --keyword code2
chatter-clan keymap file.cha --keyword code1 --tier spa
chatter-clan keymap file.cha -k code1 -k code2          # short form

Options (chatter-native)

OptionCLAN flagDescription
-k, --keyword <code>+bSPrimary code to track (required, repeatable)
--tier <name>+t%X (rewriter target)Tier label to read codes from (default: cod)
--speaker <code>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <code>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--format <fmt>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

KEYMAP-specific +-flags (from keymap.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+bS / +b@FSet key code(s) to S (or codes in file @F)-k / --keyword (only the inline S form)PartialInline +bS is now routed (since 2026-05-22), rewriter sends --keyword S. File-list form +b@F still missing; it passes through unrewritten so clap rejects loudly.
+cS / +c@FSet complimentary key code to S (or file @F),MissingPair-completion key for the contingency table.
+dOutput in spreadsheet format,MissingOSX-CLAN/src/clan/keymap.cpp:834 no-arg Excel/CSV toggle (no_arg_option(f) + isExcel = TRUE). Per-KEYMAP rewriter arm passes the token through so clap rejects loudly; no --format csv consumer for KEYMAP today.
+oInclude codes that precede target code(s),MissingTwo-sided contingency (before + after).

Audit summary

BucketCount
Done5
Partial1
Rewriter only3
Missing6

KEYMAP’s largest gap is the complimentary code (+cS): without it, the contingency table is one-sided, chatter tracks what follows each keyword, but CLAN’s KEYMAP also pairs keywords with their complimentary codes for a true cross-tabulation. The +o two-sided mode (codes before AND after the target) is also missing.

Output

Per speaker per keyword:

  • Total keyword occurrences
  • Following codes with speaker attribution and frequency counts

Differences from CLAN

  • Manual intent: The legacy manual explicitly treats KEYMAP as a coding-tier command and says that only symbols beginning with $ are considered on that tier; all other strings are ignored.
  • Code extraction for %cod now uses a clan-local semantic %cod item layer derived from the parsed AST rather than flattened tier text
  • Selector handling: %cod selectors such as <w4> and <w4-5> are treated as item scope, not as stand-alone codes, when deriving keyword and following-code items.
  • Manual constraint not yet fully enforced: KEYMAP currently retains a generic non-%cod tier fallback. The manual suggests tighter coding-tier semantics than that fallback provides.
  • Keyword matching is case-insensitive by default
  • Output supports text, JSON, and CSV formats
  • Deterministic ordering via BTreeMap
  • Golden test parity: Verified against CLAN C binary output

KIDEVAL – Child Language Evaluation

Status: Current Last updated: 2026-05-22 09:20 EDT

Purpose

Produces a comprehensive child language evaluation report by combining multiple analysis methods into a single per-speaker summary. KIDEVAL is designed for evaluating children’s language development and aggregates results from several individual CLAN commands.

See the CLAN manual for the original KIDEVAL command specification.

Usage

chatter-clan kideval file.cha
chatter-clan kideval --speaker CHI file.cha
chatter-clan kideval --format json file.cha
chatter-clan kideval --dss-rules english.scr file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--dss-rules <PATH>,Custom DSS rules file (.scr), chatter extension
--ipsyn-rules <PATH>+lF (Phase 1.7 follow-up)Custom IPSYN rules file
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

KIDEVAL does not expose per-component utterance caps as CLI flags (despite the standalone DSS / IPSYN commands having --max-utterances of their own); the combined report uses each component’s built-in default (DSS 50, IPSYN 100). To override, run those components separately and aggregate.

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN kideval flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/kideval.cpp: usage() and getflag().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() KIDEVAL branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Kideval plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

KIDEVAL-specific +-flags (from kideval.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aNLimit to files with > N utterances,MissingSample-size guard.
+bS / -bSMorpheme-delimiter customization,MissingShared with WDLEN/MAXWD/EVAL.
+dtd~S / +dnarrative~S / similarDatabase keyword filters (age range, sex),MissingKIDEVAL’s database-comparison engine; not wired in chatter.
+eS, +e+, +e-, +e1Dataset keyword / metadata listing,MissingDatabase-side.
+lFLanguage script file (eng, engu, fra, jpn, nld, spa, yue, zho)partial via --ipsyn-rules / --dss-rulesPartialchatter exposes only the per-component rules files; CLAN’s +lF picks a packaged language bundle.
+n / -nGem termination semantics,Missing
+oNOutput format/verbosity sub-modes,Rewriter onlyFalls to --display-mode rewrite.
+sPostcode filter [+ ...]partial via --include-wordPartialDifferent semantic, chatter filters by main-tier word, CLAN’s KIDEVAL +s matches postcodes.

General +-flags KIDEVAL inherits (from cutt.cpp::mainusage)

Same shape as MLU / FREQPOS. KIDEVAL is currently a required- flag refusal command in chatter, invoking without +t*X (or --speaker X) emits CLAN’s exact Please specify at least one speaker tier code with "+t" option on command line. to stderr and exits 1. That refusal byte-parity is verified.

Audit summary

BucketCount
Done5
Partial3
Rewriter only5
Missing11

KIDEVAL’s largest gaps are the database-comparison engine (+dtd~, +dnarrative~, +eS, +lF language bundles). These are KIDEVAL’s whole point, comparison to age-/sex-stratified normative samples, and currently chatter’s KIDEVAL emits the combined-metrics report without the comparison overlay. Filed as a Phase 1.7 follow-up.

Combined Metrics

KIDEVAL produces a single report combining:

MetricSourceDetails
MLU (words and morphemes)Main tier + %morSee MLU
NDW / TTRMain tier word types/tokensSee FREQ
DSS score%mor tierSee DSS
VOCD (D statistic)Main tier wordsSee VOCD
IPSyn score%mor tierSee IPSYN
POS category counts%mor tierNouns, verbs, auxiliaries, etc.
Error counts[*] markersWord-level errors

This is the primary tool for clinical assessment of child language samples, providing a comprehensive profile in a single command invocation.

Differences from CLAN

VOCD simplification

KIDEVAL uses a simplified TTR-based D estimate rather than the full bootstrap sampling approach used by the standalone VOCD command. This trades precision for speed when computing the combined report.

IPSYN rules

Uses the built-in simplified rule subset unless a custom rules file is provided via --ipsyn-rules. For full 56-rule coverage, supply the official IPSYN rules file.

DSS rules

Uses the built-in simplified rule subset unless a custom rules file is provided via --dss-rules. For full clinical scoring, supply a complete .scr rules file.

AST-based analysis

All component analyses share the same AST-based infrastructure, ensuring consistent word identification and morpheme counting across all metrics. In CLAN, each component command has its own independent word-filtering logic, which can lead to subtle inconsistencies.

Golden test parity

Verified against CLAN C binary output.

KWAL – Keyword And Line

Status: Current Last updated: 2026-06-15 12:55 EDT

Purpose

Searches for clusters containing specified keywords and displays the matching lines with context. The legacy manual gives KWAL a dedicated section and describes it as operating on “clusters”: the main tier plus the selected dependent tiers associated with that line.

In talkbank-clan, keywords are currently matched against countable words on the main tier, with the matched utterance shown in context.

Usage

chatter-clan kwal -k want file.cha
chatter-clan kwal -k want --speaker CHI file.cha
chatter-clan kwal -k want -k cookie file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
-k <WORD> / --keyword <WORD>+s"WORD"Keyword to search for (repeatable)
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN kwal flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/kwal.cpp: usage() and getflag().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() KWAL branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Kwal plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

KWAL-specific +-flags (from kwal.cpp::getflag)

CLAN flagMeaningChatterStatusNotes
+aSort output in alphabetical order of keywords (repeats tier per keyword),MissingKWAL’s keyword-alphabetised mode.
+bApply +s match only when the keyword is the only item on the tier--strict-matchDoneLanded 2026-05-23. Gate runs before keyword matching: utterances with words.len() != 1 are rejected outright. Pinned by kwal_strict_match_only_solo_word_matches (single-word ["want"] matches, ["I", "want", "cookie"] doesn’t) and kwal_default_matches_anywhere_on_tier (default matches both).
+nSInclude all utterances from speaker S when they follow a match for +s,MissingSliding-window-by-speaker, distinct from +wN general context window.
-nSExclude all utterances from speaker S when they follow a match,Missing
+d (no N)Output legal CHAT format--legal-chatDoneLanded 2026-05-23. Rewriter maps bare +d for KWAL; render_clan skips the --- separator and *** File … Keyword: X decoration so only the matching *Speaker: lines remain. The dependent tiers attached to the match (e.g. %mor) come through to_chat_string() as legal CHAT. Pinned by kwal_legal_chat_format_drops_location_decoration and the rewriter test kwal_legal_chat_format. +dN for N ≥ 1 still falls through to --display-mode N.
+d1..+d4, +d30, +d31, +d40, +d7, +d90, +d99Various output-format and tier-linking variants,Rewriter onlyAll rewrite to --display-mode N; no consuming clap field.

General +-flags KWAL inherits (from cutt.cpp::mainusage)

CLAN flagMeaningChatterStatusNotes
+t*X / -t*XInclude/exclude speaker--speaker / --exclude-speakerDone+tX accepted post-2026-05-21.
+t%X / -t%XInclude/exclude dependent tier--tier / --exclude-tier (rewriter target)Rewriter onlyKWAL stores fDepTierName / sDepTierName for cluster output; chatter does not expose this.
+t@ID="..."Filter by @ID pattern--id-filterDone
+t#ROLEFilter by role--roleDoneFixed 2026-05-22; see FREQ for the shared implementation.
+s"word" / -s"word"Keyword (KWAL’s primary input)-k / --keyword / --exclude-wordPartialThe search mapping (+s"word" to --keyword) is correct. Divergence: CLAN’s +s is optional, not required, verified by running OSX-CLAN/src/unix/bin/kwal with no +s (it echoes all clusters, the +t%/-t% tier-trim use the manual documents); chatter currently requires --keyword and has no no-search pass-through mode. Tighten when KWAL’s cluster/tier-echo behavior lands.
+s@F / -s@FKeywords / exclude words from file--include-word-file / --exclude-word-fileDoneLanded 2026-05-22. File format: one pattern per line; blank lines, # -comments, and ;%* -annotation lines skipped. Repeatable.
+gXGem filter--gemDoneKWAL uses the inherited semantic (gem segment), not an overloaded one.
+zN-MUtterance range--rangeDone
+rNRetrace / clitic / prosodic controls--include-retracings (+r6)Partial
+uCombine across files(default)DoneInverse default vs CLAN.
+reRecurse(default)Done
+pSWord delimiter,Missing
+kCase-sensitive--case-sensitiveDoneLanded 2026-05-23. Reads CommonAnalysisArgs::case_sensitive; KWAL process_utterance skips the NormalizedWord lowercasing on both keyword and word sides when set. The flag is wired across the search/frequency family, with polarity matching each command’s CLAN default; see the flag-translation guide. Pinned by kwal_case_sensitive_uppercase_keyword_misses_lowercase_word and kwal_case_sensitive_matches_when_case_aligned.
+wN / -wNContext window--context-after N / --context-before NDoneLanded 2026-05-23. +wN emits N utterances following each match; -wN emits N utterances preceding. KwalState carries a VecDeque ring buffer of recent utterance texts (for pre-context) and a Vec<(match_idx, remaining)> list of matches still collecting post-context. Per-utterance flow: feed any open awaiting-after entries, detect match, snapshot ring as pre_context, register new awaiting-after, then update ring. render_clan emits pre-context lines + match body + post-context lines per match block. Distinct from KWAL’s +nS speaker-context (separate Missing item). Pinned by kwal_context_after_captures_post_match_lines, kwal_context_before_captures_pre_match_lines, and kwal_default_no_context_window.
+f / +fEXTOutput to file--output-ext (rewriter target)Rewriter onlyPhase 1.1.

Audit summary

BucketCount
Done (byte-parity or in scope)11
Partial2
Rewriter only9
Missing6

KWAL has the largest “Rewriter only” bucket of any audited command so far (12). Almost all the variants come from +dN’s nine sub-modes (+d, +d1..+d4, +d30, +d31, +d40, +d7, +d90, +d99), each of which materially changes KWAL’s output shape. Until --display-mode N is wired in, a researcher pasting kwal +d1 +s"want" file.cha into chatter gets a parse error.

CLAN Equivalence

CLAN commandRust equivalent
kwal +s"want" file.chachatter-clan kwal file.cha -k want
kwal +s"want" +t*CHI file.chachatter-clan kwal file.cha -k want --speaker CHI

Display Modes (+dN / --display-mode N), partially landed

Status: +d (no number) implemented as --legal-chat; +dN for N ≥ 1 still drafted from CLAN manual. The generic rewriter at crates/talkbank-clan/src/clan_args.rs translates each +dN to --display-mode N, but no clap field consumes that token for N ≥ 1 today. This table is drafted from CLAN manual §7.17.5 (Unique Options, KWAL) verbatim for PI review. The generic +dN placeholder is tracked internally.

KWAL uses +d to switch the output shape (plain CHAT, with filenames, Excel form, etc.). Quoted from CLAN manual §7.17.5:

NCLAN behavior (verbatim from manual)
+d (no number)“Normally, kwal outputs the location of the tier where the match occurs. When the +d switch is turned on you can [output] in these formats: … outputs legal CHAT format.”
+d1“Outputs legal CHAT format plus file names and line numbers.”
+d2“Outputs file names once per file only.”
+d3“Outputs ONLY matched items.”
+d30“Outputs ONLY matched items without any defaults removed. The +d30 and the +d3 switches can be combined.”
+d99“Convert ‘word [x 2]’ to ‘word [/] word’ and so on.”
+d4“Outputs for Excel.”
+d40“Outputs for Excel, repeating the same tier for every keyword match.”
+d7“Compares items across dependent tiers.” Example: kwal +d7 +s@|-cop +sROOT +t%gra +t%mor t.cha

Open questions for PI review

  1. +d (no number): resolved 2026-05-23. Implemented as --legal-chat (boolean), chatter’s default render emits the *** File ... Keyword: X location decoration; +d switches to the matching utterance lines as a legal CHAT fragment. The --display-mode 0 numeric framing was rejected in favour of a named boolean since the rest of the +dN table is genuinely distinct shape/format options rather than a numeric severity axis.
  2. +d30 is “+d3 + don’t strip defaults”, combinable. Maps to --display-mode matched --no-strip-defaults or --display-mode 30?
  3. +d99 is conceptually orthogonal to the others (it’s a transformation, not an output shape). Worth splitting into a separate --expand-repetition flag rather than overloading --display-mode.
  4. +d4/+d40 for Excel: same Excel question as FREQ, overlap with --format csv.
  5. +d7 cross-tier comparison: deeply specific. In scope for the first --display-mode pass, or future work alongside freqpos / mortable?

Output

Each matching utterance with:

  • Speaker code
  • Full utterance text
  • File path (for multi-file searches)
  • Match count summary per keyword

Differences from CLAN

  • Manual intent: KWAL is a cluster-oriented search command, not just a main-tier keyword matcher.
  • Search: Operates on parsed AST word content rather than raw text lines.
  • Word identification: Uses AST-based is_countable_word() instead of CLAN’s string-prefix matching.
  • Scope reduction: The legacy manual describes richer tier-selection and output-shaping behavior, including cluster searches over selected dependent tiers and %mor/%gra combined searches with +d7. The current implementation is narrower.
  • Output formats: Supports text, JSON, and CSV formats (CLAN produces text only).
  • Golden test parity: Verified against CLAN C binary output.

LAB2CHAT – LAB Timing Labels to CHAT Conversion

Status: Current Last updated: 2026-05-27 10:39 EDT

Purpose

Converts LAB (label) timing files into CHAT format. LAB files contain time-aligned word or segment labels commonly used in speech research tools (e.g., HTK, Kaldi).

Usage

chatter-clan lab2chat input.lab

Options

OptionDefaultDescription
-s, --speaker"SPK"Speaker code for all utterances
-L, --language"eng"ISO 639 language code for the @Languages header (note: uppercase -L because lowercase -l would conflict)
-o, --outputstdoutOutput CHAT file path

The corpus name in @ID headers is hardcoded to "lab_corpus" (crates/talkbank-clan/src/converters/lab2chat.rs:110); there is no CLI flag to override it.

Supported Formats

  • Three-column: start_time end_time label (times in seconds)
  • Two-column: time label (end time inferred from the next entry)

Input Format

Plain text files with whitespace-separated columns. Silence markers (sil, sp, #) are skipped during conversion. Comment lines starting with # and blank lines are ignored.

Example:

0.0 0.5 hello
0.5 1.2 world
1.2 1.5 sil

Output

A well-formed CHAT file where each non-silence label becomes a separate utterance with timing bullets derived from the LAB timestamps (converted from seconds to milliseconds).

Differences from CLAN

  • Uses typed AST for CHAT generation
  • Produces valid, well-formed CHAT output

CLAN +-flag coverage audit

LAB2CHAT is a converter: input WaveSurfer .lab files, output CHAT. Sources: OSX-CLAN/src/clan/lab2chat.cpp::usage, crates/talkbank-clan/src/converters/lab2chat.rs.

LAB2CHAT-specific +-flags (from lab2chat.cpp::usage)

CLAN flagMeaningChatterStatus
+dFTags-dependencies file F,Missing
+fN(CLAN-internal),Missing
+mFMovie file name F (default: input file name),Missing
+pPlain file conversion (default: merge per attribute file),Missing
+oSCode page selection,Missing
+tNMovie segment start time offset,Missing
+reRecurse subdirectories(default for directory input)Done

Audit summary: 1 Done, 6 Missing. LAB2CHAT’s metadata-rich options (tags, movie association, code-page) are the biggest gap; chatter handles the timing-label → utterance core but not the surrounding metadata machinery.

LENA2CHAT – LENA Device XML to CHAT Conversion

Status: Current Last updated: 2026-05-22 13:40 EDT

Purpose

Converts LENA (Language Environment Analysis) device output files (.its format) into CHAT format. LENA XML contains segment-level annotations with speaker types and timing information but no actual transcribed words.

Usage

chatter-clan lena2chat input.its

Options

OptionDefaultDescription
language"eng"ISO 639 language code for the @Languages header
corpus"lena_corpus"Corpus name for the @ID header

Speaker Mapping

LENA segment types are mapped to CHAT speaker codes:

LENA typeCHAT speakerDescription
CHN/CXNCHIChild near/far
FAN/FAFMOTFemale adult near/far
MAN/MAFFATMale adult near/far
OLN/OLFOTHOther child overlap
TVN/TVFENVTV/electronic media
NON/NOFENVNoise
SIL(skipped)Silence

Input Format

LENA .its XML files containing segment-level annotations with speaker type attributes and timing information.

Output

A well-formed CHAT file where each LENA segment becomes a timed utterance. Since LENA does not provide transcribed words, all utterances use xxx (untranscribed) as placeholder text, with optional word count annotation.

Differences from CLAN

  • Uses typed AST for CHAT generation
  • Produces valid, well-formed CHAT output

CLAN +-flag coverage audit

LENA2CHAT is a converter: input LENA .its XML, output CHAT. Sources: OSX-CLAN/src/clan/Lena2Chat.cpp::usage, crates/talkbank-clan/src/converters/lena2chat.rs.

CLAN’s Lena2Chat.cpp::usage documents no command-specific +-flags: the surface is just the inherited general flag set (mostly +re for recursion). Byte-parity complete for the documented surface.

Audit summary: 1 Done, 0 Missing.

LINES – Add or Remove Sequential Line Numbers

Status: Current Last updated: 2026-05-22 13:05 EDT

Purpose

Adds or removes line numbers for display. The legacy manual describes LINES as inserting line numbers based on CLAN’s “Show Line Numbers” display and using +n to remove them.

Since line numbering is a display concern rather than a structural CHAT operation, the AST transform is a no-op; the actual logic operates on serialized CHAT text via add_line_numbers(), remove_line_numbers(), and the end-to-end run_lines() function.

Line numbers are formatted as 5-character right-aligned integers prefixed to non-header lines. Header lines (@Begin, @Languages, etc.) are not numbered.

Usage

chatter-clan lines file.cha
chatter-clan lines --remove file.cha

Options

OptionTypeDefaultDescription
--removeboolfalseRemove existing line numbers instead of adding them

CLAN +-flag coverage audit

LINES is a transform. Sources: OSX-CLAN/src/clan/lines.cpp::usage, crates/talkbank-clan/src/transforms/lines.rs.

LINES-specific +-flags (from lines.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+nRemove all line/tier numbers--removeDoneDirect mapping; rewriter routes +n → --remove (since 2026-05-22).

Audit summary: 1 Done (add-numbers default), 1 Done (+n removal mapped). 0 Missing.

Behavior

Adding line numbers: Each non-header line receives a 5-character right-aligned sequential number prefix (e.g., 1 *CHI: ...). Header lines (@-prefixed) are not numbered.

Removing line numbers: Strips the first 6 characters (5-digit number + space) from non-header lines.

Differences from CLAN

  • Manual intent: LINES is a display/layout command, so text-level processing is intentional here.
  • Operates on serialized text (post-parse) rather than raw input, since line numbering is a display concern.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> text fixups -> write).

LIPP2CHAT – LIPP Phonetic Profile to CHAT Conversion

Status: Current Last updated: 2026-05-22 13:40 EDT

Purpose

Converts LIPP (Logical International Phonetics Programs) phonetic profile data into CHAT format. Each entry becomes an utterance, and phonetic transcriptions are placed on %pho dependent tiers.

Usage

chatter-clan lipp2chat input.lipp

Options

OptionDefaultDescription
-s, --speaker"CHI"Speaker code for all utterances
-l, --language"eng"ISO 639 language code for the @Languages header
-o, --outputstdoutOutput CHAT file path

The corpus name in @ID headers is hardcoded to "lipp_corpus" (crates/talkbank-clan/src/converters/lipp2chat.rs:80); there is no CLI flag to override it.

Input Format

Tab-separated word and phonetic transcription, one pair per line:

cat    kaet
dog    dog

Lines starting with # are treated as comments. Single words without a tab-separated phonetic field are imported without a %pho tier.

Output

A well-formed CHAT file where each LIPP entry becomes an utterance on the main tier. When a phonetic transcription is present, it is placed on a %pho dependent tier attached to the utterance.

Differences from CLAN

  • Uses typed AST for CHAT generation
  • Produces valid, well-formed CHAT output

CLAN +-flag coverage audit

LIPP2CHAT has no dedicated .cpp in CLAN’s source tree, chatter exposes a first-class converter for the LIPP phonetic profile format with no CLAN counterpart to compare against. Audit summary: chatter extension. No CLAN flag surface.

LONGTIER – Remove Line Continuation Wrapping

Status: Current Last updated: 2026-05-22 13:06 EDT

Purpose

Removes physical continuation-line wrapping so each logical tier occupies one line in the output file. The legacy manual describes LONGTIER as removing line wraps on continuation lines so that each main tier and each dependent tier is on one long line.

In CHAT format, long tiers are conventionally wrapped with a newline followed by a tab. LONGTIER folds those continuations back into a single line.

Usage

chatter-clan longtier file.cha
chatter-clan longtier file.cha -o unwrapped.cha

Behavior

Folds any line starting with a tab character into the preceding tier line, replacing the newline+tab with a single space. The result has one line per tier with no continuation wrapping.

Differences from CLAN

  • Manual intent: LONGTIER is below the AST layer; it is about physical line wrapping, not CHAT semantics.
  • Operates on raw text rather than partial parsing, making it robust against malformed files that might not parse cleanly.
  • Normalizes all newlines to \n (handles \r\n and \r).

CLAN +-flag coverage audit

LONGTIER is a transform. CLAN’s longtier.cpp::usage accepts [o ...] (the +o extra-output-tier flag, inherited) but documents no command-specific +-flags. chatter’s surface is likewise minimal.

CLAN flagMeaningChatterStatus
(none documented)default unwrap continuationsdefaultDone

Audit summary: 1 Done, 0 Missing. Byte-parity complete.

  • Multiple leading tabs on continuation lines are all consumed.

LOWCASE – Lowercase All Words on Main Tiers

Status: Current Last updated: 2026-05-26 09:05 EDT

Purpose

Reimplements CLAN’s lowcase command, which converts all words on main tiers to lowercase. Speaker codes, headers, and dependent tiers are preserved unchanged. The transformation recurses into annotated words, replaced words, groups, and annotated groups.

See the CLAN manual for the original command documentation.

Usage

chatter-clan lowcase file.cha

Options

This command has no command-specific flags beyond the shared -o, --output <PATH> (default: stdout). See Output Formats for the transform output flag.

CLAN +-flag coverage audit

LOWCASE is a transform. Sources: OSX-CLAN/src/clan/lowcase.cpp::usage, crates/talkbank-clan/src/transforms/lowcase.rs.

LOWCASE-specific +-flags (from lowcase.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+cLowercase only the first word on a tier,MissingFirst-word-only mode.
+dDo NOT change words listed in iF dict file; lower-case the rest,MissingDictionary-guarded lowercasing, typically a proper-nouns / pronouns list.
+d1Capitalize words in dict file; leave the rest unchanged,MissingInverse mode (capitalization, not lowercasing).
+d2Ignore dict file; lower-case everything(default; no-op rewriter arm)Done (no-op per CLAN)chatter’s transforms/lowcase.rs lowercases every main-tier word unconditionally, exactly the +d2 semantic per OSX-CLAN/src/clan/lowcase.cpp case ‘d’ (isChangeToUpper = atoi(...), range 0..=2). Rewriter drops the token (clan_args.rs).
+iFDictionary file F with words to NOT lowercase,MissingPairs with +d.

Audit summary

BucketCount
Done1
Partial0
Missing4

LOWCASE’s largest gap is the proper-noun/pronoun preservation dictionary (+iF++d): CLAN ships a lowcase.cut dictionary that lists words to keep capitalised (proper nouns, the pronoun I, etc.), so the typical CLAN invocation preserves “I” and “Mary” while lowercasing the rest. chatter’s lowcase lowercases everything unconditionally, which can incorrectly merge the pronoun “I” with the article “i” (rare but real). Filed as the top Phase 1.7 follow-up for this command.

Behavior

For each utterance, the transform lowercases all word surfaces on the main tier. The transformation recurses into:

  • Plain words
  • Annotated words (inner word)
  • Replaced words (both original and replacement forms)
  • Groups (bracketed content)
  • Annotated groups (inner bracketed content)

Speaker codes, header lines, and dependent tiers are not modified.

Differences from CLAN

  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).

MAKEMOD – Generate %mod Tier from Pronunciation Lexicon

Status: Current Last updated: 2026-05-22 13:12 EDT

Purpose

Reimplements CLAN’s MAKEMOD command, which looks up each countable word on main tiers in a pronunciation lexicon (CMU dictionary format) and generates a %mod dependent tier with the phonemic transcription. Words not found in the lexicon are marked with ???.

Usage

chatter-clan makemod --lexicon cmulex.cut file.cha

Options

OptionTypeDefaultDescription
-l, --lexiconpath(required)Path to the pronunciation lexicon file
--all-alternativesboolfalseShow all alternative pronunciations (default: first only)
-o, --outputpathstdoutOutput CHAT file path

CLAN +-flag coverage audit

MAKEMOD is a transform. Sources: OSX-CLAN/src/clan/makemod.cpp::usage, crates/talkbank-clan/src/transforms/makemod.rs.

MAKEMOD-specific +-flags (from makemod.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aPrint out all alternative pronunciations (default: first)--all-alternativesDoneDirect mapping; rewriter routes +a → --all-alternatives (since 2026-05-22).

Audit summary: 2 Done (default first-only + +a all-alts). 0 Missing. Clean parity.

External Data

Requires a CMU-format lexicon file. CLAN ships a cmulex.cut in its lib/ directory and uses that by default; chatter-clan makemod does not bundle a lexicon, so --lexicon must be passed explicitly.

Format: WORD phoneme1 phoneme2 ... (one entry per line). Lines starting with # or % are treated as comments. Words with (N) suffix (variant number like READ(2)) are treated as pronunciation alternatives for the base word.

Behavior

For each utterance, the transform:

  1. Extracts countable words from the main tier (using the framework’s countable_words() utility).
  2. Looks up each word in the loaded pronunciation lexicon (case-insensitive).
  3. Builds a %mod dependent tier with the phonemic transcriptions. Words not found are marked ???.
  4. Appends the %mod tier to the utterance’s dependent tiers.

Differences from CLAN

  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).

MAXWD – Longest Words

Status: Current Last updated: 2026-05-27 10:39 EDT

Purpose

Finds the longest words used by each speaker, reporting a ranked table of unique words sorted by character length descending. Word length is measured in characters after normalization (lowercasing, stripping + compound markers and ' apostrophes for CLAN compatibility).

Usage

chatter-clan maxwd file.cha
chatter-clan maxwd --speaker CHI file.cha
chatter-clan maxwd --limit 50 file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--limit <N>+cNMaximum number of words to show (default: 20)
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN maxwd flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/maxwd.cpp: usage() and getflag().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() MAXWD branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Maxwd plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

MAXWD-specific +-flags (from maxwd.cpp::getflag)

CLAN flagMeaningChatterStatusNotes
+aConsider ONLY unique-length utterances/words--unique-length-onlyDoneLanded 2026-05-23. Per-speaker filter: drops words whose character length is shared with another word in the same speaker’s lexicon. max_length is recomputed over the surviving entries, so the output reflects only unique-length words. Pinned by maxwd_unique_length_only_drops_shared_length_words and the regression companion maxwd_default_keeps_shared_length_words. CLAN’s flag covers both “words” and “utterances”; chatter currently only implements the words sense (MAXWD’s +gN utterance-mode is a separate Missing item).
+bSAdd chars in S to morpheme-delimiter list,MissingShared with WDLEN.
-bSRemove chars from delimiter list (-b clears all),Missing
+cNDisplay the N longest items--limit N (or -n N)DoneRewriter handles this since 2026-05-22: +c50 → --limit 50 for the MAXWD subcommand specifically (CHECK still gets --bullets N).
+gNFind longest utterance instead of longest word; N selects metric (1=morph, 2=word, 3=char),MissingA different domain (utterances vs words). Per-MAXWD rewriter arm in clan_args.rs returns None for digit-only +gN so the literal token passes through to clap (which rejects it) rather than silently mis-routing to --gem N via the generic +g → rewrite_gem arm. MAXWD’s +gX non-digit gem-filter form continues to fall through to rewrite_gem.
+xNExclude lengths--exclude-length N (repeatable)DoneLanded 2026-05-23. Drops words whose character length matches any value in exclude_lengths. Repeatable on the CLI (+x5 +x7 or --exclude-length 5 --exclude-length 7). max_length is recomputed over surviving entries. Applied per-speaker after +a. Pinned by maxwd_exclude_lengths_drops_listed_lengths plus rewriter tests maxwd_exclude_length_single and maxwd_exclude_length_multiple. End-to-end smoke: input ["I", "go", "bye", "hi", "hello", "world", "cookie"] with +x6 reports max_length 5 instead of 6 (cookie dropped).
+dDisplay modes (see “Display Modes” below),MissingMAXWD has no local case 'd'; consumption via the shared maingetflag path at OSX-CLAN/src/clan/cutt.cpp:9382 with non-empty per-program body at cutt.cpp:9475 (onlydata == 1 → puredata = 0). chatter has no --display-mode consumer for MAXWD. Per-MAXWD rewriter arm in clan_args.rs passes the token through so clap reports the literal +d/+dN argument rather than the misleading --display-mode rewrite.

General +-flags MAXWD inherits (from cutt.cpp::mainusage)

CLAN flagMeaningChatterStatusNotes
+t*X / -t*XInclude/exclude speaker--speaker / --exclude-speakerDone+tX accepted post-2026-05-21.
+t%X / -t%XInclude/exclude dependent tier--tier / --exclude-tier (rewriter target)Rewriter only
+t@ID="..."Filter by @ID pattern--id-filterDone
+s"word" / -s"word"Include/exclude word--include-word / --exclude-wordDone
+s@F / -s@FSearch / exclude words from file--include-word-file / --exclude-word-fileDoneLanded 2026-05-22. File format: one pattern per line; blank lines, # -comments, and ;%* -annotation lines skipped. Repeatable.
+gXGem filter (without N)--gemDoneDistinct from +gN.
+zN-MUtterance range--rangeDone
+rNRetrace / clitic / prosodic controls--include-retracings (+r6)Partial
+uCombine across files(default)Done
+reRecurse(default)Done
+kCase-sensitive--case-sensitiveDoneLanded 2026-05-23. Reads CommonAnalysisArgs::case_sensitive. process_utterance picks the key derivation: default uses NormalizedWord::from_word (lowercased), +k uses NormalizedWord(cleaned_text().to_owned()) (case-preserving) so case variants count as distinct words for the unique-length and exclude-length filters. Pinned by maxwd_case_sensitive_splits_case_variants and maxwd_default_collapses_case_variants.
+wN / -wNContext window (KWAL/COMBO keyword-context)–Rewriter onlyInapplicable to MAXWD (a per-speaker longest-words list, no per-match context to surround). The rewriter maps +wN/-wN to --context-after/--context-before, but MAXWD has no such clap field, so it errors at parse time, the correct outcome for an inapplicable flag (talkbank-clan/AGENTS.md). CLAN’s binary instead empties the output (a context-machinery artifact).
+f / +fEXTOutput to file--output-ext (rewriter target)Rewriter only

Audit summary

BucketCount
Done12
Partial1
Rewriter only2
Missing6

+cN ↔ --limit N was a one-line rewriter follow-up, closed 2026-05-22. The rewriter now distinguishes the MAXWD subcommand (+cN → --limit N) from the CHECK subcommand (+cN → --bullets N); two RED→GREEN tests pin the behaviour.

Other one-line rewriter follow-ups identified during this audit (e.g. FREQ’s +c0..7, VOCD’s +c) remain open and are tracked under Phase 1.7.

Display Modes (+dN / --display-mode N), DRAFT, awaiting PI review

Status: drafted from CLAN manual; not yet implemented. Rewriter at crates/talkbank-clan/src/clan_args.rs:101 translates +dN → --display-mode N; no clap field consumes it today. Drafted from CLAN manual §7.19.1 (Unique Options, MAXWD) for PI review.

NCLAN behavior (verbatim from manual)
+d (no number)“The +d level of this switch produces output with one line for the length level and the next line for the word.”
+d1“Produces output with only the longest words, one per line, in order, and in legal chat format.”

Open questions for PI review

  1. +d is a two-line-per-result format (length on one line, word on next). chatter’s current MAXWD output is a single-line table. Should --display-mode 0 produce the two-line legacy form, or should we treat the table form as the modern default and only honour +d1 (legal CHAT format)?
  2. +d1 “legal chat format” suggests the output is itself a CHAT file. That’s a transform-flavoured output, not analyze. The chatter approach might be to route --display-mode 1 to an explicit chatter-clan maxwd-extract transform rather than overloading the analyze command.

Output

Per speaker:

  • Table of longest words sorted by length descending (up to limit)
  • All occurrences with line numbers (matching CLAN)
  • Maximum word length
  • Mean word length
  • Total and unique word counts

Differences from CLAN

Occurrence reporting

Reports all occurrences with line numbers, matching CLAN’s output format exactly.

Word normalization

Length is measured after stripping + (compound markers) and ' (apostrophes), matching CLAN’s character counting behavior.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

100% parity with CLAN C binary output.

MEGRASP – Grammar Relation Parsing (deliberately not implemented)

Status: Reference – stub command Last updated: 2026-05-22 13:14 EDT

Purpose

In legacy CLAN, megrasp adds %gra (grammatical relation) tiers to CHAT files. It builds dependency-style head/relation labels on top of an existing %mor tier produced by mor, using the MEGRASP rule engine.

This project does not implement megrasp. Like its %mor counterpart, the legacy hand-coded grammar rules are replaced by neural inference. The CHAT data model uses UD-style dependency relations on %gra, which Stanza emits directly alongside %mor.

What to use instead

Use the upstream batchalign3 morphotag pipeline. It produces %mor and %gra tiers from a single Stanza pass, with UD-style relations (NSUBJ, OBJ, ROOT, etc.) instead of CLAN’s GRASP labels. The mapping layer is documented in the batchalign3 project’s morphosyntax reference.

batchalign3 morphotag corpus/  # emits %mor + %gra together

Behavior

Invoking chatter-clan megrasp prints an error directing users to batchalign and exits with a non-zero status. No CHAT files are modified.

See also

  • MOR, POST – companion stubs in the same legacy grammar family
  • The upstream batchalign3 morphosyntax reference – the UD-to-CHAT mapping that replaces this pipeline

CLAN +-flag coverage audit

Exempt: see MOR for the shared MOR-pipeline policy: chatter does not consume CLAN’s +-flags for any command in this family. CLAN’s own usage text documents the legacy flag surface; chatter emits a refusal that points users to batchalign.

MLT – Mean Length of Turn

Status: Current Last updated: 2026-05-26 11:50 EDT

Purpose

Calculates mean length of turn in utterances and words. A “turn” is a maximal consecutive sequence of utterances by the same speaker; the turn boundary is detected when a different speaker produces the next utterance.

See the CLAN manual for the original MLT command specification.

Usage

chatter-clan mlt file.cha
chatter-clan mlt --speaker CHI file.cha
chatter-clan mlt --format json corpus/

Options (chatter-native)

OptionCLAN FlagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN Equivalence

CLAN commandRust equivalent
mlt file.chachatter-clan mlt file.cha
mlt +t*CHI file.chachatter-clan mlt file.cha --speaker CHI

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN mlt flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/mlt.cpp: usage() at line 43 and the command-specific getflag() intercept at line 582.
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() MLT branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s +flag to --flag rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Mlt plus clan_common.rs::CommonAnalysisArgs, chatter’s clap field surface for MLT.

(Status legend: same as FREQ, Done / Partial / Rewriter only / Missing.)

MLT-specific +-flags (from mlt.cpp::getflag)

CLAN flagMeaningChatterStatusNotes
+aDo not count empty utterances (0 utterances),MissingCLAN’s default is to count them; +a flips that. chatter does not yet expose an empty-utterance switch.
+atCount empty utterances when they carry the [+ trn] postcode,MissingSubtle conversational-analysis convention.
+cSClause-marker delimiter S,MissingUsed to split utterances into clauses for turn counting.
+c@FClause markers from file F,MissingFile-list workflow.
+gSExclude utterances consisting solely of word S--exclude-solo-word SDoneFixed 2026-05-22. Per-subcommand rewriter routing + new clap field; same semantic as MLU. See the MLU page for the broader +g overload story.
+g@F+g from file--exclude-solo-word-fileDoneLanded 2026-05-23. Same shape as MLU +g@F; see the MLU page for the rewriter/loader details. Pinned by mlt_solo_word_from_file.
+o3Combine selected speakers per filepartial via --per-file inversePartialchatter’s aggregate-vs-per-file model is the inverse choice.
+t%X (implicit)Switch to dependent-tier mode for the turn split(default for non-mlt commands)PartialMLT’s nomain = TRUE for +t%X has no chatter analog today; MLT chatter operates on main tier exclusively.

General +-flags MLT inherits (from cutt.cpp::mainusage)

CLAN flagMeaningChatterStatusNotes
+t*X / -t*XInclude/exclude speaker--speaker / --exclude-speakerDone+tX (no *) also accepted post-2026-05-21 fix.
+t%X / -t%XInclude/exclude dependent tier %X--tier / --exclude-tier (rewriter target)Rewriter onlyNo --tier field on the Mlt struct.
+t@ID="..."Filter by @ID pattern--id-filterDone
+t#ROLEFilter by role--roleDoneFixed 2026-05-22; see FREQ for the shared implementation.
+s"word" / -s"word"Include/exclude word--include-word / --exclude-wordPartialMLT’s +s special-cases xxx/yyy/www exclusion; chatter’s filter does not.
+s@F / -s@FSearch / exclude words from file--include-word-file / --exclude-word-fileDoneLanded 2026-05-22. File format: one pattern per line; blank lines, # -comments, and ;%* -annotation lines skipped. Repeatable.
+gX(in MLT: utterance-elision filter, see above)--gemPartialSame +g overload as MLU.
+zN-MUtterance range--rangeDone
+rNRetrace / clitic / prosodic-symbol / replacement controls--include-retracings (handles +r6 only)Partial
+uCombine across files(default)Donechatter combines by default; inverse default vs CLAN.
+reRecurse subdirectories(default for directory args)Done
+pSAdd S to word delimiters,Missing
+kCase-sensitive matching--case-sensitive (via CommonAnalysisArgs)Done (no-op per CLAN)MLT does no word-keying; +k is silently accepted per CLAN’s cutt.cpp::mainusage no-op semantic. Covered by CommonAnalysisArgs.case_sensitive flatten on ClanCommands::Mlt.
+wN / -wNContext window (KWAL/COMBO keyword-context)–Rewriter onlyInapplicable to MLT (per-speaker turn/utterance totals, no per-match context to surround). The rewriter maps +wN/-wN to --context-after/--context-before, but MLT has no such clap field, so it errors at parse time, the correct outcome for an inapplicable flag (talkbank-clan/AGENTS.md). CLAN’s binary instead empties the output (a context-machinery artifact).
+f / +fEXTOutput to file--output-ext (rewriter target)Rewriter onlyPhase 1.1.
+dNonlydata output-detail level,MissingMLT has no local case 'd'; consumption is via the shared maingetflag path at OSX-CLAN/src/clan/cutt.cpp:9382 with non-empty per-program body at cutt.cpp:9478 (CLAN_SRV-only rejection of onlydata == 1; otherwise pure level effect). chatter has no --display-mode consumer for MLT. Per-MLT rewriter arm in clan_args.rs passes the token through.

Audit summary

BucketCount
Done (byte-parity or in scope)9
Partial (chatter abstraction differs)6
Rewriter only (would error at parse time)3
Missing (no rewriter, no clap field)6

The +a / +at empty-utterance switch and the clause-delimiter flags (+cS, +c@F) are MLT’s most distinctive omissions: they affect what counts as “an utterance” and “a turn” and so directly drive the MLT ratio. Filed as Phase 1.7 follow-ups.

Algorithm

  1. Walk utterances in file order
  2. Group consecutive utterances by the same speaker into turns
  3. For each speaker, compute:
    • Number of turns
    • Total utterances and total words
    • MLT-u: mean turn length in utterances
    • MLT-w: mean turn length in words
    • SD: standard deviation of words per utterance (population SD, dividing by n)

Turn boundaries

A turn boundary occurs when a different speaker produces the next utterance. For example:

*CHI: I want a cookie .          <- turn 1 (CHI)
*CHI: please .                   <- still turn 1 (CHI)
*MOT: here you go .              <- turn 2 (MOT)
*CHI: thank you .                <- turn 3 (CHI)

CHI has 2 turns (3 utterances), MOT has 1 turn (1 utterance).

Output

Speaker: CHI
  Turns: 15
  Utterances: 42
  Words: 127
  MLT (utterances): 2.800
  MLT (words): 8.467
  SD: 3.217

Differences from CLAN

Standard deviation

Uses population SD (dividing by n), matching CLAN. This was verified during parity testing.

SD basis

The SD is computed over per-utterance word counts, not per-turn totals. This matches CLAN’s behavior, which was confirmed through golden test comparison.

Turn detection

Operates on parsed speaker codes from the AST rather than raw text line prefixes. Functionally identical but type-safe.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

100% parity with CLAN C binary output.

MLU – Mean Length of Utterance

Status: Current Last updated: 2026-10-31

Purpose

Calculates mean length of utterance in morphemes from the %mor tier. When no %mor tier is available and --words was not passed, reports “utterances = 0, morphemes = 0” (matching CLAN behavior – no fallback to word counting).

See the CLAN manual for the original MLU command specification.

Usage

chatter-clan mlu file.cha
chatter-clan mlu --speaker CHI file.cha
chatter-clan mlu --words file.cha
chatter-clan mlu --id-rows file.cha
chatter-clan mlu --id-rows --combine-files corpus/
chatter-clan mlu --format json corpus/

Options (chatter-native)

OptionCLAN FlagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--words-bwCount words from main tier instead of morphemes from %mor
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--include-xxx+sxxxRe-admit xxx (unintelligible) utterances to the count
--include-yyy+syyyRe-admit yyy (phonological) utterances to the count
--combine-speakers+o3 (or bare +t*)Pool selected speakers into one *COMBINED* result
--spreadsheet+dWrite an Excel-compatible SpreadsheetML workbook
--id-rows+d1Emit tab-separated rows with the ten @ID fields and MLU statistics
--combine-files+u with +d1Aggregate +d1 rows across input files
--format <FMT>–Output format: clan (default), text, json, csv

CLAN Equivalence

CLAN commandRust equivalent
mlu file.chachatter-clan mlu file.cha
mlu +t*CHI file.chachatter-clan mlu file.cha --speaker CHI
mlu -bw file.chachatter-clan mlu file.cha --words
mlu +d file.chachatter-clan mlu file.cha --spreadsheet

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN mlu flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/mlu.cpp: usage() at line 51 and the command-specific getflag() intercept at line 669.
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() MLU branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s +flag to --flag rewriter.
  • crates/talkbank-cli/src/cli/args/clan_common.rs and clan_commands.rs::Mlu, chatter’s clap field surface.

(Status legend: same as FREQ, Done / Partial / Rewriter only / Missing.)

MLU-specific +-flags (from mlu.cpp::getflag)

CLAN flagMeaningChatterStatusNotes
-bwCount words, not morphemes--wordsDoneDirect mapping; doc note above.
-bcCount characters, not morphemes(reject)DoneThe unix CLAN binary (our parity target) ERRORS on -bc: the character branch is #ifndef UNX (mlu.cpp:678-680), so getflag falls through to “Please specify w - words after -b option.” (mlu.cpp:686). chatter is fail-closed too (clap rejects; documented message divergence, like the +w-on-aggregate reject). Counting characters is a legitimate measure but would live on a chatter-only flag, never the CLAN -b slot. Pinned by mlu_bc_fails_closed_no_silent_count.
+cSClause-marker delimiter S,MissingUsed to break utterances into clauses for MLU calculation.
+c@FClause-markers listed in file F,MissingFile-list workflow.
+dSpreadsheetML workbook--spreadsheetDoneWrites <input>.mlu.xls beside the first input file. Workbook rows share the CLAN excelOutputID lowering; absent @ID headers use . fields with the speaker code in Code. Live-probed against CLAN (2026-10-31).
+sxxxRe-include xxx utterances in the count--include-xxxDoneLanded 2026-06-05. CLAN ml_isXXXFound (mlu.cpp:766) stops dropping xxx-containing utterances (mlu_excludeUtter blanks the token instead of returning TRUE, mllib.cpp:337) and switches to the two-line +sxxx header (mlu.cpp:250-251); the xxx string still contributes no morpheme. Manual §7.21 pt5. Byte-parity golden mlu_sxxx_include (manchester-anne.cha CHI: utt 3 / morph 4). Modeled as MluConfig.re_included_untranscribed.
+syyyRe-include yyy utterances in the count--include-yyyDone (binary-matched; documented divergence)The CLAN binary accepts +syyy (sets ml_isYYYFound, mlu.cpp:776) and re-includes the yyy utterances, but (a) the manual §7.21 pt2 says “yyy and www are always excluded and cannot be included”, and (b) CLAN has NO yyy-only header branch (mlu.cpp:246-253), so +syyy alone keeps the DEFAULT header while changing the count. chatter reproduces the binary (the chatter-clan parity oracle), pinned by the header-variant unit test; the manual conflict is recorded under “Documented CLAN-bug divergences” below for PI adjudication.
+sxxx/+syyy default (no flag)Exclude utterances containing xxx/yyy/www(default)DoneLanded 2026-06-05 (base-command bug fix). Manual §7.21 pt2: xxx/yyy/www and the utterances containing them are excluded by default; mlu_excludeUtter (mllib.cpp:303-348) returns TRUE on the MAIN tier (mlu.cpp:509). chatter previously counted utterances that mixed xxx with real words (e.g. it xxx xxx). Byte-parity golden mlu_xxx_exclude.
-sxxx/-syyy/+swww/-swww(reject)(reject)DoneCLAN errors: “Excluding xxx is not allowed” (mlu.cpp:768), “Including/Excluding www is not allowed” (mlu.cpp:784); www is never includable. chatter fails closed (clap rejects a self-documenting non-existent flag, because --speaker owns -s and a plain pass-through would be misread as --speaker). Pinned by mlu_s_untranscribed_guards_fail_closed.
[+ mlue] postcodeExclude this utterance from MLU(default)DoneLanded 2026-06-05 (base-command bug fix). isMLUEpostcode defaults TRUE (mlu.cpp:108); isPostCodeOnUtt(line, "[+ mlue]") -> isSkip (mlu.cpp:503). chatter checks MainTier::content.postcodes for the mlue payload. Byte-parity golden mlu_mlue_postcode_exclude (trimmed NINJAL-Okubo fixture). The +s"[+ mlue]" force-include override (manual §7.21 pt5) is not yet surfaced; the default always excludes.
+gSExclude utterances consisting solely of word S--exclude-solo-word SDoneFixed 2026-05-22. CLAN’s MLU +gS overload (vs the inherited gem-segment filter) is now routed via per-subcommand rewriter branch to a new clap field --exclude-solo-word. Drops utterances whose every countable word is in the list. Case-insensitive.
+g@F+g from file--exclude-solo-word-fileDoneLanded 2026-05-23. Same idiom as COMBO/KWAL +s@F, rewriter intercepts +g@F before the per-word +gS arm, dispatch loads via load_search_expr_file and extends --exclude-solo-word. File format matches CLAN’s cutt.cpp::rdexclf: one pattern per line, skip blank lines, #-comments, and ;%*-annotation lines. Repeatable. Pinned by mlu_solo_word_from_file.
+o3Combine selected speakers into one result--combine-speakersDoneLanded 2026-06-05. CLAN mlu_isCombineSpeakers (mlu.cpp:721): pool every selected speaker’s utterances into one result rendered *COMBINED* (no :), with the morpheme/utterance/SD aggregate over the merged length list. +o3 is the ONLY valid MLU +o form (any other +o<x> is “Invalid argument”, mlu.cpp:723), so other values fall through to fail-closed. Modeled as MluConfig.combine_speakers; finalize pools the per-speaker utterance_lengths and the renderer emits *COMBINED* (gated on MluResult.combine_speakers). Reuses the FREQ +o3 --combine-speakers flag name + rewriter pattern. Byte-parity golden mlu_o3_combine (mor-gra.cha: CHI+MOT -> utt 2 / morph 11 / ratio 5.500 / SD 0.500); CLI pinned by mlu_o3_combines_speakers_into_one_block; rewriter by mlu_o3_and_word_form_noop_flags_rewrite.
+t%mor (implicit)Switch to %mor tier (special handling)(default)Donechatter reads %mor by default; +t%mor is a CLAN re-confirmation.
-t%morExclude %mor tier, implies --words semantics--wordsDoneLanded 2026-05-23. Rewriter special-cases -t%mor under MLU/MLT to emit --words instead of the generic --exclude-tier mor (which MLU/MLT’s clap doesn’t accept). Pinned by mlu_exclude_mor_tier_maps_to_words, mlt_exclude_mor_tier_maps_to_words, and the fall-through mlu_exclude_non_mor_tier_falls_through (which confirms -t%pho and other non-%mor values still route to the generic --exclude-tier).

General +-flags MLU inherits (from cutt.cpp::mainusage)

CLAN flagMeaningChatterStatusNotes
+t*X / -t*XInclude/exclude speaker--speaker / --exclude-speakerDone+tX (no *) also accepted post-2026-05-21 fix. Bare +t* (star, NOTHING after) is a hidden alias for +o3 (mlu.cpp:735, *f == '*' && *(f+1) == EOS sets mlu_isCombineSpeakers) -> --combine-speakers; pinned by mlu_bare_star_t_combines_like_o3.
+t%X / -t%XInclude/exclude dependent tier %X--tier / --exclude-tier (rewriter target)Rewriter onlyNo clap field on MLU; only +t%mor is handled implicitly by the default-mor logic. Other %X errors at parse time.
+t@ID="..."Filter by @ID pattern--id-filterDoneLive-probed against CLAN MLU on tiers/mor-gra.cha with `+t@ID=*
+t#ROLEFilter by role--roleDoneFixed 2026-05-22; see FREQ for the shared implementation.
+s"word" / -s"word"Include/exclude word in counting--include-word / --exclude-wordPartialMLU’s +s has command-specific scope. The untranscribed forms (+sxxx/+syyy/-sxxx/+swww/…) are now handled (rows above). Still Partial: the postcode force-include forms +s"[+ mlue]"/+s"[+ trn]" (manual §7.21 pt5) and the [+ mlue]-bracket / retrace-pattern (+s+"</>") search forms; chatter’s general word filter is the simple form only.
+s@F / -s@FSearch / exclude words from file--include-word-file / --exclude-word-fileDoneLanded 2026-05-22. File format: one pattern per line; blank lines, # -comments, and ;%* -annotation lines skipped. Repeatable.
+gX(in MLU: utterance-elision, see above)--gem (banner default)Partial+g collides between MLU’s elision semantic and the general gem filter. CLAN’s MLU +g is the elision meaning per getflag; --gem is the general filter (semantics differ). Confusing in CLAN itself.
+zN-MUtterance range--rangeDone
+rNVarious retrace / clitic / prosodic-symbol / replacement controls--include-retracings (+r6); +r1/+r2/+r3/+r4/+r5/+r7 no-opDone+r6 (include retracings) is the only +r with a real MLU effect (--include-retracings). +r1/+r2/+r3/+r4/+r5/+r7 are FAITHFUL NO-OPS: they tune the word FORM, but MLU counts morphemes (from %mor) or words (-bw) and never displays a form, so they change nothing (probe-confirmed 2026-06-05: morpheme total 6 and word total 189 identical with/without on mor-gra.cha and 000829.cha, both modes). MLU enables R_OPTION (option_flags[MLU], cutt.cpp:8674), so CLAN accepts them; effect is +s-search only, like +k. Rewriter consumes them (vec![]); pinned by mlu_word_form_flags_are_noops_* and mlu_o3_and_word_form_noop_flags_rewrite. +r8/+r50 carry over from FREQ as MOR/cross-tier deferred.
+uCombine across files--combine-files (+d1 rows)DoneMLU +d1 is per-file by default; +u aggregates those rows. The normal summary already aggregates files in chatter.
+reRecurse subdirectories(default for directory args)Done
+pSAdd S to word delimiters– (no-op)DoneFAITHFUL NO-OP. MLU enables P_OPTION (option_flags[MLU], cutt.cpp:8674) so CLAN accepts +pS, but the extra word delimiters never reach MLU’s morpheme/word count (probe-confirmed 2026-06-05: morphemes 196 and words 189 unchanged with +p_ on 000829.cha, where choo_choo stays one word and the %mor tier already has choochoo). Unlike FREQ, MLU does not re-tokenize on +p. Rewriter consumes it (vec![]); pinned by the mlu_word_form_flags_are_noops_* tests.
+kCase-sensitive matching--case-sensitive (via CommonAnalysisArgs)Done (no-op per CLAN)MLU does no word-keying; +k is silently accepted per CLAN’s cutt.cpp::mainusage no-op semantic. Covered by CommonAnalysisArgs.case_sensitive flatten on ClanCommands::Mlu.
+wN / -wNContext window (KWAL/COMBO keyword-context)–Rewriter onlyInapplicable to MLU (per-speaker morpheme means, no per-match context to surround). The rewriter maps +wN/-wN to --context-after/--context-before, but MLU has no such clap field, so it errors at parse time, the correct outcome for an inapplicable flag (talkbank-clan/AGENTS.md). CLAN’s binary instead empties the output (a context-machinery artifact).
+f / +fEXTOutput to file--output-ext (rewriter target)Rewriter onlyPhase 1.1 sidecar work.

MLU +d display modes

Both MLU display modes are implemented: bare +d writes SpreadsheetML, while +d1 writes tab-separated rows.

Audit summary

BucketCount
Done (byte-parity or in scope)21
Partial (chatter abstraction differs)4
Rewriter only (would error at parse time)2
Missing (no rewriter, no clap field)2 (+cS, +c@F)

The remaining Missing rows are the clause-marker family (+cS / +c@F, which breaks utterances into clauses and relabels the output). The Documented CLAN-bug divergences below record the +syyy manual conflict.

Documented CLAN-bug divergences

FlagDivergenceAdjudication
+syyyThe CLAN binary re-includes yyy-containing utterances (ml_isYYYFound, mlu.cpp:776) AND prints the DEFAULT exclusion header (no yyy-only branch, mlu.cpp:246-253). The manual §7.21 pt2 says yyy “cannot be included.” chatter reproduces the binary exactly (the chatter-clan parity oracle), so +syyy matches the binary including the header quirk.The manual-vs-binary conflict is a genuine adjudication item for the PI / CLAN maintainer: should +syyy be an error (per the manual) or an include (per the binary)? chatter follows the binary until that is resolved, rather than diverging on a solo call.

The +g overload is the most subtle issue: MLU’s command-specific +g means “exclude an utterance if it consists solely of the given word” (a special-case elision filter), but chatter’s --gem inherited from CommonAnalysisArgs means “restrict to gem segment labelled S” (a general gem filter). Identical syntax, different semantics, a CLAN user pasting mlu +gum file.cha (skip um-only utterances) gets gem-label filtering in chatter (a no-op for files with no @G um gem). Tracked as a Phase 1.7 follow-up.

Display Modes (+dN)

Both +d and +d1 are implemented. Bare +d writes SpreadsheetML; it is not emulated as CSV.

MLU’s +d table is small, two N-values, both Excel-friendly output formats. Quoted from CLAN manual §7.21.2:

NCLAN behavior (verbatim from manual)
+d (no number)“You can use this switch, together with the ID specification to output data for Excel.” CLAN writes a <basename>.mlu.xls SpreadsheetML file. Implemented by --spreadsheet.
+d1“This level of the +d switch outputs data in another systematic format, with data for each speaker on a single line. However, this form is less adapted to input to a statistical program than the output for the basic +d switch. Also, this switch works with the +u switch, whereas the basic +d switch does not.” Implemented by --id-rows; the first column retains the input path, and --combine-files reproduces +u.

Binary probe (2026-10-31): the manual is OUTDATED; the binary is the parity oracle. Probing the current CLAN on mor-gra.cha shows the actual behavior differs from the manual’s examples:

  • +d (no number) writes a SpreadsheetML file <basename>.mlu.xls (stdout only reports Output file <...>); it does NOT print the *CHI: ... line. This is the same family as FREQ +d2/+d3 (semantic-equivalence standard, not byte, per the talkbank-clan crate guide), and forces @ID: header selection (the banner adds “and ONLY header tiers matching: @ID:”).
  • The workbook uses a File column with each input basename, the expanded @ID columns, utterance and morpheme counts, MLU, and standard deviation. -bw changes the count columns to #words and words/utterances. Multiple input files contribute rows to one workbook named from the first input. +o3 emits a pooled *COMBINED* row. When a speaker has no @ID, CLAN fills the Code cell with that speaker and emits . for the other ID cells (mlu.cpp:291-296); chatter matches this fallback.
  • +d1 prints TAB-separated, @ID-FIELD-EXPANDED lines to stdout, one per speaker, NOT the *CHI: 5 7 ... form the manual shows. On mor-gra.cha: pipeout<TAB>eng<TAB>corpus<TAB>CHI<TAB>3;00.<TAB>.<TAB>.<TAB>.<TAB>Child<TAB>.<TAB>.<TAB> 1<TAB> 6<TAB> 6.000<TAB>NA (input path, then the ten @ID fields with empties rendered ., then padded utterances / morphemes / MLU / SD). CLAN echoes the supplied path; its stdin name is pipeout.

The +d1 implementation uses parsed @ID fields, emits rows per file by default, and pools them across files with +u. For +o3, it emits zero-valued individual speaker rows followed by the pooled row.

Algorithm

For each utterance with a %mor tier:

  1. Count 1 per stem (the base morpheme word)
  2. Count +1 per bound morpheme suffix – but ONLY these 7 suffix strings: PL, PAST, Past, POSS, PASTP, Pastp, PRESP
  3. Count +1 per clitic stem (~ separated)
  4. Count clitic suffixes using the same 7-string rule
  5. Fusional features (&PRES, &INF, etc.) do NOT count

Per speaker, compute:

  • Number of utterances
  • Total morphemes
  • MLU (mean = total morphemes / utterances)
  • Standard deviation (population SD, dividing by n)
  • Range (min, max morphemes per utterance)

Brown’s Morpheme Rules

This was a key discovery during parity verification. CLAN only counts 7 specific suffix strings as bound morphemes:

SuffixMeaning
PLPlural
PASTPast tense
PastPast tense (alternate)
POSSPossessive
PASTPPast participle
PastpPast participle (alternate)
PRESPPresent participle

All other suffixes (including fusional features like &PRES, &INF, &3S) are ignored for MLU counting. This matches Brown’s (1973) original operationalization of “morpheme” for child language analysis.

Example

Given %mor: pro|I v|want-PAST det|a n|cookie-PL:

  • pro|I = 1 stem = 1
  • v|want-PAST = 1 stem + 1 suffix (PAST) = 2
  • det|a = 1 stem = 1
  • n|cookie-PL = 1 stem + 1 suffix (PL) = 2
  • Total: 6 morphemes

Output

Speaker: CHI
  Utterances: 42
  Morphemes: 168
  MLU: 4.000
  SD: 1.732
  Range: 1-9

Differences from CLAN

Standard deviation

Uses population SD (dividing by n), not sample SD (dividing by n-1). Verified against CLAN output – CLAN uses population SD too.

Morpheme counting

Uses parsed %mor tier structure (MorWord features and post-clitics) rather than text splitting on spaces and delimiters. The semantic result is identical thanks to applying Brown’s 7-suffix rule, but the mechanism is type-safe.

No %mor tier behavior

When no %mor tier exists and --words was not passed, reports 0 utterances for the speaker (matching CLAN). Does not silently fall back to word counting.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

100% parity with CLAN C binary output.

MODREP, Model/Replica Comparison

Status: Current Last updated: 2026-05-26 10:20 EDT

Purpose

Compares the model (target) pronunciation on the %mod tier with the actual (replica) pronunciation on the %pho tier, tracking word-by-word mappings between model forms and replica forms. This is used in phonological analysis to assess how closely a speaker’s productions match the adult target forms.

See the CLAN manual for the original MODREP command specification.

Usage

chatter-clan modrep file.cha
chatter-clan modrep file.cha --speaker CHI

Algorithm

  1. For each utterance with both %mod and %pho tiers:
    • Extract word lists from both tiers (flattening groups)
    • Pair words positionally (model word N <-> replica word N)
    • Record each (model, replica) pair in a frequency map per speaker
  2. Report per-speaker tables of model words with their replica variants and frequency counts

Options (chatter-native)

OptionCLAN flagDescription
--speaker <code>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <code>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--format <fmt>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

MODREP-specific +-flags (from modrep.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aSort output by descending frequency,MissingCLAN’s modrep.cpp:1431 sets isSort = TRUE, gating a frequency-sorted output path at line 659. chatter’s finalize step at commands/modrep.rs:174-203 iterates BTreeMap<String, ModelWordData> in alphabetical-ascending key order; the result struct has no sort mode. A prior version of this row claimed Done-by-default; that was a mis-classification surfaced by the 2026-05-26 audit-vs-runtime sweep. Real Tier-4 feature work: add a sort-mode enum to ModrepConfig, the rewriter arm, and a frequency-sorted output path.
+bSSet model tier name to S (e.g. +b*CHI or +b%hes); S = "*" to use +t@ID=,Missingchatter hard-codes %mod as the model tier.
+cSSet replica tier name to S,Missingchatter hard-codes %pho as the replica tier.
+dSpreadsheet output,MissingPer OSX-CLAN/src/clan/modrep.cpp:1492, CLAN’s +d is a no-arg toggle (no_arg_option(f); isExcel = TRUE). chatter has no --format csv for MODREP. Per-MODREP arm in clan_args.rs passes the token through so clap reports the literal +d argument.
+nS / +n@FWord S (or file @F) included in output associated with +c,MissingReplica-side word allowlist.
+oS / +o@FWord S (or file @F) included in output associated with +b,MissingModel-side word allowlist.
+o3Combine selected speakers per filepartial via --per-file inversePartial
+sS / -sSWord S included/excluded from input--include-word / --exclude-wordDone

Audit summary

BucketCount
Done5
Partial1
Rewriter only3
Missing7

MODREP’s biggest gap is the tier-name customization (+bS, +cS): researchers using non-default model/replica tier names cannot redirect chatter’s MODREP. The +nS / +oS word allowlists are also missing, which limits MODREP to whole-file comparisons rather than targeted lexical subsets.

Output

Per-speaker listing of model words, each with its set of replica variants and their frequency counts, sorted alphabetically by model word.

Differences from CLAN

  • Model and replica extraction uses parsed %mod and %pho tier structures from the AST rather than raw text line parsing
  • Word pairing operates on typed PhoWord content rather than string splitting
  • Output supports text, JSON, and CSV formats (CLAN produces text only)
  • Deterministic output ordering via sorted collections
  • Golden test parity: Verified against CLAN C binary output

MOR – Morphological Analysis (deliberately not implemented)

Status: Reference – stub command Last updated: 2026-05-22 13:14 EDT

Purpose

In legacy CLAN, mor adds %mor dependent tiers to CHAT files by performing morphological analysis of main-tier words against language-specific lexicon databases (trie-based, ~11,000 lines of C) and five rule engines (A-rules, C-rules, D-rules, PREPOST rules, allomorph rules).

This project does not implement mor. The CHAT grammar and data model have moved to UD-style (Universal Dependencies) morphological representation, which is incompatible with the legacy CLAN MOR format. A faithful port is impractical and would diverge from the rest of the toolchain on the very dimension the command is meant to serve.

What to use instead

Use the upstream batchalign3 morphotag pipeline, which produces %mor and %gra tiers via Stanza’s UD-trained neural models. It supports more languages with higher accuracy than the legacy CLAN MOR grammars.

batchalign3 morphotag corpus/  # neural morphosyntax pipeline

See the batchalign3 project’s morphosyntax reference for the full pipeline.

Behavior

Invoking chatter-clan mor prints an error directing users to batchalign and exits with a non-zero status. No CHAT files are modified.

CLAN +-flag coverage audit

Exempt: MOR is a deliberate non-implementation (see Purpose above). Per the workspace policy, the MOR-pipeline commands (mor, post, postlist, postmodrules, posttrain, megrasp) are stubs that emit a refusal and direct users to batchalign’s neural pipeline. The CLAN +-flag surface for each is documented in CLAN’s own usage text and is not mirrored here because chatter does not consume those flags.

See also

MORTABLE – Morphological Category Cross-Tabulation

Status: Current Last updated: 2026-05-22 09:49 EDT

Purpose

Produces a per-speaker frequency table of morphosyntactic categories by matching POS tags from the %mor tier against patterns defined in a language-specific script file.

Requires a language script file (e.g., eng.cut) that defines patterns and their labels for categorizing morphemes from the %mor tier. Each rule line contains a quoted label and +/- prefixed POS patterns. Rules can be grouped as OR (first match wins) or AND (all must match).

See the CLAN manual for the original MORTABLE command specification.

Note on -f short flag. Both --script and --format declare -f as their short flag in crates/talkbank-cli/src/cli/args/clan_commands.rs:260 and :345. clap currently accepts this, chatter-clan mortable --help runs successfully and -f test.cut resolves to --script, so the previous warning that the command was “unusable” no longer applies. Verified 2026-05-12 by invoking chatter-clan mortable --help and chatter-clan mortable -f test.cut file.cha. Prefer the long form --script / --format in scripts to avoid ambiguity in future clap upgrades.

Usage

chatter-clan mortable --script eng.cut file.cha
chatter-clan mortable --script eng.cut --speaker CHI file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--script <PATH>+lFLanguage script file (.cut), required
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

MORTABLE is a required-flag refusal command in chatter, emits the exact CLAN refusal when +lF (or --script F) is absent.

MORTABLE-specific +-flags (from mortable.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+lFSpecify language script file F (required)--script <PATH>DoneDirect mapping; rewriter routes +lF → --script F for MORTABLE (since the per-subcommand routing batch).
+o3Combine selected speakers per filepartial via --per-file inversePartial
+o4Output raw values instead of percentage values,Rewriter only

Audit summary

BucketCount
Done6
Partial1
Rewriter only4
Missing4

Differences from CLAN

  • POS matching: Operates on parsed %mor tier data rather than raw text line scanning.
  • POS matching detail: POS tags are read directly from typed %mor items instead of reparsing serialized %mor content.
  • Script file format: Compatible with CLAN’s .cut files.
  • Output formats: Supports text, JSON, and CSV formats.
  • Deterministic ordering: BTreeMap ordering ensures deterministic output across runs.
  • Golden test parity: Verified against CLAN C binary output.

ORT – Orthographic Conversion via Dictionary Lookup

Status: Current Last updated: 2026-05-22 13:07 EDT

Purpose

Reimplements CLAN’s CONVORT command, which applies orthographic conversion rules from a dictionary file to main-tier words. When a word is modified, the original main-tier text is preserved on a %ort: dependent tier for reference.

Usage

chatter-clan ort --dictionary ort.cut file.cha

Options

OptionTypeDefaultDescription
-d, --dictionarypath(required)Path to the orthographic conversion dictionary
-o, --outputpathstdoutOutput CHAT file path

CLAN +-flag coverage audit

ORT is a transform. Sources: OSX-CLAN/src/clan/ort.cpp::usage, crates/talkbank-clan/src/transforms/ort.rs.

ORT-specific +-flags (from ort.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+cFHomons table file name (default 0canhomo.cut)-d / --dictionary <PATH>DoneDirect mapping; chatter requires the path explicitly (no default path search). Rewriter routes +cF → --dictionary F (since 2026-05-22).

Audit summary: 1 Done, 0 Missing.

External Data

Requires an orthographic conversion dictionary. CLAN uses ort.cut from its lib/ directory by default; chatter-clan ort does not bundle a dictionary, so --dictionary must be passed explicitly. Format: from_word to_word (one pair per line, tab or space separated). Lines starting with # or ; are treated as comments. Lookups are case-insensitive.

Behavior

For each utterance, the transform:

  1. Serializes the original main tier content for preservation.
  2. Applies dictionary-based word substitutions on the main tier.
  3. If any words were modified, inserts a %ort: dependent tier containing the original (pre-conversion) main-tier text.

Differences from CLAN

  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).

PHONFREQ, Phonological Frequency Analysis

Status: Current Last updated: 2026-05-22 09:40 EDT

Purpose

Counts individual phone (character) occurrences from %pho tier content, tracking positional distribution within each phonological word: initial (first character), final (last character), and other (middle positions). Counts alphabetic characters (Unicode, including IPA) plus the + compound marker; stress marks (ˈ, ˌ), length marks (ː), digits, and other non-letter symbols are skipped (crates/talkbank-clan/src/commands/phonfreq.rs:178).

See the CLAN manual for the original PHONFREQ command specification.

Usage

chatter-clan phonfreq file.cha
chatter-clan phonfreq file.cha --speaker CHI

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN phonfreq flag. Sources:

  • OSX-CLAN/src/clan/phonfreq.cpp: usage().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() PHONFREQ branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Phonfreq plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

PHONFREQ has the narrowest command-specific surface, a single flag.

PHONFREQ-specific +-flags (from phonfreq.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+bSSet phonological tier name to S (default %pho),Missingchatter hard-codes %pho. Users with non-standard phonological tiers (e.g. %xpho) cannot redirect.

Audit summary

BucketCount
Done6
Partial1
Rewriter only4
Missing7

PHONFREQ’s body parity already matches CLAN byte-for-byte (Unicode-block sort + byte-width column padding landed in the squash). The remaining gap is the +bS tier-name selector, a one-line clap field addition.

Output

Per-phone frequency with positional breakdown (initial/final/other), sorted alphabetically by phone character.

Differences from CLAN

  • Phone extraction uses parsed %pho tier structure from the AST rather than raw text character scanning
  • Positional classification operates on typed PhoWord content
  • Output supports text, JSON, and CSV formats (CLAN produces text only)
  • Deterministic output ordering via sorted collections
  • Golden test parity: Verified against CLAN C binary output

PLAY2CHAT – PLAY Annotation to CHAT Conversion

Status: Current Last updated: 2026-05-22 13:40 EDT

Purpose

Converts PLAY (Phonological and Lexical Acquisition in Young children) annotation files into CHAT format.

Usage

chatter-clan play2chat input.play

Options

OptionDefaultDescription
-l, --language"eng"ISO 639 language code for the @Languages header
-o, --outputstdoutOutput CHAT file path

The corpus name in @ID headers is hardcoded to "play_corpus" (crates/talkbank-clan/src/converters/play2chat.rs:92); there is no CLI flag to override it. If you need a different corpus name, post-edit the generated @ID lines or call play_to_chat_with_options() from Rust.

Input Format

Tab-separated fields: speaker, start_time, end_time, text. Times are in milliseconds and may be empty. Lines starting with # or % are skipped. Lines with fewer than 2 tab-separated fields are ignored.

Example:

CHI	1000	3500	hello world
MOT	4200	6800	how are you

Output

A well-formed CHAT file with headers and participants. Unique speakers are automatically collected and registered as CHAT participants with the Unidentified role. Each PLAY entry becomes an utterance, with timing bullets when start/end times are provided.

Differences from CLAN

  • Uses typed AST for CHAT generation
  • Produces valid, well-formed CHAT output

CLAN +-flag coverage audit

PLAY2CHAT is a converter: input Datavyu text, output CHAT. Sources: OSX-CLAN/src/clan/Play2Chat.cpp::usage, crates/talkbank-clan/src/converters/play2chat.rs.

PLAY2CHAT-specific +-flags (from Play2Chat.cpp::usage)

CLAN flagMeaningChatterStatus
+dCheck utterances for illegal overlaps,Missing

Audit summary: 1 Done (default conversion), 1 Missing. The overlap-check is a validation pass that chatter does not run; researchers wanting that check can pipe the output to chatter-clan check.

POST – POS Disambiguation (deliberately not implemented)

Status: Reference – stub command Last updated: 2026-05-22 13:14 EDT

Purpose

In legacy CLAN, post disambiguates the multiple part-of-speech candidates that mor emits on a %mor tier, choosing the most likely category for each token based on a trained model and a context-sensitive rule database.

This project does not implement post. It is part of the legacy CLAN MOR/POST grammar pipeline (see mor) and depends on the same lexicon and rule artifacts that we deliberately do not port.

What to use instead

Use the upstream batchalign3 morphotag pipeline. Stanza’s neural models produce a single disambiguated POS per token at inference time, so a separate post-pass is not needed.

Behavior

Invoking chatter-clan post prints an error and exits non-zero. No CHAT files are modified.

See also

CLAN +-flag coverage audit

Exempt: see MOR for the shared MOR-pipeline policy: chatter does not consume CLAN’s +-flags for any command in this family. CLAN’s own usage text documents the legacy flag surface; chatter emits a refusal that points users to batchalign.

POSTLIST – List POST Database Contents (deliberately not implemented)

Status: Reference – stub command Last updated: 2026-05-22 13:14 EDT

Purpose

In legacy CLAN, postlist enumerates the contents of the POST disambiguation rule database for a given language. It is a developer inspection tool for the model that post consults at runtime.

This project does not implement postlist. The POST rule database does not exist here – the neural morphotag pipeline (see mor) replaces it.

What to use instead

There is no direct replacement; Stanza models do not expose an equivalent inspectable rule database. For developer inspection of batchalign’s morphotag output, dump the raw Stanza JSON via the worker’s debug logging, or operate on the typed Mor values in the talkbank-model crate.

Behavior

Invoking chatter-clan postlist prints an error and exits non-zero.

See also

CLAN +-flag coverage audit

Exempt: see MOR for the shared MOR-pipeline policy: chatter does not consume CLAN’s +-flags for any command in this family. CLAN’s own usage text documents the legacy flag surface; chatter emits a refusal that points users to batchalign.

POSTMODRULES – Modify POST Database Rules (deliberately not implemented)

Status: Reference – stub command Last updated: 2026-06-14 19:57 EDT

Purpose

In legacy CLAN, postmodrules edits the POST disambiguation rule database – it allows researchers to update the context-sensitive rules that post applies, without retraining the full model.

This project does not implement postmodrules. The POST rule database does not exist here – the neural morphotag pipeline (see mor) supersedes it.

What to use instead

There is no direct replacement. Custom morphology rules are not part of the upstream batchalign3 neural pipeline; the Stanza models are trained end-to-end. For per-language overrides, the upstream batchalign3 project documents its own contributor entry point for non-English workarounds.

Behavior

Invoking chatter-clan postmodrules prints an error and exits non-zero.

See also

CLAN +-flag coverage audit

Exempt: see MOR for the shared MOR-pipeline policy: chatter does not consume CLAN’s +-flags for any command in this family. CLAN’s own usage text documents the legacy flag surface; chatter emits a refusal that points users to batchalign.

POSTMORTEM – Pattern-Matching Rules for %mor Post-Processing

Status: Current Last updated: 2026-05-22 13:11 EDT

Purpose

Reimplements CLAN’s POSTMORTEM command, which applies pattern-matching and replacement rules to dependent tiers (typically %mor:). Rules are applied sequentially, and wildcard tokens (*) match any single token. The replacement side uses $- to copy the matched wildcard text.

The CLAN manual does not appear to contain a standalone POSTMORTEM command section. It is mentioned indirectly as part of the mor *.cha pipeline that runs MOR, PREPOST, POST, POSTMORTEM, and MEGRASP to produce %mor and %gra.

Usage

chatter-clan postmortem --rules postmortem.cut file.cha
chatter-clan postmortem --rules rules.cut --target-tier spa file.cha

Options

OptionTypeDefaultDescription
-r, --rulespath(required)Path to the rules file
--target-tierstring"mor"Target tier label to apply rules to
-o, --outputpathstdoutOutput CHAT file path

CLAN +-flag coverage audit

POSTMORTEM is a transform. Sources: OSX-CLAN/src/clan/postmortem.cpp::usage, crates/talkbank-clan/src/transforms/postmortem.rs.

POSTMORTEM-specific +-flags (from postmortem.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aCreate files with ambiguous results (default: no ambiguous),MissingAmbiguity-output policy.
+a1Interactive disambiguation (non-UNX only),MissingInteractive mode; out of scope for a CLI tool.
+a2Mark all changes (with color on non-UNX),MissingDiff-style output.
+cFDictionary/rules file (default postmortem.cut)--rules <PATH>DoneDirect mapping. chatter requires explicit path.
+MFPath of mor lib folder (UNX only),MissingLibrary lookup.
+p1Look for postmortem.cut in working directory first,MissingPath-search heuristic.

Audit summary

BucketCount
Done1
Missing5

POSTMORTEM’s +a variants are output-policy switches (ambiguity handling, interactive disambiguation, change-marking). chatter implements only the default “non-ambiguous, no marking” behaviour. Filed as Phase 1.7 follow-ups; not load-bearing for the typical rule-application workflow.

External Data

Requires a rules file. CLAN uses postmortem.cut from its lib/ directory by default; chatter-clan postmortem does not bundle a rules file, so --rules must be passed explicitly. Format: from_pattern => to_replacement (one rule per line, using => or ==> as the separator). Lines starting with # or ; are comments.

Wildcards: * in the pattern matches any single token. $- in the replacement copies the matched wildcard text.

Behavior

For each utterance, the transform:

  1. Finds the target dependent tier (default: %mor:).
  2. If the target is a user-defined text tier, tokenizes its content.
  3. Applies each rule sequentially, matching patterns and performing substitutions.
  4. Stores the modified result back on the tier.

Differences from CLAN

  • Manual coverage gap: the CLAN manual only mentions POSTMORTEM indirectly through the MOR pipeline, so this chapter cannot yet rely on a standalone legacy command spec.
  • Typed %mor safety: If a rule would change a parsed %mor tier, POSTMORTEM fails explicitly until an AST-based %mor rewrite exists, rather than degrading typed morphology into user-defined text.
  • User-defined target tiers are still supported as text rewrite targets.
  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).

POSTTRAIN – Train POST Model (deliberately not implemented)

Status: Reference – stub command Last updated: 2026-05-22 13:14 EDT

Purpose

In legacy CLAN, posttrain trains the POST disambiguation model from a hand-annotated training corpus. It is the offline counterpart to the runtime post disambiguator.

This project does not implement posttrain. The MOR/POST training pipeline is replaced by Stanza’s neural-model training infrastructure, which lives upstream of batchalign and is not part of this toolchain.

What to use instead

To train new morphological models, use Stanza’s training pipeline directly (see the Stanza documentation), then route the resulting models through batchalign’s morphotag pipeline.

Behavior

Invoking chatter-clan posttrain prints an error and exits non-zero.

See also

CLAN +-flag coverage audit

Exempt: see MOR for the shared MOR-pipeline policy: chatter does not consume CLAN’s +-flags for any command in this family. CLAN’s own usage text documents the legacy flag surface; chatter emits a refusal that points users to batchalign.

PRAAT2CHAT – Praat TextGrid Bidirectional Conversion

Status: Current Last updated: 2026-05-22 13:40 EDT

Purpose

Converts between Praat TextGrid files and CHAT format. TextGrid files contain time-aligned interval tiers widely used in phonetic research.

Usage

chatter-clan praat2chat input.TextGrid

Conversion Functions

DirectionFunctionDescription
TextGrid to CHATpraat_to_chat()Convert TextGrid intervals to CHAT utterances
CHAT to TextGridchat_to_praat()Convert timed CHAT utterances to TextGrid intervals

Options

OptionDefaultDescription
-l, --language"eng"ISO 639 language code for the @Languages header
-o, --outputstdoutOutput CHAT file path

The corpus name in @ID headers is hardcoded to "praat_corpus" (crates/talkbank-clan/src/converters/praat2chat.rs:200); there is no CLI flag to override it. Same pattern as the other converters in this directory.

TextGrid Format Support

Both long (normal) and short TextGrid formats are supported. Tier names are mapped to CHAT speaker codes (first 3 characters, uppercased). Empty intervals and point tiers are skipped. Untimed utterances are excluded from CHAT-to-TextGrid conversion.

Input Format

Praat TextGrid files (.TextGrid) containing interval tiers with time-aligned text segments.

Output

TextGrid to CHAT: A well-formed CHAT file with timing bullets derived from interval boundaries. Each non-empty interval becomes a timed utterance.

CHAT to TextGrid: A Praat TextGrid file with one interval tier per speaker, containing text from timed utterances.

Differences from CLAN

  • Uses typed AST for CHAT generation
  • Produces valid, well-formed CHAT output
  • Supports bidirectional conversion (CHAT to TextGrid and TextGrid to CHAT)
  • Handles both long and short TextGrid formats

Reference

See the CLAN manual for the original PRAAT2CHAT command documentation.

CLAN +-flag coverage audit

PRAAT2CHAT is a converter: input Praat .TextGrid, output CHAT. Sources: OSX-CLAN/src/clan/Praat2Chat.cpp::usage, crates/talkbank-clan/src/converters/praat2chat.rs.

PRAAT2CHAT-specific +-flags (from Praat2Chat.cpp::usage)

CLAN flagMeaningChatterStatus
+bMultiple bullets per line,Missing
+dFAttribs/tags dependencies file,Missing
+oSCode page (utf8, macl, pcl, …),Missing

Audit summary: 1 Done (default conversion), 3 Missing. Same metadata-options gap as ELAN2CHAT and LAB2CHAT.

QUOTES – Extract Quoted Text to Separate Utterances

Status: Current Last updated: 2026-05-22 12:52 EDT

Purpose

Reimplements CLAN’s QUOTES command.

This is a relatively uncommon command used for discourse analysis of reported speech.

Usage

chatter-clan quotes file.cha

Options

This command has no command-specific flags beyond the shared -o, --output <PATH> (default: stdout). See Output Formats for the transform output flag.

CLAN +-flag coverage audit

QUOTES is a transform. Sources: OSX-CLAN/src/clan/quotes.cpp::usage, crates/talkbank-clan/src/transforms/quotes.rs.

CLAN’s quotes.cpp::usage lists no command-specific +-flags the surface is the inherited general flag set only (none of which apply to a pure transform). chatter’s QUOTES surface is likewise minimal: input CHAT file in, transformed CHAT out.

Audit summary

BucketCount
Done1 (default extract-quoted behaviour)
Missing0

QUOTES is one of the cleanest parity stories in the catalog, both CLAN and chatter expose the identical “do the obvious thing” surface and produce comparable output. No follow-ups filed.

Behavior

The Rust port now inspects the parsed CHAT AST directly.

  • If no quote-extraction postcode ([+ "]) is present, the command is a semantic no-op and emits normalized CHAT.
  • If [+ "] is present, the command fails with an explicit error. talkbank-clan does not silently fall back to post-serialization string manipulation for this transform.

Differences from CLAN

  • Does not currently implement CLAN’s text-level extraction rewrite for [+ "].
  • Fails explicitly on unsupported quote-extraction postcodes instead of attempting a lossy raw-text rewrite.

RELY, Inter-Rater Reliability (Cohen’s Kappa)

Status: Current Last updated: 2026-05-22 09:48 EDT

Purpose

Compares two parallel CHAT files for coder agreement. The legacy manual gives RELY five functions: coder agreement, Cohen’s kappa, student-vs-master evaluation, rough transcript overlap on the main line, and selective dependent-tier merging.

The current talkbank-clan implementation focuses on the coding-tier comparison use case: it compares coded data on a specified dependent tier (default %cod) across two files to compute per-code agreement statistics, overall agreement percentage, and Cohen’s kappa coefficient.

See the CLAN manual for the original RELY command specification.

Usage

chatter-clan rely file1.cha file2.cha
chatter-clan rely file1.cha file2.cha --tier spa

Algorithm

  1. Parse both input files and extract codes per utterance from the specified tier
  2. Align utterances by position (index)
  3. For each aligned pair, count per-code agreements (minimum of the two counts for each code in that utterance)
  4. Compute overall observed agreement (Po) and expected agreement (Pe) for Cohen’s kappa: k = (Po - Pe) / (1 - Pe)

Options (chatter-native)

OptionCLAN flagDescription
--tier <name>+t%X (rewriter target)Tier label to compare (default: cod)
--format <fmt>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

RELY is a paired-file analysis (control + second file). The flag set is largely inherited; the command-specific flags govern which aspects of the comparison are computed.

RELY-specific +-flags (from rely.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aAdd tiers from second file to first (control) file,MissingTier-merging mode (not a kappa computation).
+bInclude BULLETS in string comparison,MissingBullets are CHAT-format media-link markers.
+cDo not compare data on non-selected tier,Missing
+c1Compare only main part of code ($COD:EX → just $COD),MissingCode-prefix granularity.
+dCompute percentage-agreement coefficient,Rewriter onlyMulti-dispatch (see Display Modes section).
+dmNCompute student correctness (m1 = first is control, m2 = second is control),Rewriter only
+dNCompute Cohen’s kappa with N possible categories,Rewriter onlychatter computes kappa always; N (category count) is not user-specifiable.
+uCompute kappa across all pairs of files,Missing
+mMerge files and place error flags in output,Missing

Audit summary

BucketCount
Done4
Partial0
Rewriter only4
Missing11

RELY has the most fragmented +d semantics of any CLAN command: +d (percentage), +dmN (student correctness), +dN (numeric kappa) all use the same flag letter with different shapes. Researchers expecting CLAN’s per-flag-shape behavior need the multi-dispatch wired through --display-mode.

Display Modes (+dN / --display-mode N), DRAFT, awaiting PI review

Status: drafted from CLAN manual; not yet implemented. Rewriter at crates/talkbank-clan/src/clan_args.rs:101 translates +dN → --display-mode N; no clap field consumes it today. Drafted from CLAN manual §7.24.1 (Unique Options, RELY) for PI review. RELY’s +d is a multi-dispatch flag with three distinct forms, bare, +dmN, and +dN (numeric kappa), that can’t all fit into a single scalar --display-mode N.

FormCLAN behavior (verbatim from manual)
+d (bare)“Compute percentage agreement. By default, this is based only on the main line. To compute percentage agreement on a dependent tier, such as %cod, you should add the -t* switch to exclude the main line and then use +t%cod to include just this dependent tier.”
+dmN“Compute student correctness. (+dm1, first file is control, +dm2 second file is control.)”
+dN“Compute Cohen’s kappa coefficient, where N is the number of categories.”

Open questions for PI review

  1. The three forms are modes, not numeric levels. Should chatter expose them as an enum (--mode percentage|student|kappa) with a separate --categories N for the kappa case, rather than try to overload --display-mode?
  2. +dN collides with the universal --display-mode N shape used by FREQ/KWAL/etc. The rewriter at clan_args.rs:101 doesn’t currently distinguish RELY’s +dN from FREQ’s +dN. Resolving this requires the rewriter to be subcommand-aware (similar to how +g1..+g5 are already CHECK-aware).
  3. +dmN is even more specific, small-N integer that picks which file is the control. The current rewriter has no +dm case; adding it requires explicit per-command branching.

Output

  • Per-code agreement statistics (count in each file, agreed count, agreement percentage)
  • Overall agreement percentage
  • Cohen’s kappa coefficient

Differences from CLAN

  • RELY requires two-file input and does not use the standard AnalysisCommand trait; it is invoked directly
  • Manual intent: The legacy manual gives special semantics for coding tiers such as %cod and %spa, and documents +c1 as comparing only the main part of a colon-delimited code.
  • Code extraction for %cod now uses a clan-local semantic %cod item layer derived from the parsed AST
  • Selector handling: %cod selectors such as <w4> and <w4-5> are preserved as item scope, not counted as compared code values.
  • Scope reduction: The current implementation does not yet cover all five legacy RELY functions described in the manual, and it does not yet implement the documented +c1 colon-prefix comparison mode.
  • Output supports text, JSON, and CSV formats
  • Golden test parity: Verified against CLAN C binary output

REPEAT – Mark Utterances Containing Revisions

Status: Current Last updated: 2026-05-22 12:57 EDT

Purpose

Reimplements CLAN’s repeat command, which adds a [+ rep] postcode to utterances from a target speaker that contain revision markers. Only utterances that do not already have [+ rep] are modified.

Usage

chatter-clan repeat --speaker CHI file.cha

Options

OptionTypeDefaultDescription
--speakerspeaker code(required)Target speaker to process. Only utterances from this speaker are checked.

CLAN +-flag coverage audit

REPEAT is a transform. Sources: OSX-CLAN/src/clan/repeat.cpp::usage, crates/talkbank-clan/src/transforms/repeat.rs.

REPEAT-specific +-flags (from repeat.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+tSSpecify target speaker S--speaker SDoneDirect mapping. The clap field is required, matching CLAN’s behaviour (no implicit “all speakers” mode).

Audit summary

BucketCount
Done1
Missing0

REPEAT has a single command-specific flag, mapped one-to-one. Parity is clean. The revision-marker classifier (is_revision_kind) is documented above and tracks CLAN’s default markers verbatim.

Revision Markers Detected

Per is_revision_kind() at crates/talkbank-clan/src/transforms/repeat.rs:81-87, three of the four RetraceKind variants trigger [+ rep]:

  • [//]: full retrace (RetraceKind::Full)
  • [///]: multiple retracing (RetraceKind::Multiple)
  • [/-]: reformulation (RetraceKind::Reformulation)

Note: Simple partial repetition ([/], RetraceKind::Partial) does not trigger the [+ rep] marker, that’s the “non-revision” case. (Earlier versions of this doc listed a [/?] “uncertain retracing” marker as the fourth case; there is no such marker, the grammar has exactly four retrace tokens, all listed above and at book/src/chat-format/retraces.md.)

Behavior

For each utterance from the target speaker, the transform checks whether the main-tier content contains any revision markers. If revision markers are found and the utterance does not already have a [+ rep] postcode, one is appended.

Utterances from other speakers are left unchanged.

Differences from CLAN

  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).

RETRACE – Add %ret Dependent Tier with Verbatim Main-Tier Copy

Status: Current Last updated: 2026-05-22 12:57 EDT

Purpose

Reimplements CLAN’s retrace command, which adds a %ret: dependent tier to each utterance containing a verbatim serialized copy of the main-tier content (including retrace markers, pauses, events, etc.). This serves as a reference tier preserving the original utterance text before other transforms modify it.

See the CLAN manual for the original command documentation.

Usage

chatter-clan retrace file.cha

Options

This command has no command-specific flags beyond the shared -o, --output <PATH> (default: stdout). See Output Formats for the transform output flag.

CLAN +-flag coverage audit

RETRACE is a transform. Sources: OSX-CLAN/src/clan/retrace.cpp::usage, crates/talkbank-clan/src/transforms/retrace.rs.

RETRACE-specific +-flags (from retrace.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+cSubstitute the %ret: line for the main line in output,Missingchatter always emits both. A --substitute-main boolean would close this.

Audit summary

BucketCount
Done1 (default emit-both)
Missing1

RETRACE’s +c is a one-line config addition (substitute-main boolean) plus a small render-time choice. Filed as a Phase 1.7 follow-up.

Behavior

For each utterance, the transform:

  1. Serializes the main tier to its full CHAT text representation.
  2. Extracts the content portion (after *SPEAKER:\t).
  3. Creates a %ret: user-defined dependent tier containing the verbatim content.
  4. Inserts the %ret: tier at position 0 (before other dependent tiers).

All headers are preserved. Existing dependent tiers are kept.

Differences from CLAN

  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).

ROLES, Rename Speakers

Status: Current Last updated: 2026-05-22 13:08 EDT

Purpose

Renames speaker codes throughout a CHAT file: in @Participants, @ID headers, and all main-tier speaker prefixes. Used to standardize speaker codes across a corpus.

Usage

chatter-clan roles --rename "EXP=INV" file.cha
chatter-clan roles --rename "Child=CHI" --rename "Mother=MOT" file.cha

Options

OptionDescription
-r, --rename "OLD=NEW"Rename speaker OLD to NEW (required, can be repeated). Splits on the first =; see crates/talkbank-cli/src/commands/clan/transforms.rs:172 for the parser.
-o, --outputOutput CHAT file path (default: stdout).

Behavior

Speaker codes are renamed in all structural locations:

  • @Participants header entries
  • @ID header speaker fields
  • Main-tier speaker prefixes (*OLD: becomes *NEW:)

Differences from CLAN

  • Operates on the typed AST rather than raw text.
  • Speaker codes are renamed in all structural locations via AST manipulation.

CLAN +-flag coverage audit

ROLES is a transform. Sources: OSX-CLAN/src/clan/roles.cpp::usage, crates/talkbank-clan/src/transforms/roles.rs.

ROLES-specific +-flags (from roles.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+cFDictionary file (original_code speaker_code speaker_role)--rename "OLD=NEW" (inline only)Partialchatter accepts inline OLD=NEW mappings as a repeatable flag; CLAN reads a dictionary file with three-column lines. Adding --rename-file <PATH> would close the file-list form.

Audit summary: 1 Partial (file-list form missing), 0 Missing. The semantic is also slightly narrower in chatter: CLAN’s dictionary maps OLD → (NEW_CODE, NEW_ROLE); chatter only remaps codes, not the participant role. Filed as a follow-up.

RTF2CHAT – Rich Text Format to CHAT Conversion

Status: Current Last updated: 2026-05-22 13:40 EDT

Purpose

Converts Rich Text Format (RTF) files into CHAT format by stripping RTF formatting commands and extracting plain text content.

Usage

chatter-clan rtf2chat input.rtf

Options

OptionDefaultDescription
-l, --language"eng"ISO 639 language code for the @Languages header
-o, --outputstdoutOutput CHAT file path

The corpus name in @ID headers is hardcoded to "rtf_corpus" (crates/talkbank-clan/src/converters/rtf2chat.rs:212); there is no CLI flag to override it. Same pattern as the other converters in this directory.

Processing Steps

  1. RTF stripping: Removes control words, groups, font/color/stylesheet tables, and converts Unicode escapes (\uN?) to characters. Handles \par (newline) and \tab (tab).
  2. Turn extraction: Looks for CHAT-style speaker prefixes (*CHI:, *MOT:) in the plain text. If none are found, all text is assigned to a default SPK speaker.
  3. CHAT construction: Builds a proper ChatFile with headers, participants, and utterances.

Input Format

RTF (.rtf) files, optionally containing CHAT-style speaker prefixes embedded in the rich text. Standard RTF control sequences are supported including font tables, color tables, stylesheets, Unicode escapes, and nested groups.

Output

A well-formed CHAT file. If the RTF contains CHAT-style speaker codes (*CHI:, *MOT:, etc.), those are preserved as proper CHAT speaker codes. Otherwise, all text is assigned to a default SPK speaker.

Differences from CLAN

  • Uses typed AST for CHAT generation
  • Produces valid, well-formed CHAT output

CLAN +-flag coverage audit

RTF2CHAT is a converter: input RTF, output CHAT. Sources: OSX-CLAN/src/clan/rtf2chat.cpp::usage, crates/talkbank-clan/src/converters/rtf2chat.rs.

RTF2CHAT-specific +-flags (from rtf2chat.cpp::usage)

CLAN flagMeaningChatterStatus
+aPretty-print RTF structure (diagnostic),Missing
+bPost-process legal CHAT output,Missing
+reRecurse subdirectories(default for directory input)Done
+oSCode page,Missing

Audit summary: 2 Done (default conversion + +re), 3 Missing. The +a diagnostic and +b post-process variants are power-user features; chatter handles the default conversion.

SALT2CHAT – SALT Transcription to CHAT Conversion

Status: Current Last updated: 2026-05-22 13:40 EDT

Purpose

Converts SALT (Systematic Analysis of Language Transcripts) transcription files into CHAT format. SALT is a widely used clinical transcription system with its own conventions for speaker codes, morpheme annotations, and error marking.

Usage

chatter-clan salt2chat input.slt

Options

OptionDefaultDescription
-l, --language"eng"ISO 639 language code for the @Languages header
-o, --outputstdoutOutput CHAT file path

The corpus name in @ID headers is hardcoded to "salt_corpus" (crates/talkbank-clan/src/converters/salt2chat.rs:193); there is no CLI flag to override it. Same pattern as the other converters in this directory.

Speaker Mapping

SALT codeCHAT speakerRole
CCHITarget_Child
EEXAInvestigator
PPAR(Parent)
IINV(Investigator)

SALT Annotation Stripping

SALT-specific annotations are removed during conversion:

  • Morpheme codes (word/3s –> word)
  • Error markers (word* –> word)
  • Maze markers ((word) –> skipped)
  • Comment markers ({...}, [...] –> skipped)
  • Bound morpheme markers (_word –> word)

Input Format

SALT transcription files with header lines (starting with $ or +) followed by speaker-prefixed utterance lines. SALT uses single-letter speaker codes and inline annotation conventions.

Output

A well-formed CHAT file with SALT speakers mapped to standard CHAT speaker codes, SALT-specific annotations stripped, and proper CHAT headers generated. Header metadata (participant name, age, gender, context) is extracted from SALT $ lines when available.

Differences from CLAN

  • Uses typed AST for CHAT generation
  • Produces valid, well-formed CHAT output

CLAN +-flag coverage audit

SALT2CHAT is a converter: input SALT, output CHAT. Sources: OSX-CLAN/src/clan/salt2chat.cpp::usage, crates/talkbank-clan/src/converters/salt2chat.rs.

SALT2CHAT-specific +-flags (from salt2chat.cpp::usage)

CLAN flagMeaningChatterStatus
+cSSpecial coding system (a/b/c/g/h/p/r/s for various researcher conventions),Missing
+hHandle <...> as [% ...] (default: as ["overlap"]),Missing
+lFCodes-on-separate-tier mapping file,Missing

Audit summary: 1 Done (default conversion), 3 Missing. Researcher-specific coding conventions are CLAN’s most-elaborate SALT2CHAT customization; chatter’s converter is one-size-fits- all.

SCRIPT, Compare Utterances to a Template

Status: Current Last updated: 2026-05-22 09:48 EDT

Purpose

Compares subject CHAT data against an ideal template file to compute accuracy metrics: words produced vs. expected, correct matches, omissions (in template but not produced), and additions (produced but not in template). Useful for evaluating scripted language samples such as picture descriptions or story retells.

See the CLAN manual for the original SCRIPT command specification.

Usage

chatter-clan script file.cha --template template.cha
chatter-clan script corpus/ --template template.cha --speaker CHI

Algorithm

  1. Parse the template CHAT file and build a word frequency map (ideal counts)
  2. For each subject utterance, accumulate word frequency counts
  3. At finalization, compute per-word matches (minimum of ideal and actual), omissions, and additions

Options (chatter-native)

OptionCLAN flagDescription
--template <path>+sFPath to template/script file (required)
--speaker <code>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <code>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--format <fmt>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

SCRIPT-specific +-flags (from script.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+eCount error codes in retraces or repeats (default: don’t count),MissingCounting-policy switch for error-marked words.
+sFSpecify template script file F (required)--template <path>DoneDirect mapping; rewriter routes +sF → --template F for SCRIPT (since the per-subcommand routing batch).

Audit summary

BucketCount
Done6
Partial0
Rewriter only4
Missing4

Display Modes (+dN / --display-mode N), DRAFT, awaiting PI review

Status: drafted from CLAN manual; not yet implemented. Rewriter at crates/talkbank-clan/src/clan_args.rs:101 translates +dN → --display-mode N; no clap field consumes it today. Drafted from CLAN manual §7.25.5 (Unique Options, SCRIPT) for PI review.

NCLAN behavior (verbatim from manual)
+d (no number)“Outputs default results in SPREADSHEET format.”
+d1“Outputs ratio of words and utterances over time duration.”
+d10“Outputs above, +d1, results in SPREADSHEET format.”

Open questions for PI review

  1. +d (spreadsheet) overlaps with --format csv exactly. Should +d rewrite to --format csv instead of --display-mode 0?
  2. +d10 = +d1 + spreadsheet, a combinator. The numeric encoding 10 mixes a “ratio mode” with the “spreadsheet” output format on one axis. Better factored as --display-mode ratio --format csv (two orthogonal flags) rather than --display-mode 10.
  3. +d1 requires “time duration” data, implies bullet timings or @Duration headers in the input. Should chatter validate that prerequisite at clap-parse time or fail at runtime with a clear error?

Output

Per file:

  • Words produced by subject
  • Words expected from template
  • Correct words (matched)
  • Omitted words (in template but not produced)
  • Added words (produced but not in template)
  • Percentage correct

Overall totals across all files.

Differences from CLAN

  • Template file is parsed into a typed AST (not raw text comparison)
  • Word matching uses NormalizedWord for case-insensitive comparison
  • Omissions and additions are computed from frequency maps rather than positional alignment, which may produce different results when word order matters
  • Output supports text, JSON, and CSV formats
  • Golden test parity: Verified against CLAN C binary output

SRT2CHAT – SRT Subtitle to CHAT Conversion

Status: Current Last updated: 2026-05-22 13:40 EDT

Purpose

Parses SRT (SubRip) subtitle files and converts them to CHAT format, mapping each subtitle block to an utterance with timing bullets derived from the SRT timestamps.

Usage

chatter-clan srt2chat input.srt

Options

OptionDefaultDescription
-l, --language"eng"ISO 639 language code for the @Languages header
-o, --outputstdoutOutput CHAT file path

The speaker code ("SPK") and corpus name ("srt_corpus") in @ID headers are both hardcoded at crates/talkbank-clan/src/converters/srt2chat.rs:152; there are no CLI flags to override them. Same pattern as the other converters in this directory.

Input Format

SRT files consist of numbered blocks separated by blank lines:

1
00:00:01,000 --> 00:00:03,000
Hello world

2
00:00:04,200 --> 00:00:06,800
How are you

Timestamps use HH:MM:SS,mmm format (both comma and period separators are accepted). Multi-line subtitle text within a block is joined with spaces.

Output

A well-formed CHAT file where each SRT subtitle block becomes a timed utterance. Timing bullets are derived from the SRT timestamps (converted to milliseconds). All utterances are assigned to the configured speaker code.

Differences from CLAN

  • Uses typed AST for CHAT generation
  • Produces valid, well-formed CHAT output
  • Accepts both comma and period as millisecond separators in timestamps

CLAN +-flag coverage audit

SRT2CHAT is a converter: input SRT subtitles, output CHAT. Sources: OSX-CLAN/src/clan/Srt2Chat.cpp::usage, crates/talkbank-clan/src/converters/srt2chat.rs.

CLAN’s Srt2Chat.cpp::usage documents no command-specific +-flags. Byte-parity complete for the documented surface.

Audit summary: 1 Done, 0 Missing.

SUGAR – Sampling Utterances and Grammatical Analysis Revised

Status: Current Last updated: 2026-05-22 09:22 EDT

Purpose

Computes language sample analysis metrics from %mor and %gra tiers, providing a quick clinical assessment of grammatical complexity. SUGAR is designed as a time-efficient alternative to more detailed scoring systems like DSS or IPSYN.

See the CLAN manual for the original SUGAR command specification.

Usage

chatter-clan sugar file.cha
chatter-clan sugar --speaker CHI file.cha
chatter-clan sugar --format json file.cha

Options (chatter-native)

OptionCLAN flagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN sugar flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/sugar.cpp: usage() and getflag().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() SUGAR branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Sugar plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

SUGAR is a required-flag refusal command in chatter, same refusal byte-parity as EVAL/KIDEVAL/DSS/IPSYN.

SUGAR-specific +-flags (from sugar.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aNMinimum-utterance threshold (default 50)--min-utterances NDoneFixed 2026-05-22. New clap field on Sugar; rewriter routes +aN → --min-utterances N.
+bS / -bSMorpheme-delimiter customization,MissingShared with WDLEN/MAXWD/EVAL.
-dShow utterances that fail at least one verb requirement,MissingDiagnostic listing.

Audit summary

BucketCount
Done5
Partial0
Rewriter only5
Missing7

SUGAR’s narrowest gap was +aN: closed 2026-05-22 with a new --min-utterances N clap field and rewriter routing.

SUGAR has no command-specific flags beyond the shared CommonAnalysisArgs set. The minimum-utterance threshold (50) is a fixed internal default; there is no --min-utterances switch in the current CLI.

Metrics

MetricDescriptionSource
MLU-SMean Length of Utterance in morphemes%mor tier
TNWTotal Number of Words (tokens with POS tags)%mor tier
WPSWords Per SentenceUtterances containing verbs
CPSClauses Per Sentence%gra subordination relations

Algorithm

  1. For each utterance, count morphemes and words from %mor
  2. Detect verb-containing utterances using POS tags: v, verb, cop, aux, mod, part (crates/talkbank-clan/src/commands/sugar.rs:198, both v and the longer verb form are accepted)
  3. For verb utterances with %gra, count subordinate clauses via grammatical relations (COMP, CSUBJ, CMOD, etc.)
  4. Compute per-speaker ratios at finalization:
    • WPS = total words / number of verb utterances
    • CPS = total clauses / number of verb utterances

Minimum utterance threshold

If a speaker has fewer than min_utterances (default: 50), the sample is flagged as insufficient. This ensures statistical reliability of the computed ratios.

Differences from CLAN

Verb detection

Uses mapped POS tags from the parsed %mor tier structure. CLAN may use a slightly different POS tag set for verb identification. Both implementations identify the same core verb categories.

Post-clitic %mor chunks are included in verb detection, so clitic-bearing items still contribute when the verb-like chunk appears only after ~.

Clause counting

Uses %gra subordination relations only (dependency structure). CLAN’s clause detection may use additional heuristics beyond grammatical relations.

Morpheme counting

Morpheme counts are computed from typed %mor structure, including post-clitics and their features.

Minimum utterance threshold

The Rust implementation uses a fixed internal default of 50, matching CLAN. There is currently no CLI flag to override this.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

Verified against CLAN C binary output.

TEXT2CHAT – Plain Text to CHAT Conversion

Status: Current Last updated: 2026-05-22 13:40 EDT

Purpose

Converts plain text files into CHAT format by splitting on sentence-ending punctuation (., ?, !) and assigning all utterances to a default speaker. This is the simplest converter, useful for bootstrapping CHAT files from raw text.

Usage

chatter-clan text2chat input.txt

Options

OptionDefaultDescription
-s, --speaker"SPK"Speaker code for all utterances
-l, --language"eng"ISO 639 language code for the @Languages header
-o, --outputstdoutOutput CHAT file path

The corpus name in @ID headers is hardcoded to "text_corpus" (crates/talkbank-clan/src/converters/text2chat.rs:37); there is no CLI flag to override it. Same pattern as the other converters in this directory.

Input Format

Plain text files. Newlines within the input are treated as spaces (not sentence boundaries). The text is split into utterances at sentence-ending punctuation (., ?, !).

Output

A well-formed CHAT file where each sentence becomes an utterance. Sentence terminators are preserved as CHAT terminators (period, question mark, exclamation point). Trailing text without punctuation receives a default period terminator.

Differences from CLAN

  • Uses typed AST for CHAT generation
  • Produces valid, well-formed CHAT output

CLAN +-flag coverage audit

TEXT2CHAT is a converter: input plain text, output CHAT. Sources: OSX-CLAN/src/clan/text2chat.cpp::usage, crates/talkbank-clan/src/converters/text2chat.rs.

TEXT2CHAT-specific +-flags (from text2chat.cpp::usage)

CLAN flagMeaningChatterStatus
+c0Insert @Blank/@Indent headers when appropriate,Missing
+c1Each line is an utterance regardless of delimiter,Missing
+c2Convert first capitalized word of utterance/quotation to lowercase,Missing
+c3Convert [...] lines to *INV: ...,Missing

Audit summary: 1 Done (default line-per-utterance conversion), 4 Missing. The +cN family is a tokenization-policy switch ladder; chatter implements one fixed policy. Filed as a Phase 1.7 follow-up.

TIERORDER – Reorder Dependent Tiers to Canonical Order

Status: Current Last updated: 2026-05-22 13:04 EDT

Purpose

Reorders dependent tiers into a consistent order. The legacy manual describes TIERORDER as putting dependent tiers into a consistent alphabetical order, with /lib/fixes/tierorder.cut able to control the order.

talkbank-clan sorts dependent tiers on each utterance according to its built-in canonical ordering.

Usage

chatter-clan tierorder file.cha

Options

This command has no command-specific flags beyond the shared -o, --output <PATH> (default: stdout). See Output Formats for the transform output flag.

CLAN +-flag coverage audit

TIERORDER is a transform. Sources: OSX-CLAN/src/clan/tierorder.cpp::usage, crates/talkbank-clan/src/transforms/tierorder.rs.

TIERORDER-specific +-flags (from tierorder.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+bDo not move bullets to a new speaker tier,MissingBullet-handling toggle.
+cFDictionary file (default tierorder.cut) controlling the canonical order,Missingchatter hard-codes the canonical priority list in tierorder.rs::tier_order(). The +cF form would let researchers override the order.
+qSort only header tiers,MissingRestrict scope to header reordering.
+tSSwitch speaker tier S with the main speaker tier,MissingSpeaker-tier promotion.

Audit summary

BucketCount
Done1 (default canonical-order sort)
Missing4

TIERORDER’s gap profile is dominated by customization flags +cF for user-supplied tier-order files is the most likely request from researchers with non-standard tier conventions. chatter’s built-in tier_order() priority list is sufficient for the canonical TalkBank/CHILDES corpus but doesn’t let users override.

Behavior

Dependent tiers are sorted into the following canonical order (per the tier_order() priority function at crates/talkbank-clan/src/transforms/tierorder.rs:57-100):

  1. Linguistic analysis tiers (priorities 0-5): %mor → %gra → %pho → %mod → %wor → %sin

  2. Phon project syllabification/alignment tiers (priorities 6-8): %xmodsyl → %xphosyl → %xphoaln

  3. Behavioral/descriptive tiers (priorities 10-18): %act → %cod → %com → %spa → %gpx → %sit → %exp → %int → %add

  4. Simple text tiers (priorities 20-30): %alt → %coh → %def → %eng → %err → %fac → %flo → %gls → %ort → %par → %tim

  5. User-defined tiers (priority 100): %x* (anything beyond the standard set)

  6. Unsupported tiers (priority 101): tiers that hit the grammar’s catch-all but aren’t recognized CHAT tiers

Utterances with zero or one dependent tier are left unchanged.

Differences from CLAN

  • Manual configurability not yet mirrored: The legacy manual describes tierorder.cut as controlling tier order. The current implementation uses a built-in ordering instead.
  • Operates on AST rather than raw text.
  • Uses the framework transform pipeline (parse -> transform -> serialize -> write).

TIMEDUR – Time Duration

Status: Current Last updated: 2026-05-22 09:41 EDT

Purpose

Computes time duration statistics from media timestamp bullets attached to utterances. Utterances without bullet timing are silently skipped.

See the CLAN manual for the original TIMEDUR command specification.

Usage

chatter-clan timedur file.cha
chatter-clan timedur --speaker CHI file.cha
chatter-clan timedur --format json file.cha

Options (chatter-native)

OptionCLAN FlagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN timedur flag. Sources:

  • OSX-CLAN/src/clan/timedur.cpp: usage().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() TIMEDUR branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Timedur plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

TIMEDUR has no command-specific flags beyond the general inherited set. All variation is in +d display modes:

TIMEDUR-specific flags (from timedur.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+dDefault results in spreadsheet format,Rewriter only--display-mode rewrite.
+d1Ratio of words/utterances over time duration,Rewriter only
+d10+d1 results in spreadsheet format,Rewriter only

Audit summary

BucketCount
Done6
Partial1
Rewriter only6
Missing4

TIMEDUR’s gap profile is dominated by +dN display modes. Body parity already matches CLAN. The default (+d) emits in spreadsheet format, chatter’s text/json/csv formats cover the spreadsheet use case but with different shapes; researchers expecting CLAN’s exact spreadsheet column layout need --format csv plus the layout audit.

Output

Per speaker:

  • Number of timed utterances
  • Total duration (formatted as HH:MM:SS.mmm)
  • Mean utterance duration
  • Min/max duration

Plus a corpus-wide summary:

  • Total timed utterances across all speakers
  • Total duration
  • Recording span (earliest start to latest end)
  • Speaker interaction matrix (overlap and gap analysis)

Differences from CLAN

Timestamp extraction

Uses parsed media bullet structures from the AST (Bullet { start_ms, end_ms }) rather than raw byte scanning in text. This is more robust against formatting variations.

Interaction matrix header

The interaction matrix header includes a leading space, matching CLAN exactly. This was verified during golden test parity work.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

100% parity with CLAN C binary output.

TRIM, Remove Dependent Tiers

Status: Current Last updated: 2026-05-22 12:55 EDT

Purpose

Removes selected dependent tiers from a CHAT file while preserving headers, main tiers, and all other file structure. The CLAN manual describes TRIM as a shorthand for removing coding tiers, such as %mor, without changing anything else in the transcript.

Usage

chatter-clan trim file.cha --exclude-tier mor
chatter-clan trim file.cha --exclude-tier '*'
chatter-clan trim file.cha --tier cod

Options

OptionCLAN FlagDescription
--tier <NAME>+t%NAMEKeep only selected dependent tier(s)
--exclude-tier <NAME>-t%NAMERemove selected dependent tier(s)

CLAN +-flag coverage audit

TRIM has no dedicated *.cpp in the CLAN source tree, CLAN documents it as a KWAL-style invocation that produces text output rather than as a discrete command. chatter exposes trim as a first-class subcommand operating on the typed AST.

  • Inherited flags applicable here: +t%NAME / -t%NAME for tier selection (both routed via clan_args::rewrite_tier_speaker to --tier / --exclude-tier).
  • * wildcard for “all dependent tiers” is a chatter extension.

Audit summary

BucketCount
Done3 (default, +t%X, -t%X)
Chatter extension1 (* wildcard)
Missing0

TRIM is a chatter-first interpretation of CLAN’s legacy workaround. Parity is “as documented” rather than “as implemented in CLAN”, by design.

Differences from CLAN

  • Legacy intent preserved: TRIM follows the tier-removal behavior described in CLAN.html, rather than extracting utterance or gem ranges.
  • Operates on the typed AST rather than the KWAL-style text-output workaround shown in the legacy manual.
  • --tier / --exclude-tier operate on dependent-tier labels only. Headers and main tiers are always preserved.
  • Supports * as a wildcard dependent-tier selector and normalizes %trn to %mor and %grt to %gra.

TRNFIX, Compare Two Dependent Tiers

Status: Current Last updated: 2026-05-26 10:36 EDT

Purpose

Compares two dependent tiers (default: %mor and %trn) word-by-word across all utterances, reporting unique mismatch pairs with frequency counts and an overall accuracy percentage. Useful for verifying tier consistency after automatic annotation or manual correction.

When tiers have different lengths for a given utterance, missing positions are represented as the null symbol ∅ (empty set).

Usage

chatter-clan trnfix file.cha
chatter-clan trnfix file.cha --tier1 mor --tier2 gra

Options (chatter-native)

OptionCLAN flagDescription
--tier1 <name>+bS (first instance)First tier to compare (default: mor)
--tier2 <name>+bS (second instance)Second tier to compare (default: trn)
--speaker <code>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <code>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--format <fmt>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

TRNFIX-specific +-flags (from trnfix.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+aDisambiguate words before compare (default: compare whole words),MissingAffects mismatch resolution semantics.
+bSSpecify a tier to compare (repeatable; first → tier1, second → tier2)--tier1 / --tier2Partialchatter splits into two explicit fields rather than positional +b semantics.
+dInclude speaker tier in output,MissingOSX-CLAN/src/clan/TrnFix.cpp:132 bare branch sets whichDopt = 1; per-TRNFIX rewriter arm passes the token through so clap rejects loudly.
+d1+d + include utterances in mismatches summary file,MissingOSX-CLAN/src/clan/TrnFix.cpp:132 non-bare branch sets whichDopt = 2; per-TRNFIX rewriter arm passes the token through so clap rejects loudly.

Audit summary

BucketCount
Done5
Partial2
Rewriter only2
Missing5

TRNFIX’s +a disambiguate-before-compare is the most semantically significant gap: it changes whether multi-analysis %mor tokens like det|the^pro|the are compared by their first analysis only or by full text.

Output

  • Table of unique mismatch pairs with frequency counts
  • Total items compared
  • Total mismatched items
  • Accuracy percentage

Differences from CLAN

  • Tier content is compared from parsed AST data rather than raw text
  • %trn is treated as an alias of %mor, and %grt as an alias of %gra
  • %mor/%gra token comparison preserves typed token boundaries from the AST rather than comparing whitespace-split serialized payload strings.
  • Length mismatches are handled with explicit ∅ null symbols
  • Configurable tier names (CLAN uses fixed %mor/%trn comparison)
  • Output supports text, JSON, and CSV formats
  • Golden test parity: Verified against CLAN C binary output

UNIQ – Report Repeated Lines

Status: Current Last updated: 2026-05-23 13:00 EDT

Purpose

Identifies and counts duplicate lines (both @header and *speaker utterance lines, lowercased) across all input files. Matches CLAN behavior of including all line types in the frequency table.

See the CLAN manual for related CLAN command specifications.

Usage

chatter-clan uniq file.cha
chatter-clan uniq --sort file.cha
chatter-clan uniq --format json corpus/

Options (chatter-native)

OptionCLAN FlagDescription
--sort-oSort output by descending frequency
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

UNIQ has the narrowest flag surface of any analysis command: just -o (sort by descending frequency). chatter exposes it as --sort, and the rewriter routes -o → --sort under UNIQ (pinned by clan_args::tests::uniq_sort).

CLAN flagMeaningChatterStatusNotes
-oSort by descending frequency--sortDoneRewriter arm in clan_args.rs consumes -o under UNIQ only; other commands route -o differently (FIXBULLETS bullet offset, etc.).

Inherited general flags: same as FREQ. Audit summary: 7 Done / 0 Partial / 4 Rewriter only / 3 Missing.

Output

  • Table of unique line texts with frequency counts (headers + utterances + dependent tiers)
  • Total lines processed and number of unique lines
  • Optional frequency-descending sort

What Gets Counted

UNIQ counts all line types, including:

  • @header lines
  • *speaker utterance lines
  • %dependent tier lines (including %mor and %gra)
  • Multi-line headers are split and counted individually

This matches CLAN’s behavior of including dependent tiers in the frequency table and splitting multi-line headers for counting.

Differences from CLAN

Dependent tier inclusion

Includes %mor/%gra dependent tiers in counts, matching CLAN.

Multi-line header splitting

Splits multi-line headers for counting, matching CLAN.

Unicode sort order

1 accepted divergence: Unicode sort order for U+230A (LEFT FLOOR character). C-locale strcoll() places this character differently than Rust’s byte-order sorting. Result: a single line position swap with identical content and counts. This is a cosmetic difference with no impact on analysis.

Line text extraction

Uses the parsed AST and WriteChat serialization rather than raw text line reading. This ensures consistent normalization.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

99% parity (1 accepted Unicode sort order divergence).

VOCD – Vocabulary Diversity (D Statistic)

Status: Current Last updated: 2026-06-01 12:03 EDT

Purpose

Computes the D statistic for lexical diversity using bootstrap sampling of type-token ratios (TTR). The D statistic provides a more stable measure of vocabulary diversity than raw TTR because it accounts for sample size effects.

See the CLAN manual for the original VOCD command specification.

Usage

chatter-clan vocd file.cha
chatter-clan vocd --speaker CHI file.cha
chatter-clan vocd --format json file.cha

Options (chatter-native)

OptionCLAN FlagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN vocd flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/vocd/vocd.cpp: usage() and getflag().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() VOCD branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Vocd plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

VOCD has the largest command-specific flag surface of any CLAN analysis tool, dominated by the D_optimum sampling parameters.

VOCD-specific +-flags (from vocd.cpp::getflag)

CLAN flagMeaningChatterStatusNotes
+b0D_optimum: use split half, even,MissingSampling-method switch.
+b1D_optimum: use split half, odd,Missing
+bsND_optimum: size N of starting sample (default 35),Missing
+blND_optimum: size N of largest sample (default 50),Missing
+biND_optimum: size N of increments (default 1),Missing
+bnND_optimum: N number of samples (default 100),Missing
+brD_optimum: random sampling with replacement (default: without),Missing
+beD_optimum: sequential sampling,Missing
+c / +c0 / +c1Find capitalised words only (+c/+c0) or mid-uppercase (+c1)--capitalization <initial|mid>DoneLanded 2026-05-22. Shares the CapitalizationFilter enum with FREQ. +c/+c0 (alias) → initial filter; +c1 → mid (e.g. McDonald, iPhone). Applied before VOCD’s token sequence reaches the D-statistic sampler.
+d, +d1, +d2, +d3Output mode (utterances + types/tokens; summary only; etc.),MissingOSX-CLAN/src/clan/vocd/vocd.cpp:311 sets onlydata = atoi(getfarg(...))+1 (bounded by OnlydataLimit; onlydata == 4 rejected under CLAN_SRV). chatter has no --display-mode consumer for VOCD. Per-VOCD rewriter arm in clan_args.rs passes the token through so clap reports the literal +dN argument rather than the misleading --display-mode rewrite.
+gnS / -gnSCompute LRD, S = NUMERATOR +s directives,MissingLRD = Limiting Relative Diversity.
+gdS / -gdSCompute LRD, S = DENOMINATOR +s directives,Missing
+oOverride default lemma-based analysis,MissingSwitches VOCD from %mor lemma-based to main-tier word-based.
+o3Combine selected speakers per filepartial via --per-file inversePartial

General +-flags VOCD inherits (from cutt.cpp::mainusage)

CLAN flagMeaningChatterStatusNotes
+t*X / -t*XInclude/exclude speaker--speaker / --exclude-speakerDone+tX accepted post-2026-05-21.
+t%X / -t%XInclude/exclude dependent tier--tier / --exclude-tier (rewriter target)Rewriter only
+t@ID="..."Filter by @ID pattern--id-filterDone
+s"word" / -s"word"Include/exclude word--include-word / --exclude-wordDoneVOCD’s +sm suffix variants for %mor searches not special-cased.
+s@F / -s@FSearch / exclude words from file--include-word-file / --exclude-word-fileDoneLanded 2026-05-22. File format: one pattern per line; blank lines, # -comments, and ;%* -annotation lines skipped. Repeatable.
+gXGem filter (without N suffix)--gemDoneDistinct from +gnS/+gdS.
+zN-MUtterance range--rangeDone
+rNRetrace / clitic / prosodic controls--include-retracings (+r6)Partial
+uCombine across files(default)Done
+reRecurse(default)Done
+kCase-fold toggle: VOCD preserves case by default, +k folds to lowercase--plus-k (carries +k)DoneVOCD is in CLAN’s mmaininit nomap=TRUE set (cutt.cpp:7845), so it PRESERVES case by default; +k TOGGLES nomap (cutt.cpp:13816) to fold, collapsing case variants before the D-statistic sampler. INVERSE of the fold-by-default commands; chatter sets VOCD’s case_sensitive keying to !(+k present). VOCD output is non-deterministic (random sampling), so this is pinned by the deterministic token-case tests vocd_default_preserves_case_in_tokens and vocd_plus_k_folds_case_in_tokens, not a byte golden.
+f / +fEXTOutput to file--output-ext (rewriter target)Rewriter only

Audit summary

BucketCount
Done9
Partial2
Rewriter only5
Missing13

VOCD has the largest Missing bucket of any audited command, driven by the D_optimum sampling parameter family (+b0, +b1, +bsN, +blN, +biN, +bnN, +br, +be) and the LRD family (+gnS, +gdS). chatter’s vocd uses a fixed default sampling strategy with no exposed knobs. The +o lemma-vs-main-tier override is also missing, researchers studying main-tier diversity directly cannot get there from chatter today. Filed as Phase 1.7 follow-ups.

CLAN Equivalence

CLAN commandRust equivalent
vocd file.chachatter-clan vocd file.cha
vocd +t*CHI file.chachatter-clan vocd file.cha --speaker CHI

Algorithm

Overview

VOCD fits empirical type-token data to a theoretical curve, finding the D parameter that best explains the relationship between sample size and vocabulary diversity.

Steps

  1. Collect tokens: Gather all countable word tokens per speaker from the main tier
  2. Bootstrap sampling (3 independent trials):
    • For each sample size N from 35 through 50:
      • Draw 100 random samples of N tokens (without replacement)
      • Compute mean TTR across the 100 samples
    • Fit the empirical (N, TTR) curve to the theoretical D-curve using gradient-descent least-squares optimization
    • Record the optimal D value
  3. Report: Per-trial D values and their average

Theoretical TTR Curve

TTR(N) = (D/N) * [sqrt(1 + 2*N/D) - 1]

This models the expected type-token ratio for a sample of size N given a lexical diversity parameter D. Higher D means greater diversity.

Interpretation

D valueInterpretation
< 30Low lexical diversity
30-70Typical range for young children
70-100Typical range for older children/adults
> 100High lexical diversity

(Values are approximate and depend on the population.)

Output

Per-speaker D statistic with per-trial breakdown tables:

Speaker: CHI
  Trial 1:
    N    samples  TTR     std_dev   D
    35   100      0.743   0.045     42.1
    36   100      0.735   0.043     42.3
    ...
    50   100      0.680   0.038     43.0
    D = 42.5
  Trial 2: D = 41.8
  Trial 3: D = 43.2
  Average D = 42.5

Differences from CLAN

Stochastic variation

Because VOCD uses random sampling, D values may differ slightly between runs and between CLAN and our implementation. This is expected behavior, not a bug. Differences of +/- 5 are normal.

Fusional feature stripping

Fusional features (&PRES, &INF, etc.) are stripped from lemmas in %mor echo output. This ensures clean lemma display when VOCD echoes the morphological tier for insufficient-token warnings.

Word identification

Uses AST-based is_countable_word() instead of CLAN’s string-prefix matching. Token collection operates on parsed AST content rather than raw text.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

100% parity with CLAN C binary output (within expected stochastic variation).

WDLEN – Word Length Distribution

Status: Current Last updated: 2026-05-26 08:21 EDT

Purpose

Computes six distribution tables matching CLAN’s output format. WDLEN provides detailed histograms of word and utterance lengths, useful for studying vocabulary complexity and utterance structure development.

See the CLAN manual for the original WDLEN command specification.

Usage

chatter-clan wdlen file.cha
chatter-clan wdlen --speaker CHI file.cha
chatter-clan wdlen --format json file.cha

Options (chatter-native)

OptionCLAN FlagDescription
--speaker <CODE>+t*CHI (or +tCHI)Include speaker
--exclude-speaker <CODE>-t*CHI (or -tCHI)Exclude speaker
--gem <LABEL>+g"label"Restrict to gem segment
--range <START-END>+z25-125Utterance range
--id-filter <PATTERN>+t@ID="..."Filter by @ID pattern
--include-retracings+r6Include retraced words in counting
--format <FMT>–Output format: clan (default), text, json, csv

CLAN +-flag coverage audit

Authoritative enumeration of every CLAN wdlen flag, mapped against chatter’s coverage. Sources:

  • OSX-CLAN/src/clan/wdlen.cpp: usage() and getflag().
  • OSX-CLAN/src/clan/cutt.cpp: mainusage() WDLEN branches.
  • crates/talkbank-clan/src/clan_args.rs: chatter’s rewriter.
  • crates/talkbank-cli/src/cli/args/clan_commands.rs::Wdlen plus clan_common.rs::CommonAnalysisArgs.

(Status legend: same as FREQ.)

WDLEN-specific +-flags (from wdlen.cpp::getflag)

CLAN flagMeaningChatterStatusNotes
+aCompute both words and morphemes from %mor only (no main tier),MissingCLAN’s “depend-only” mode. chatter’s sections 5/6 already use %mor per the six-section design, so the divergence is whether sections 1-4 use main tier or skip.
+bSAdd chars in S to morpheme-delimiter list,MissingMorpheme-boundary customization.
-bSRemove chars in S from delimiter list (-b clears all),Missing
+cSClause-marker delimiter S,Missing
+c@FClause markers from file F,Missing

General +-flags WDLEN inherits (from cutt.cpp::mainusage)

CLAN flagMeaningChatterStatusNotes
+t*X / -t*XInclude/exclude speaker--speaker / --exclude-speakerDone+tX accepted post-2026-05-21.
+t%X / -t%XInclude/exclude dependent tier--tier / --exclude-tier (rewriter target)Rewriter only
+t@ID="..."Filter by @ID pattern--id-filterDone
+t#ROLEFilter by role--roleDoneFixed 2026-05-22; see FREQ for the shared implementation.
+s"word" / -s"word"Include/exclude word--include-word / --exclude-wordDoneWDLEN docs say +sm is the recommended search-spec form for %mor-tier searches; chatter does not yet special-case the m suffix.
+s@F / -s@FSearch / exclude words from file--include-word-file / --exclude-word-fileDoneLanded 2026-05-22. File format: one pattern per line; blank lines, # -comments, and ;%* -annotation lines skipped. Repeatable.
+gXGem filter--gemDone
+zN-MUtterance range--rangeDone
+rNRetrace / clitic / prosodic controls--include-retracings (+r6)Partial
+uCombine across files(default)DoneInverse default vs CLAN.
+reRecurse(default)Done
+pSWord delimiter,Missing
+kCase-sensitive--case-sensitive (via CommonAnalysisArgs)Done (no-op per CLAN)WDLEN does no word-keying; +k is silently accepted per CLAN’s cutt.cpp::mainusage no-op semantic. Covered by CommonAnalysisArgs.case_sensitive flatten on ClanCommands::Wdlen.
+wN / -wNContext window (KWAL/COMBO keyword-context)–Rewriter onlyInapplicable to WDLEN (word-length distributions, no per-match context to surround). The rewriter maps +wN/-wN to --context-after/--context-before, but WDLEN has no such clap field, so it errors at parse time, the correct outcome for an inapplicable flag (talkbank-clan/AGENTS.md). CLAN’s binary instead empties the output (a context-machinery artifact).
+f / +fEXTOutput to file--output-ext (rewriter target)Rewriter onlyPhase 1.1.

Audit summary

BucketCount
Done (byte-parity or in scope)10
Partial2
Rewriter only3
Missing6

WDLEN’s specific gaps (+a depend-only mode, +bS/-bS morpheme-delimiter customization, +cS clause delimiters) all affect what counts as a unit in the six distribution sections, i.e., they change the numbers in the histograms. Filed as Phase 1.7 follow-ups.

Six Distribution Sections

SectionWhat it measuresSource
1. Word lengths in charactersCharacter count per wordMain tier
2. Utterance lengths in wordsWord count per utteranceMain tier
3. Turn lengths in utterancesUtterances per turnMain tier
4. Turn lengths in wordsWords per turnMain tier
5. Word lengths in morphemesMorphemes per word (stem + Brown’s suffixes)%mor tier
6. Utterance lengths in morphemesMorphemes per utterance (POS + stem + Brown’s suffixes)%mor tier

Each section shows a histogram (value -> count), mean, and total.

Differences from CLAN

Brown’s morpheme rules

Sections 5 and 6 use distinct counting methods:

  • Section 5: stem + Brown’s suffix count (no POS tag counted). Clitic pairs (~) are merged as one word.
  • Section 6: POS tag + stem + Brown’s suffix count. POS is counted only for the main word (not clitics).

Brown’s suffix strings: PL, PAST, Past, POSS, PASTP, Pastp, PRESP (same 7 as MLU).

Character counting

CLAN strips apostrophes before counting character length. Our implementation matches this behavior.

Speaker ordering

CLAN outputs speakers in reverse encounter order (an artifact of its C linked-list prepend pattern). Our implementation replicates this ordering for parity.

CLAN appends </Table></Worksheet></Workbook> XML tags at the end of output. Our implementation matches this for parity.

Output formats

Supports text, JSON, and CSV. CLAN produces text only.

Golden test parity

100% parity with CLAN C binary output.

WDSIZE, Word Size Distribution

Status: Current Last updated: 2026-05-26 08:47 EDT

Character-length histogram for word stems from the %mor tier.

Usage

chatter-clan wdsize file.cha
chatter-clan wdsize corpus/ --speaker CHI
chatter-clan wdsize file.cha --main-tier    # Use main tier words instead
chatter-clan wdsize file.cha --format json

What It Measures

WDSIZE counts the character length of each word stem extracted from the %mor tier and produces a histogram showing how many words of each length appear. By default it uses morphological stems (lemmas); with --main-tier it uses surface forms from the main tier.

Output

Per speaker:

  • Character-length histogram (length → count)
  • Total words measured
  • Mean word size in characters

Differences from WDLEN

FeatureWDSIZEWDLEN
Default source%mor stemsMain tier words
Sections1 (character lengths only)6 (chars, words/utt, turns, morphemes)
Morpheme countingNoYes (sections 5-6)

Differences from CLAN

  • Uses typed MorTier items with MorWord.lemma rather than raw string parsing
  • Supports JSON and CSV output
  • Falls back to main tier words when %mor is absent

CLAN +-flag coverage audit

WDSIZE is an analysis command (banner-emitting). Sources: OSX-CLAN/src/clan/wdsize.cpp::usage, crates/talkbank-clan/src/commands/wdsize.rs, crates/talkbank-cli/src/cli/args/clan_commands.rs::Wdsize.

(Status legend: same as FREQ.)

WDSIZE-specific +-flags (from wdsize.cpp::usage)

CLAN flagMeaningChatterStatusNotes
+bSAdd chars in S to morpheme-delimiter list,MissingSame gap as WDLEN/MAXWD’s +bS.
-bSRemove chars from delimiter list (-b clears all),Missing
+cSClause-marker delimiter S,MissingSame as MLU/MLT’s +c.
+wCNInclude only words C (>, <, =) than N characters--length-filter <gt:N|lt:N|eq:N>DoneLanded 2026-05-23. Per-word length gate before the histogram accumulator. The rewriter intercepts `+w[>
--main-tier (chatter extension)Use main-tier words instead of %mor stems--main-tierChatter-onlyNo CLAN analog.

Audit summary

BucketCount
Done7 (6 general inherited as documented on FREQ + +wCN)
Partial1
Rewriter only4
Missing3

Note on a removed audit row (2026-05-26). A prior version of this page listed a +a row claiming “Use %mor only (no fallback to main tier)” as Done-by-default. Direct inspection of OSX-CLAN/src/clan/wdsize.cpp::getflag shows the WDSIZE option switch handles only b, d, s, t, w; there is no case 'a'. The row was a phantom; the CLAN flag does not exist. Removed entirely rather than reclassified, per the discrepancy- adjudication rule (CLAN source = canonical authority for parity claims). The 2026-05-26 audit-vs-runtime sweep flagged the row as Category B and the investigation surfaced the phantom.

WDSIZE shares its morpheme-delimiter and clause-marker gaps with WDLEN/MAXWD/MLU/MLT, the cluster of commands that all read %mor and would benefit from a shared “morpheme-delimiter customization” feature. Filed as a Phase 1.7 cross-cutting follow-up.

Why We Diverge

Status: Current

The parity goal

The primary goal is exact output parity with legacy CLAN wherever possible. We match CLAN’s output format, counting rules, and even its quirks (like reverse speaker ordering from C linked-list prepend patterns). Every implemented command has golden tests that compare our output character-by-character against the original CLAN C binary.

Current parity: 95% (113/118 golden snapshots match exactly). The 5 accepted divergences are in DELIM (4 cosmetic) and UNIQ (1 Unicode sort order difference).

When we accept divergences

We diverge from CLAN only when one of these conditions holds:

  1. CLAN has a bug that produces incorrect results; we fix the bug and document it. Examples: INDENT’s infinite loop on certain overlap patterns, FREQ double-counting words in retrace groups.

  2. The difference is cosmetic and doesn’t affect analysis results, different whitespace, column alignment, or header formatting that no downstream tool depends on.

  3. Matching would require unreasonable complexity for zero user benefit, e.g., replicating CLAN’s 80-character line wrapping in output, or matching exact floating-point rounding from C’s printf("%.3f").

  4. We deliberately improve on CLAN’s behavior, structured output formats (JSON, CSV), recursive directory traversal, rich error diagnostics with file locations. These are extensions, not replacements of existing behavior.

What we never change

  • Counting semantics: If CLAN counts a word, we count it. If CLAN uses population SD (/n), we use population SD. Counting rules are discovered empirically through golden test comparison and documented in Framework-Level Divergences.

  • Speaker ordering: CLAN outputs speakers in reverse encounter order due to its C linked-list prepend pattern. We replicate this, even though it’s a data structure artifact, because users and scripts depend on it.

  • Algorithm behavior: For stochastic commands like VOCD, we use the same random sampling algorithm (D_optimum curve fitting on 100 random samples at each token count from 35-50).

The AST advantage

The most fundamental architectural difference: CLAN processes CHAT files as flat text using string pattern matching and character scanning. The Rust reimplementation parses files into a typed AST (Abstract Syntax Tree) and operates on structured data.

This means:

  • Word classification uses typed fields (word.category, word.untranscribed()) instead of string prefix checks (starts_with('&'), == "xxx")
  • Annotations are structured objects with typed fields, not regex-extracted substrings
  • Transform commands modify AST nodes, then serialize, guaranteeing structural validity
  • Filters operate on typed speaker codes, tier names, and word categories

This eliminates entire classes of bugs where CLAN’s string patterns match unintended content (e.g., a word starting with & in a speaker name being misclassified as a special form). The tradeoff is occasional whitespace or formatting differences in edge cases, which we track and document.

Documentation policy

Every divergence, intentional or discovered, is documented in three places:

  1. Module doc comments: Each command’s //! header includes a “Differences from CLAN” section
  2. The book: Per-Command Divergences provides a centralized reference
  3. Golden test snapshots: The @clan vs @rust snapshot pairs make divergences visible in code review

Framework-Level Divergences

Status: Current Last updated: 2026-05-21 23:38 EDT

These differences apply across all commands, not to specific ones.

CLI syntax

AspectLegacy CLANRust CLAN
Flag style+flag / -flag--flag (both styles accepted)
Invocationfreq file.chachatter-clan freq file.cha
DirectoryManual file listing or *.chaRecursive directory traversal
Output formatText onlyText, JSON, CSV
Error outputSimple messages to stderrRich diagnostics with file location and context

Both flag styles are accepted, +t*CHI and --speaker CHI are equivalent. The automatic rewriting happens in clan_args::rewrite_clan_args() before argument parsing.

Output formatting

  • File headers: Our headers include the full file path; CLAN uses basename only in some commands
  • Speaker ordering: CLAN outputs speakers in reverse encounter order (C linked-list prepend pattern). We replicate this behavior for parity.
  • Encoding: UTF-8 only. CLAN supports legacy encodings via CP2UTF.
  • Line wrapping: Our text output does not wrap long lines. CLAN wraps at ~80 characters in some commands.

Counting semantics

These counting rules were discovered during golden test parity verification and apply across multiple commands:

RuleCommands affectedDetails
Population SDMLU, MLTUses / n, not / n-1 (sample SD)
Brown’s morphemesMLU, WDLENOnly 7 suffix strings count: PL, PAST, Past, POSS, PASTP, Pastp, PRESP
Fusional featuresVOCD, MLU&PRES, &INF etc. are part of the lemma; strip with split('&')
Apostrophe strippingWDLENCharacters counted after removing apostrophes
Turn = utteranceDISTEvery utterance is its own turn (no speaker-continuity grouping)

AST-based processing

The most fundamental divergence: CLAN processes CHAT files as text using string pattern matching. The Rust reimplementation parses files into a typed AST and operates on structured data. This means:

  • Word classification uses typed fields (word.category, word.untranscribed()) instead of string prefixes (starts_with('&'))
  • Annotations are structured objects, not regex-extracted substrings
  • Transform commands modify AST nodes, then serialize, guaranteeing structural validity

This eliminates classes of bugs where string patterns match unintended content, but occasionally produces different whitespace or formatting in edge cases.

CLAN-bug divergences (chatter improves on CLAN)

The CLAN parity contract is byte-level output equivalence on file-arg invocations. Within that contract, the parity work has surfaced behaviours where CLAN’s output is internally inconsistent or inadvertently doubled, visible plumbing artifacts rather than intended product. chatter-clan preserves the intended behaviour and documents the divergence here rather than reproducing the artifact.

Each entry below names the divergence, CLAN’s behaviour, chatter’s behaviour, the source-grounded reason chatter is correct, and the ledger row where it is tracked.

CLAN’s cutt.cpp mainloop emits the six-line banner block twice in:

  • any invocation that reads from stdin (freq < file.cha),
  • any invocation passing more than one positional file argument (freq a.cha b.cha),
  • and arguably others, the FirstTime branch fires whenever CLAN’s input committer reaches the scratch-file boundary, which is many call sites.

Single-file invocations (freq file.cha) emit the banner once.

  • CLAN behaviour (when duplicating): banner block printed twice, byte-identical except for an extra tab-prefixed echo on the second block’s line 1.
  • chatter behaviour: banner block printed once on every invocation regardless of source or arity.
  • Reason chatter is correct: the duplication is internal pipeline plumbing exposed by the FirstTime + scratch-file-commit ordering in cutt.cpp. No downstream consumer parses it as semantic content; researchers’ scripts that anchor on the **** separator find one separator and proceed. Doubling the block would be visual noise with no information value.
  • Ledger row: CLAN-DIV-001 (banner duplication).

If a researcher’s script breaks because it relied on seeing exactly two banner blocks, that script is parsing CLAN’s plumbing as content and needs to be updated; reach out and we will help.

Source line: always “From pipe input” in CLAN

CLAN’s banner emits the literal string From pipe input on line 6 in every invocation, regardless of whether the input came from stdin, a single file-arg, or multiple file-args. The label is misleading: freq file.cha (with no < redirection) still prints From pipe input.

  • CLAN behaviour: always From pipe input regardless of source.
  • chatter behaviour: From file <basename> when a file is the source (aggregated mode uses the first file; per-file mode uses each file’s basename).
  • Reason chatter is correct: the file name carries information a researcher inspecting CLAN output may want. CLAN’s hardcoded From pipe input was a poor design choice, the only time it is technically accurate is for < redirection, which is one of several supported invocation shapes. chatter’s label honestly reports the source.
  • Ledger row: CLAN-DIV-002 (source line).

Migration note: scripts that grep for the literal From pipe input will need to adjust to From file <…> when running chatter. Scripts that anchor on the **** separator (the more common pattern) are unaffected.

Per-Command Divergences

Status: Current Last updated: 2026-10-31

This page documents every known divergence between the Rust chatter-clan commands and the original CLAN C binaries. Divergences are verified through golden tests that compare output character-by-character.

9 accepted CLAN-bug divergences across 3 commands (DELIM, UNIQ, FREQ); each is a deliberate, source-and-manual-grounded out-correction, not a parity gap.

Parity Summary

StatusCommands
Implemented; parity not establishedCHIP
Golden-tested; not byte-parity certifiedMLU, MLT, VOCD, DIST, MAXWD, TIMEDUR, WDLEN, DSS, EVAL, KIDEVAL, IPSYN, FLUCALC, SUGAR, CHAINS, CODES, COMBO, COOCCUR, FREQPOS, GEMLIST, KEYMAP, MODREP, MORTABLE, PHONFREQ, RELY, SCRIPT, TRNFIX, CHSTRING, FLO, POSTMORTEM
Accepted divergencesDELIM (4), UNIQ (1), FREQ (4)

Golden-tested means the command has golden coverage; it does not establish byte-for-byte parity. The generated parity status is the authority for byte-parity evidence, and currently establishes it for no command.


Analysis Commands

FREQ – Word Frequency

  • AST-based is_countable_word() replaces string-prefix matching
  • The CLAN manual explicitly says FREQ ignores xxx, www, and items beginning with 0, &, +, -, or # by default; talkbank-clan preserves that intent through typed word classes rather than raw prefix checks.
  • NormalizedWord lowercases and strips compound markers for grouping
  • Deterministic sort (count descending, then alphabetical); CLAN’s order varies
  • JSON and CSV output; --format clan for character-level CLAN compatibility
  • Parity: 4 accepted CLAN-bug divergences with formal ledger rows (+c1; +d2/+d3/+dCN; +xxxx/+xyyy/+xwww; +r7), see CLAN-DIV-003, CLAN-DIV-004, CLAN-DIV-005, and CLAN-DIV-006 below. The +x…m morpheme-unit divergences (over-count + output-doubling) are documented in the +x row of commands/freq.md and are pending their own ledger rows.

CLAN-DIV-003: FREQ +c1 middle-only

+c1 is documented as “find words with upper case letters in the middle only” (CLAN manual section 5483; freq.cpp:167). CLAN’s implementation (freq.cpp isRightUpper, the capwd == 2 branch, which +c1 selects via freq.cpp:782) loops from character position 0 and returns a match on any uppercase letter, including the first, so it also keeps initial-capital words. Empirically freq +c, freq +c0, and freq +c1 produce identical output; +c1 does not filter to “middle” at all.

  • CLAN behaviour: +c1 keeps any word with an uppercase letter anywhere, including position 0 (e.g. Triangle), effectively identical to +c.
  • chatter behaviour: +c1 keeps only words with an uppercase letter after position 0 (e.g. McDonald, iPhone); initial-only caps like Triangle are dropped.
  • Reason chatter is correct: the manual’s “middle only” wording, plus the separate +c (“capitalised words only”), make the intent unambiguous, +c1 must exclude position 0. CLAN’s loop never advances past index 0 before its first isupper test, so +c1 collapses into +c; reproducing the bug would make +c1 a useless duplicate of +c.
  • Ledger row: CLAN-DIV-003 (FREQ +c1 middle-only).
  • Pinned by: the freq_c1_mid_capitalization_eng golden (ParityExpectation::DivergesFromClan); the committed golden holds chatter’s corrected output, and the regen step asserts it differs from CLAN’s.

CLAN-DIV-004: FREQ +d2 +d3 mor caveat

FREQ +d2 / +d3 write an aggregate SpreadsheetML file (stat.frq.xls / stat.frq0.xls), one row per (file x speaker) keyed by @ID. The same caveat rows are emitted by the +dCN percent-of-speakers filter (onlydata = 4, words.frq.xls, the +d3-shaped summary over a percent-filtered word subset), so this divergence covers +dCN identically. When the run is on the main tier (not %mor), CLAN prepends three red advisory rows about the type-token ratio. CLAN’s spreadsheet writes those rows with a literal %%mor (its excelRowOneStrCell emits the C string "...%%mor..." verbatim, without the printf un-doubling its stdout path performs), so the cell text reads ...%%mor line forms. / run FREQ on the %%mor line.

  • CLAN behaviour: the spreadsheet caveat rows contain %%mor (a printf %%-escaping leak; CLAN’s own text output correctly shows %mor).
  • chatter behaviour: emits the correct single-percent %mor in those rows.
  • Reason chatter is correct: %%mor is unambiguously a doubled-percent bug; no %mor tier is named %%mor. Every other cell, the @ID columns, the *SPEAKER: pseudo-word counts, the per-word columns, and Types/Token/TTR, is reproduced byte-for-byte; this is the only divergence (verified by a direct diff of chatter’s +d2 output against CLAN’s stat.frq.xls).
  • Ledger row: CLAN-DIV-004 (FREQ +d2/+d3/+dCN %mor caveat).
  • Pinned by: the freq_d2_spreadsheet_manchester, freq_d3_spreadsheet_manchester, and freq_d_percent_lt_eq_manchester goldens (ParityExpectation::DivergesFromClan); the committed golden holds chatter’s corrected SpreadsheetML. Spreadsheet parity is judged on semantic cell equivalence (talkbank-clan/AGENTS.md), not byte-identical XML. The +dCN data cells (the @ID columns, the Speaker header, and the percent-filtered Types/Token/TTR) were verified byte-identical to CLAN’s words.frq.xls on a live run, the same as +d2/+d3.

CLAN-DIV-005: FREQ +xxxx/+xyyy/+xwww byte-stride restore bug

The +x C N U utterance-length filter strips the unintelligible markers xxx/yyy/www from the length count by default; the content-include flags +xxxx/+xyyy/+xwww are documented (manual section 6405) to restore a marker into that count. CLAN applies the restore in correctForXXXYYYWWW (cutt.cpp:16260-16311), which walks the cleaned line and, per loop iteration, advances its index by i += 2 three times (once each for the xxx, yyy, www checks) on top of the for loop’s own i++ – a net stride of 7. It therefore only ever inspects xxx at byte offsets divisible by 7 (and yyy at offsets ≡ 2, www at ≡ 4). Whether a marker is restored thus depends on its byte position in the line, with no basis in the manual.

  • CLAN behaviour: +xxxx restores xxx into the +x length count only when the marker’s byte offset in the cleaned line is ≡ 0 (mod 7); otherwise the marker is silently left out of the count. Verified by a 7-utterance probe (a xxx end … abcdefg xxx end): only the offset-7 case restored.
  • chatter behaviour: restores the marker UNCONDITIONALLY, through the shared AST walker framework::words_for_utterance_length (so restored markers obey the same group-recursion and retrace/replacement rules as countable words).
  • Reason chatter is correct: the manual states the restore without any byte-position qualifier; CLAN’s stride is an off-by-i+=2 C bug, not an intended semantic. On 1082.cha +x=4w +xxxx, chatter correctly restores the xxx inside <we xxx bein(g) in Rochester> [?] (4 -> 5 words, so the utterance leaves the exactly-4 filter), giving *CHI 94 tokens; CLAN’s bug leaves that xxx un-restored and keeps the utterance (*CHI 98).
  • Ledger row: CLAN-DIV-005 (FREQ +xxxx/+xyyy/+xwww byte-stride restore).
  • Pinned by: freq_x_restore_xxx_into_length_count (restore works; *CHI 94, not CLAN’s 98) and freq_x_restore_xxx_diverges_from_clan_byte_stride_bug (the <we xxx …> utterance is correctly dropped, so we is absent), with the default-strip control freq_x_default_strips_xxx_from_length_count.

CLAN-DIV-006: FREQ +r7 CA/satellite-delimiter retention (invalid UTF-8)

+r7 is documented (manual section 14.5, line 12418) as “Do not remove prosodic symbols (/~^:) in words”, a within-word scope: it keeps the lengthening :, blocking ^, clitic ~, and slash / so ca:t stays distinct from cat. CLAN’s implementation reaches far past that scope. The +r7 parser (cutt.cpp:9569-9576) clears all four R7* flags, which flips the per-word cleanup gate at cutt.cpp:7258 from the default HandleSlash (cutt.cpp:7264) to HandleSpCAs (cutt.cpp:7273); it also clears isRemoveCAChar[NOTCA_CROSSED_EQUAL] and isRemoveCAChar[NOTCA_LEFT_ARROW_CIRCLE] (cutt.cpp:9573-9574), two CA classes the manual never mentions. Empirically that +r7 cleanup branch retains the entire CA / satellite-delimiter family as standalone counted “word” tokens, where the default run strips them: ‡ (NOTCA_VOCATIVE, U+2021, check.h:83, CLAN’s own comment “Vocative or summons

  • NOT CA“), „ (NOTCA_DOUBLE_COMMA, U+201E), ≠ (NOTCA_CROSSED_EQUAL, U+2260), and ↫ (NOTCA_LEFT_ARROW_CIRCLE, U+21AB). None is a within-word prosodic symbol. Worse, CLAN’s legacy 8-bit output path mangles the two delimiters whose UTF-8 starts E2 80 (‡, „): it drops the 0xE2 lead byte and emits the invalid-UTF-8 byte pairs 0x80 0xA1 (‡) and 0x80 0x9E („) as the “word type”.

  • CLAN behaviour: under +r7, the CA / satellite delimiters survive into the frequency table as standalone tokens; the E2 80 ones are emitted as invalid UTF-8 byte garbage. Verified by single-utterance probes (each of ‡, „, ≠, ↫ flips a tier from 2 to 3 types under +r7, but not under +r4 or the default) and on 1082.cha, where +r7 adds 12 (*INV1) + 3 (*CHI) corrupt ‡ tokens that the default run omits.

  • chatter behaviour: the --prosody-mode keep (+r7) axis keeps only the modelled within-word prosodic elements (Lengthening :, SyllablePause ^, CliticBoundary ~). A satellite / tag delimiter is not word content in the typed AST, so it never enters the frequency map, and chatter never emits invalid UTF-8.

  • Reason chatter is correct: the manual scopes +r7 to within-word /~^:; the satellite delimiters are between-word markers CLAN’s own source labels “NOT CA”, so retaining them is outside the documented intent. Emitting a frequency “word type” that is not even valid UTF-8 is an unambiguous defect of CLAN’s 8-bit pipeline, not a behaviour any reading of the manual intends.

  • Ledger row: CLAN-DIV-006 (FREQ +r7 CA/satellite-delimiter retention).

  • Pinned by: freq_r7_does_not_retain_corrupt_ca_delimiters (chatter +r7 on 1082.cha is valid UTF-8, emits no 0x80 0xA1, and never counts ‡), alongside freq_r7_keeps_within_word_lengthening / freq_default_strips_where_r7_keeps which pin the documented /~^: keep.

MLU – Mean Length of Utterance

  • Population SD (/ n), not sample (/ n-1). Verified against CLAN output.
  • Brown’s morpheme rules: Only 7 suffix strings count: PL, PAST, Past, POSS, PASTP, Pastp, PRESP. Each adds +1 to the stem count. Fusional features (&PRES, &INF) do NOT count.
  • When no %mor tier exists and not in --words-only mode, reports 0 utterances (matching CLAN).
  • Parity: 100%

MLT – Mean Length of Turn

  • Population SD (/ n), matching CLAN.
  • SD basis: Computed over per-utterance word counts, not per-turn totals.
  • Turn boundaries detected when a different speaker produces the next utterance.
  • Parity: 100%

DSS – Developmental Sentence Scoring

  • Built-in rules are a simplified subset; supply full .scr file for clinical scoring.
  • Sentence-point assignment uses heuristic (subject + verb POS) rather than full syntax.
  • Up to 50 utterances per speaker scored (configurable via max_utterances).
  • Parity: Verified

EVAL – Language Sample Evaluation

  • AST-based word/morpheme identification and typed POS categories.
  • Error counts ([*]) extracted from parsed AST annotations, not text patterns.
  • Parity: Verified

KIDEVAL – Child Language Evaluation

  • Same AST-based approach as EVAL with combined metrics.
  • VOCD uses simplified TTR-based D estimate in the combined report.
  • Parity: Verified

IPSYN – Index of Productive Syntax

  • Parses %mor tier structure for syntactic pattern matching.
  • Built-in rule set is a simplified subset; supply rules file for full coverage.
  • Parity: Verified

VOCD – Vocabulary Diversity (D Statistic)

  • Bootstrap sampling of TTR across sample sizes 35-50, least-squares D-curve fitting.
  • Fusional feature stripping: &PRES, &INF etc. stripped from lemmas in %mor echo output.
  • D values may differ slightly due to random sampling (stochastic algorithm).
  • Parity: 100% (within expected stochastic variation)

FLUCALC – Fluency Calculation

  • Counts disfluency types from main tier annotations.
  • Some categories detected via text pattern matching rather than full AST traversal.
  • Parity: Verified

SUGAR – Grammatical Analysis

  • SUGAR scoring from %mor tier POS categories.
  • %mor post-clitics count as structured morphology, so clitic-bearing chunks contribute to morpheme totals and verb detection.
  • Minimum utterance threshold is configurable (CLAN uses fixed value).
  • Parity: Verified

CHAINS – Clause Chain Analysis

  • CHAINS consumes a clan-local semantic %cod item layer, so selectors like <w4> scope codes instead of being treated as codes themselves.
  • Uses sample SD (N-1), not population SD.
  • Parity: Verified

CHIP – Child/Parent Interaction Profile

  • Implements role assignment, rolling-window scoring, substitution mode, and main-tier/%mor word-source selection; see the CHIP command page.
  • Preserves case by default; +k folds word-stem comparisons while retaining original spelling for output codes.
  • Echoes main and %mor tiers only; other dependent tiers are omitted.
  • -hFILE supports exact and * wildcard patterns against either paired surface or %mor forms; other CLAN selector syntax is rejected. Main-tier mode bypasses merged-tier exclusions. +dN display modes remain unimplemented.
  • Uses Chatter’s typed UD %mor, not legacy CLAN morphology. A failed main-to-%mor alignment rejects the file rather than fabricating scores.
  • Focused unit tests pass. The existing bare-invocation golden does not cover CHIP options, so byte-for-byte option parity is not established.

CODES – Code Frequency

  • Codes extracted from parsed %cod tier, not raw text.
  • %cod is interpreted through a clan-local semantic item layer derived from the AST. Optional selectors like <w4> or <w4-5> scope the next code item instead of being counted as codes themselves.
  • Parity: Verified
  • AST-based content matching rather than raw text pattern matching.
  • Operator syntax: + for AND, , for OR (CLAN uses ^ and |).
  • Parity: Verified

COOCCUR – Word Co-occurrence

  • Bigram counting from countable words per utterance.
  • Parity: Verified

DIST – Word Distribution

  • Every utterance is its own turn (no speaker-continuity grouping), matching CLAN.
  • Parity: 100%

FREQPOS – Positional Frequency

  • Word frequency by utterance position (initial, final, other, one-word).
  • Parity: Verified

GEMLIST – Gem Segments

  • Lists @Bg/@Eg gem boundaries from file headers.
  • Parity: Verified

KEYMAP – Contingency Tables

  • Reads coded data from %cod tier, builds contingency matrix.
  • %cod selector tokens are treated as item scope rather than keyword/following-code values; KEYMAP consumes semantic %cod items.
  • Parity: Verified

MAXWD – Longest Words

  • Reports all occurrences with line numbers, matching CLAN.
  • Parity: 100%

MODREP – Model/Replica Comparison

  • Compares %mod and %pho tiers phonologically via AST.
  • Parity: Verified

MORTABLE – Morphology Tables

  • Tabulates POS categories from %mor tier using script files.
  • POS extraction reads typed %mor items directly instead of reparsing serialized %mor payload text.
  • Parity: Verified

KWAL – Keyword and Line

  • The CLAN manual does document KWAL, including cluster-based search semantics.
  • Scope reduction: The legacy manual describes richer cluster/tier selection and %mor/%gra combined searches than the current implementation exposes.
  • Parity: Verified

PHONFREQ – Phonological Frequency

  • Frequency counts from %pho tier.
  • Parity: Verified

RELY – Inter-rater Agreement

  • Cohen’s kappa for inter-rater reliability.
  • %cod comparison uses semantic code items from the AST-derived layer rather than whitespace tokens from flattened tier text.
  • Parity: Verified

SCRIPT – Template Comparison

  • Word matching uses frequency maps rather than positional alignment.
  • Parity: Verified

TIMEDUR – Time Duration

  • Interaction matrix header includes leading space, matching CLAN exactly.
  • Parity: 100%

TRNFIX – Tier Comparison

  • Uses ∅ for length mismatches between compared tiers.
  • %trn is treated as a structural alias of %mor; %grt is treated as a structural alias of %gra.
  • %mor/%gra comparison preserves typed token boundaries directly from the AST instead of comparing whitespace-split serialized payloads.
  • Parity: Verified

UNIQ – Repeated Utterances

  • Includes %mor/%gra dependent tiers in counts, matching CLAN.
  • Splits multi-line headers for counting, matching CLAN.
  • 1 accepted divergence: Unicode sort order for U+230A (LEFT FLOOR) – C-locale strcoll() vs Rust byte-order. Single line position swap, identical content and counts.
  • Parity: 99%

WDLEN – Word Length Distribution

  • 6-section format matching CLAN exactly.
  • Brown’s morpheme rules: Section 5 = stem + Brown’s suffix (no POS). Section 6 = POS + stem + Brown’s suffix.
  • Clitic handling: Section 5 merges main+clitics as one word. Section 6 counts POS only for main word.
  • Apostrophe stripping: Characters counted after removing apostrophes.
  • Reverse speaker order: CLAN’s linked-list prepend pattern replicated.
  • XML footer: </Table></Worksheet></Workbook> appended.
  • Parity: 100%

Transform Commands

All transforms use the AST pipeline: parse -> transform -> serialize -> write.

DELIM – Add Terminators

  • 4 accepted divergences: CLAN writes empty file when no changes needed; we always write the full file.
  • Parity: 4 accepted divergences

CHSTRING – String Replacement

  • Does not support CLAN’s regex-based patterns in changes files.
  • Parity: Verified

FLO – Fluent Output

  • Walks AST nodes instead of regex-stripping annotation markers.
  • Parity: Verified

POSTMORTEM – Mor Post-processing

  • Typed %mor rewrites are intentionally rejected until an AST-native rewrite path exists. POSTMORTEM errors explicitly when a rule would modify parsed %mor.
  • Current status: user-defined text tiers remain supported rewrite targets; typed %mor rewrite is intentionally unsupported until implemented through the AST.

Other transforms

  • COMBTIER preserves bullet/text tier variants such as %cod and %com instead of degrading them to user-defined tiers.
  • FIXBULLETS supports global offsets and tier-scoped repair across parsed main-tier, %wor, and bullet-content-tier bullets.
  • Bullet-bearing @Comment headers are parsed structurally, so FIXBULLETS can offset those header bullets through the AST as well.
  • Scope reduction remains: old-format bullet conversion, @Media insertion, multi-bullet merge, and +l remain unsupported.
  • Scope reduction: TIERORDER currently uses a built-in tier ordering, while the CLAN manual documents tierorder.cut as a user-controlled ordering source.
  • TRIM follows the CLAN manual intent by removing selected dependent tiers instead of extracting utterance ranges or gem segments. COMBTIER, COMPOUND, DATACLEAN, DATES, FIXBULLETS, LINES, LOWCASE, MAKEMOD, ORT, QUOTES, REPEAT, RETRACE, TIERORDER – all operate on AST rather than raw text, except for the intentionally text-level formatting transforms (DATACLEAN, LINES) and layout transforms (INDENT, LONGTIER) discussed in the dependent-tier semantics audit.

Key Discoveries

These findings were established during parity verification (golden tests comparing against CLAN C binaries):

  1. Brown’s Morpheme Rules: CLAN MLU/WDLEN count only 7 suffix strings as bound morphemes.
  2. Population SD: Both MLU and MLT use population SD (/ n), not sample (/ n-1).
  3. MLT SD basis: Computed over per-utterance word counts, not per-turn totals.
  4. DIST turns: Every utterance is its own turn (no speaker-continuity grouping).
  5. Speaker ordering: CLAN outputs speakers in reverse encounter order (linked-list prepend).
  6. Fusional features: &PRES, &INF etc. are part of the lemma string; strip with split('&').
  7. CHIP echo: CLAN echoes main tiers + %mor only, not %gra tiers.
  8. WDLEN characters: CLAN strips apostrophes before counting character length.

Deliberately Not Implemented

Status: Current

NLP Commands

These commands depend on the legacy CLAN MOR data model – trie-based lexicons, HMM/Brill taggers, and MaxEnt parsers – which is incompatible with the UD-style morphological representation used in the current CHAT grammar and data model. Attempting to invoke them produces a clear error message explaining why.

For morphological analysis, POS tagging, and dependency parsing, use batchalign’s neural pipeline, which supports more languages with higher accuracy.

CommandPurposeWhy not ported
MOR / MOR_PMorphological analysis (add %mor tiers)~11,000 lines of C with trie lexicon and 5 rule engines; output format uses legacy CLAN morphology conventions incompatible with UD-style %mor
POSTPOS disambiguation (disambiguate %mor)Reads ambiguous %mor tiers with ^ separators – a format not supported by the current CHAT grammar
MEGRASPGrammatical relation parsing (add %gra tiers)Requires trained MaxEnt model weights for the legacy CLAN %mor format
POSTLISTList POST database entriesOperates on POST’s proprietary binary database format
POSTMODRULESModify POST rulesOperates on POST’s proprietary binary database format
POSTTRAINTrain POST databaseProduces POST’s proprietary binary database format

CHECK

CommandStatus
CHECKReimplemented as chatter-clan check with full flag support

CHECK is fully ported. chatter validate provides additional spec-driven validation with rich diagnostics beyond what legacy CHECK offered.

Subsumed by existing commands

These commands’ functionality is available through other implemented commands:

CommandAvailable via
GEM (standalone)freq --gem, gemlist
GEMFREQfreq --gem

Truly obsolete

These commands address problems that no longer exist in modern environments:

CommandReason
DOS2UNIXModern systems handle line endings natively
CP2UTFUTF-8 is universal; legacy codepage files are rare
FIXMP3Audio repair, not a CHAT analysis tool
SILENCE_P / PID_PAudio processing, out of scope for transcript analysis

Low-priority / specialized

CommandReason for low priority
GPS / PP / TEMPLATEExtremely specialized, no known active users

CHECK vs chatter validate

Status: Current Last updated: 2026-05-12 21:18 EDT

The chatter CLI has two validation tools with different purposes:

chatter-clan checkchatter validate
PurposeCLAN CHECK compatibilityModern validation workflow
AudienceUsers migrating from CLANDay-to-day development
Output formatCLAN-style *** File "path": line N.Rich diagnostics with context, spans, suggestions
Error codesCHECK numbers (1-161)Typed codes (E###, W###)
FlagsCLAN +flag syntaxModern --flag syntax
CachingNoYes (SQLite-backed)
Directory supportSingle fileRecursive with parallelism
JSON outputVia --format jsonVia --format json
Fix suggestionsNoYes (some errors)
Exit code0 = clean, 1 = errors0 = clean, 1 = errors

Same Validation Engine

Both tools run the same underlying parse_and_validate_streaming pipeline from talkbank-transform. They catch the same errors; the difference is how errors are presented.

                    ┌──────────────────────────────┐
                    │  talkbank-transform           │
                    │  parse_and_validate_streaming  │
                    └──────────┬───────────────────┘
                               │
              ┌────────────────┼────────────────┐
              ▼                                 ▼
   chatter-clan check                  chatter validate
   (CLAN-compatible output)            (modern diagnostics)

When to Use Which

Use chatter-clan check when:

  • Migrating from CLAN: You have scripts that parse CHECK output format
  • Error filtering: You need CHECK’s +eN/-eN to filter by error number
  • Specific CLAN checks: You need +g2 (Target_Child), +g5 (unused speakers)
  • Comparing with colleagues who use original CLAN CHECK

Use chatter validate when:

  • Day-to-day work: Richer error messages with context and suggestions
  • Batch validation: Directory-wide validation with caching and parallelism (-j flag)
  • CI/CD pipelines: JSON output (--format json) for machine parsing
  • Performance: SQLite cache avoids re-validating unchanged files
  • Watch mode: chatter watch provides continuous validation on save

Output Comparison

The same error looks different in each tool. For a file declaring MOT in @Participants: but with no matching @ID: line:

chatter-clan check sample.cha:

*** File "sample.cha": line 4.
@Participants:	CHI Target_Child, MOT Mother
Speaker 'MOT' declared in @Participants but has no matching @ID header(60)

chatter validate sample.cha:

× error[E522]: Speaker 'MOT' declared in @Participants but has no matching
│ @ID header (line 4, column 1, bytes 29..73)
 ╭─[sample.cha:4:1]
 4 │ @Participants:  CHI Target_Child, MOT Mother
   · ──────────────────────┬─────────────────────
   ·                       ╰── here
 ╰────
help: Add @ID header: @ID:	<lang>|<corpus>|MOT|<age>|<sex>|<group>|<ses>|
      Mother|<edu>|<custom>|

Same underlying check (E522 on the typed side ↔ CHECK number 60 on the legacy side); different rendering.

Additional Checks in CHECK

chatter-clan check supports a few checks not available in chatter validate:

CheckFlagDescription
Target_Child+g2 / --check-targetVerifies CHI participant has Target_Child role
Unused speakers+g5 / --check-unusedReports speakers in @Participants but never used
UD features+u / --check-udValidates Universal Dependencies features on %mor

These are CHECK-specific because they are CLAN research conventions rather than CHAT format requirements. chatter validate checks format correctness; CHECK additionally checks research conventions.

Additional Features in chatter validate

FeatureDescription
CachingSQLite cache skips unchanged files
Parallelism-j N for multi-core directory validation
Watch modechatter watch for continuous validation
Fix suggestionsSome errors include actionable help: suggestions
Roundtrip test--roundtrip serializes and re-parses to verify fidelity
Quiet mode--quiet suppresses success output (exit code only)
Max errors--max-errors N stops after N errors

Error Number Mapping

The mapping table from typed ErrorCode to CHECK number 1-161 lives in crates/talkbank-clan/src/commands/check/error_map.rs (check_error_number). The match arms there are the live source of truth, count them directly rather than caching a stale number in this doc. Variants without a CHECK equivalent fall through to 0; those errors render as [<code>] in CHECK output instead of (<n>).

Use chatter-clan check +e to see all 161 CHECK error messages (the canonical strings from CLAN’s check_mess()).

Parity Improvement Plan

Status: Current Current: 95% (113/118): 5 accepted divergences across 2 commands.

Progress

Started at 74% (88/118). Fixed 25 divergences across 10 commands:

CommandDivergences FixedKey Changes
MLU4 → 0Brown’s morpheme counting, population SD
MLT4 → 0Per-utterance SD, population SD
DIST2 → 0Every-utterance turn counting
MAXWD1 → 0All occurrences with line numbers
TIMEDUR4 → 0Interaction matrix header leading space
VOCD4 → 0Echo %mor lemmas (stripped fusional), insufficient tokens
WDLEN4 → 06-section format, Brown’s morphemes, POS-inclusive section 6, apostrophe stripping, reversed speaker order, XML footer
UNIQ3 → 1Include %mor/%gra tiers, split multi-line headers
CHIPInitial 4 → 0 implementation passMatrix, typed role/window/substitution scoring, and main + %mor echo are implemented; option coverage and byte-parity remain open (see CHIP status)

Remaining Divergences (5), All Accepted

DELIM, 4 divergences (all test files)

CLAN writes an empty .cex file when no changes are needed (all utterances already have terminators). Our transform always writes the full file. This is by design, the transform pipeline always writes output, and empty-file detection would require change tracking that adds complexity without user benefit.

UNIQ, 1 divergence (overlaps only)

Unicode sort order edge case: ⌊ (U+230A, LEFT FLOOR) sorts differently between CLAN’s C-locale strcoll() and Rust’s BTreeMap byte-order comparison. Single line position swap, identical content and counts. Not worth adding locale-dependent sorting.

Key Discoveries

  1. Brown’s Morpheme Rules: CLAN MLU/WDLEN count only 7 suffix strings as bound morphemes: PL, PAST, Past, POSS, PASTP, Pastp, PRESP.

  2. Population SD: Both MLU and MLT use population SD (/ n), not sample (/ n-1).

  3. MLT SD basis: Computed over per-utterance word counts, not per-turn totals.

  4. DIST turns: Every utterance is its own turn (no speaker-continuity grouping).

  5. WDLEN morphemes: Section 5 = stem + Brown’s suffix (no POS). Section 6 = POS + stem + Brown’s suffix. Clitic pairs = one word in section 5, POS counted only for main word in section 6.

  6. WDLEN characters: CLAN strips apostrophes before counting character length.

  7. Speaker ordering: CLAN outputs speakers in reverse encounter order (linked-list prepend pattern from the C implementation).

  8. Fusional features: &PRES, &INF etc. are stored as part of the lemma string in our model (for roundtrip fidelity). Strip with split('&') when needed.

  9. CHIP echo: CLAN echoes main tiers + %mor only, not %gra tiers.

Parity Status

Status: Historical audit snapshot; re-baseline pending Last updated: 2026-10-31

Summary

Parity work resumed in this standalone repository on 2026-10-30. The acceptance counts and golden-coverage table below are historical snapshots from May and June 2026; they have not been regenerated against the resumed worktree. Treat the counts and prioritization as historical, not as the current inventory. Do not claim full command parity without fresh, command-specific evidence.

If you are migrating from legacy CLAN and need bit-exact output, use legacy CLAN unless the specific command/options you need have current parity evidence.

The previous audit used a depth-first, one-command-at-a-time strategy and treated FREQ as its active target. Work resumed with CHIP and other feasible gaps; a new full inventory has not yet been completed. Follow the repository’s current AGENTS.md for scope and workflow.

Historical snapshot, 2026-05-27 audit

The numbers below come from the 2026-05-27 run of the audit-vs-reality probe, which compared documented CLAN flags against the exit code and output of chatter-clan <cmd> <flag> <fixture>. The probe has not been rerun since work resumed.

CategoryMeaningCount
ACLAN-documented as Done + chatter accepts the flag (audit row is correct)89
BCLAN-documented as Done + chatter rejects (regression)0
CCLAN-documented as Partial/Missing, work remains201
DDeliberately documented divergence from CLAN2
SKIPNot testable via the probe (file-arg placeholders, etc.)45
Total337

~26% of audited rows are “done and audit-correct”. ~60% are explicit work-remaining (Category C). Zero rows are regressions.

These are historical aggregate counts across roughly 60 CLAN commands. A single command may contain anywhere from a handful to several dozen audit rows depending on its flag richness. FREQ had the most rows in that snapshot and was its active depth-first target.

Golden-verified byte parity (generated)

The snapshot above is acceptance-based: it counts whether chatter-clan <cmd> <flag> is accepted, not whether its output byte-matches CLAN. The table below is the stricter, honest signal, computed from the fail-closed golden tests: how many of each command’s CLAN flag-rows have a byte-for-byte parity golden, versus how many the per-command page still marks Done without one. For any command listed here, this supersedes the acceptance snapshot.

It was generated by the clan_golden metric test (regenerate with UPDATE_PARITY_METRIC=1). This snapshot has not been regenerated since the project resumed. “Claimed Done, no golden” is the gap the acceptance audit could not see.

CommandFlag-rows proven (byte-parity golden)Diverged (documented)Claimed Done, no golden
FREQ25 / 4444
MLT0 / 24010
DIST0 / 502
MAXWD0 / 20012
CHIP0 / 1008
TIMEDUR0 / 300
KWAL1 / 21012
COMBO1 / 24013

FREQ’s 4 “Claimed Done, no golden” rows cannot have a single-file render golden by nature, and are proven at their correct seam instead. Two are the structural flags +u (combine across files) and +re (recurse subdirectories), which chatter makes the default behaviour; they live at the CLI orchestration seam (multiple file arguments, a directory argument), not at single-file render, and are proven by the freq_combine_recurse_tests subprocess tests, with combined-table byte-parity against CLAN’s +0 +u verified against OSX-CLAN/src/clan/freq.cpp. The other two are +oS/-oS and +y, which are Done by rejection: FREQ’s case 'o' rejects non-sort +o forms and +y switches CLAN to a non-CHAT raw-text mode chatter has no analog for, so the correct behaviour is to error, pinned by inapplicable_flag_tests rather than a render golden. The “no golden” column counts the absence of a render golden, which is the right signal to keep visible; the proof exists at the correct seam for each.

Active command, FREQ, DEPTH-COMPLETE (2026-06-04)

Per the depth-first strategy, FREQ was the first command driven to full parity, and it is now depth-complete: every FREQ flag-row is in one of Done (byte-parity or rejects-matching-CLAN), Partial (a chatter abstraction differs, with the residual sub-flags themselves deferred-with-reason), Rewriter-only (errors at parse, correct for an inapplicable flag), or Deferred (scope-gated with a source-grounded reason). Zero rows remain “Missing” without a source-grounded reason.

The deferred rows are all genuine scope gates, not effort gates: %mor / cross-tier flags that need the shared MOR-analysis subsystem (+d0/+d6/+d7/+d8, bare +d, +r8, +r50, +c5); flags that switch CLAN to a non-CHAT raw-text mode chatter has no analog for (+y, +o2); a CA repeat-segment flag that needs a parser span type (+c6); a manual-vs-binary contradiction escalated to the maintainer (+xWORD/+x@FILE, +a); and output-routing infra (+f). The consolidated assessment for the maintainers, including the cost estimate for porting the rest of CLAN, is in the FREQ porting report.

The byte-parity numerator in the table above (25 / 44) counts only the rows with a CLAN-re-running golden; the denominator dropped from 47 to 44 as three rows moved from Missing to Deferred (excluded from the denominator as documented non-goals). The remaining Done rows are rejections, structural (multi-file orchestration), or spreadsheet semantic-equivalence cases that are proven at their own seam rather than by a single-file render golden. With FREQ depth-complete, the next command (a smaller analysis command, e.g. MLU or KIDEVAL) validates that the shared primitives make the second command cheap.

All other commands

Every CLAN command outside FREQ is in one of two states:

  1. Implemented but not depth-first verified. Most analysis, transform, and converter commands have a chatter implementation that handles the common-case flags. They have not been driven through the byte-for-byte parity gate. Treat their output as “approximate”, close enough for many uses, but not a drop-in replacement for legacy CLAN output in a publication-grade workflow.
  2. Intentionally unimplemented. CLAN’s MOR / POST / MEGRASP grammar commands are deliberately redirected to the batchalign neural pipeline rather than reimplemented as legacy CLAN ports. See the command pages for those commands for the deliberate-divergence rationale.

What “done” means here

A command is done when every CLAN-documented flag for it has been classified into one of:

  • matches: chatter implements the CLAN semantic byte-for-byte, with a passing golden test comparing chatter-clan <cmd> <flag> <fixture> to legacy <cmd> <flag> <fixture>.
  • deferred: intentionally not implemented yet, with a written source-grounded reason on the command’s documentation page.
  • diverged: chatter intentionally produces a different result, with a written source-grounded reason on the command’s documentation page.

Anything left as **unverified**, “matches probably”, or “needs checking” disqualifies the command from “done”, every claim must be source-grounded.

How this page is updated

The golden-verified table is generated and CI-guarded: the clan_golden metric test computes it from the fail-closed golden tests (the numerator) and the per-command audit-table denominators, and fails the build if the committed block is stale (regenerate with UPDATE_PARITY_METRIC=1). This is the authoritative, automated signal, and is exactly the CI automation the acceptance snapshot once deferred as “a later step”.

The acceptance snapshot (Category A/B/C/D) is the older, hand-maintained cut from an external probe that records flag acceptance (exit code), not output parity. It is being superseded command by command as each gains golden coverage; do not read its “Done” counts as byte-parity claims.

Faithfulness rules

Two policies govern how chatter implements each CLAN flag:

  1. Faithfulness rule. Every CLAN flag slot, +a, +bN, +c, +dN, +s, +t, etc., implements CLAN’s documented semantic byte-for-byte. Chatter extensions (researcher conveniences not in CLAN, new output formats, ergonomic shortcuts) get a chatter-specific flag name (--list-types, --include-replacements, etc.), never a CLAN slot. Squatting a chatter semantic on a CLAN flag is the worst kind of parity bug ; it looks correct in passing but silently produces non-CLAN output for the exact users (CLAN-trained researchers) the command targets.

  2. No-speculation rule. Every claim about CLAN behavior in this book or in an audit doc carries a file:line citation from CLAN source (e.g. freq.cpp:690-765). Every claim about chatter behavior carries a file:line citation from chatter source. “Likely matches” / “appears invented” guesses are banned unless explicitly tagged **unverified** with the specific file:line that would settle the question.

Canonical CLAN source for citations

When this book or any audit cites a CLAN behavior at a file:line, the path resolves inside the TalkBank/OSX-CLAN repository on the dev branch, under src/clan/<file>.cpp.

OSX-CLAN/dev is the TalkBank Git layer over the upstream CLAN maintainer’s latest unix-clan.zip from dali.talkbank.org, published there far more often than committed to GitHub. Citations against master of the same repository are typically stale; always ground at dev after the most recent sync. A sync script imports the latest snapshot onto dev as a single dated commit, so git log src/clan/<file>.cpp on dev is the de-facto audit history of upstream changes.

Design Philosophy

Status: Current Last updated: 2026-05-12 08:37 EDT

Semantic AST processing

The original CLAN processes CHAT files as text, using string-prefix checks like starts_with('&') or == "xxx" to identify word types. The Rust reimplementation works on a parsed AST where every word has typed fields (Word.category, Word.untranscribed()) and where replacements live as a distinct UtteranceContent::ReplacedWord variant wrapping the original Word. This eliminates entire classes of bugs where string patterns match unintended content.

Two-layer architecture

framework/     Shared infrastructure (runner, filters, output, word utilities)
commands/      Individual command implementations
transforms/    File-modifying commands
converters/    Format conversion commands

The framework handles file discovery, CHAT parsing, speaker/tier/word/gem/range filtering, and output formatting. Commands implement only their analysis logic.

Typed results

Every command defines a result struct implementing CommandOutput. This struct is the single source of truth, render_text(), render_clan(), render_csv(), and JSON output (via the Serialize bound and to_json_value() / render(OutputFormat::Json)) all derive from the same data. No ad-hoc string building that could drift between formats.

Stateless commands

Commands hold only configuration (Config). All mutable state lives in a separate State type that is built up utterance-by-utterance via process_utterance(), optionally settled per file in end_file(), and consumed at the end of the run by finalize(state) -> Output. This makes the data flow explicit and testable.

Parity by default

Output from render_clan() must match legacy CLAN output exactly, warts and all. Improvements go in render_text(). Golden tests compare against actual CLAN binary output to enforce this.

Framework

Status: Current Last updated: 2026-05-12 08:35 EDT

The framework (crates/talkbank-clan/src/framework/) provides shared infrastructure for all commands.

Runner

The command runner (AnalysisRunner in framework/runner.rs) handles the lifecycle:

  1. Parse: read and parse the CHAT file via talkbank-transform
  2. Filter: apply speaker, tier, word, gem, range, and ID filters
  3. Dispatch: call process_utterance() for each matching utterance
  4. Per-file end: call end_file() after all utterances in a file
  5. Finalize: after all files are processed, call finalize(state) -> Output
  6. Render: format the result as text, JSON, CSV, or CLAN-compatible output via Output::render(format)
flowchart TD
    input["Input files"]
    runner["AnalysisRunner::run()"]
    parse["parse_file_and_validate()\n→ ChatFile"]
    filter["FilterConfig\n(speaker, tier, word,\ngem, range)"]
    process["cmd.process_utterance()\n→ update State"]
    endfile["cmd.end_file()"]
    finalize["cmd.finalize(state)\n→ Output"]
    render["Output::render(format)\n→ Text / JSON / CSV"]

    input --> runner
    runner -->|per file| parse --> filter
    filter -->|matching utts| process
    process -->|loop| filter
    filter -->|file done| endfile
    endfile -->|all files done| finalize --> render

Traits

AnalysisCommand

Per crates/talkbank-clan/src/framework/command.rs:52:

trait AnalysisCommand {
    type Config;
    type State: Default;
    type Output: CommandOutput;

    fn process_utterance(
        &self,
        utterance: &Utterance,
        file_context: &FileContext<'_>,
        state: &mut Self::State,
    );

    /// Called after each file. Default impl does nothing.
    fn end_file(&self, _file_context: &FileContext<'_>, _state: &mut Self::State) {}

    /// Called once after all files. Produces the typed output.
    fn finalize(&self, state: Self::State) -> Self::Output;
}
classDiagram
    class AnalysisCommand {
        <<trait>>
        +process_utterance(utt, ctx, state)
        +end_file(ctx, state)
        +finalize(state) Output
    }
    class Config {
        command-specific options
    }
    class State {
        +Default
        accumulated results
    }
    class Output {
        +Serialize
        +CommandOutput
        +render(format) String
    }

    AnalysisCommand --> Config : holds
    AnalysisCommand --> State : mutates
    AnalysisCommand --> Output : produces

TransformCommand

Transform commands receive a mutable ChatFile and modify it in place.

CommandOutput

Per crates/talkbank-clan/src/framework/output.rs:48:

trait CommandOutput: Serialize + std::fmt::Debug {
    /// Dispatch render by format.
    fn render(&self, format: OutputFormat) -> String { ... }

    /// JSON serialization (uses the `Serialize` bound).
    fn to_json_value(&self) -> serde_json::Value { ... }

    /// Required: clean text rendering.
    fn render_text(&self) -> String;

    /// Default: falls back to `render_text()` for commands not yet
    /// CLAN-matched.
    fn render_clan(&self) -> String { self.render_text() }

    /// Default: empty string.
    fn render_csv(&self) -> String { String::new() }
}

JSON output is produced by render(OutputFormat::Json), which uses serde_json::to_string_pretty(self) via the trait’s Serialize bound, not a custom render_json() method.

Word utilities

  • countable_words(): iterate words that should be counted (skips untranscribed, fillers, etc.)
  • is_countable_word(): predicate for individual words
  • NormalizedWord: wrapper with Borrow<str> for zero-allocation frequency map lookups

Filter system

Filters are configured from CLI flags and applied by the runner before dispatching to commands. Commands never check filters directly.

Adding a Command

Status: Current Last updated: 2026-05-12 17:30 EDT

Steps

  1. Create the module: crates/talkbank-clan/src/commands/<name>.rs with four types:

    • <Name>Config: command configuration (from CLI flags)
    • <Name>State: mutable accumulator (implements Default)
    • <Name>Result: typed output (implements Serialize, Debug, CommandOutput); this is what the trait’s associated Output type resolves to
    • <Name>Command: unit struct implementing AnalysisCommand
  2. Register: add pub mod <name>; to crates/talkbank-clan/src/commands/mod.rs

  3. Wire CLI: add a subcommand variant to ClanCommands in crates/talkbank-cli/src/cli/args/clan_commands.rs

  4. Wire dispatch: add the match arm in the appropriate family module (analysis.rs, transforms.rs, converters.rs, compatibility.rs, or helpers.rs) under crates/talkbank-cli/src/commands/clan/; keep run_clan() in crates/talkbank-cli/src/commands/clan/mod.rs as the thin top-level dispatcher

  5. Add golden test: add a test case in the relevant file under crates/talkbank-clan/tests/clan_golden/

Skeleton

The trait is defined in crates/talkbank-clan/src/framework/command.rs. It has three associated types (Config, State, Output) and three methods (process_utterance, end_file with a default no-op impl, and finalize).

//! # NAME, Brief description
//!
//! What the command does and when to use it.

use serde::Serialize;
use talkbank_model::Utterance;

use crate::framework::{AnalysisCommand, CommandOutput, FileContext};

/// Command configuration.
pub struct NameConfig {
    // fields from CLI flags
}

/// Per-run accumulator (carried across all files).
#[derive(Default)]
pub struct NameState {
    // mutable state built up during processing
}

/// Typed analysis result.
#[derive(Debug, Serialize)]
pub struct NameResult {
    // typed output fields
}

impl CommandOutput for NameResult {
    fn render_text(&self) -> String { todo!() }
    fn render_clan(&self) -> String { todo!() }
}

/// The command.
pub struct NameCommand {
    pub config: NameConfig,
}

impl AnalysisCommand for NameCommand {
    type Config = NameConfig;
    type State = NameState;
    type Output = NameResult;

    fn process_utterance(
        &self,
        utterance: &Utterance,
        file_context: &FileContext<'_>,
        state: &mut Self::State,
    ) {
        // accumulate per-utterance data into `state`
    }

    // end_file has a default no-op impl; override only if you need
    // per-file finalization.

    fn finalize(&self, state: Self::State) -> Self::Output {
        // compute final result from the accumulated state
        todo!()
    }
}

Conventions

  • Use countable_words() for word iteration, don’t roll your own filter
  • Use NormalizedWord for frequency maps
  • Handle missing %mor gracefully (skip morpheme counting, don’t panic)
  • Keep the module under 400 lines; split into submodules well before it becomes another 800+ line file

Current Architecture Seams

Status: Current Last modified: 2026-05-30 21:19 EDT

This page documents the current internal seams that contributors should preserve when adding or restructuring CLAN-related functionality.

CLI command registration

Top-level CLI argument wiring is no longer in one file.

  • shared CLI args live in crates/talkbank-cli/src/cli/args/core.rs
  • shared CLAN filters and common options live in crates/talkbank-cli/src/cli/args/clan_common.rs
  • CLAN command variants live in crates/talkbank-cli/src/cli/args/clan_commands.rs

If you add a new CLAN command, register it in the appropriate split argument module instead of rebuilding a monolithic args.rs.

CLAN dispatch

run_clan now lives in crates/talkbank-cli/src/commands/clan/mod.rs and dispatches into category files:

  • analysis.rs
  • transforms.rs
  • converters.rs
  • compatibility.rs
  • helpers.rs (shared utilities consumed by the others)

Keep family-specific logic in those modules. Shared file resolution, filtering, and output helpers belong in helpers.rs, not copied into each family.

Validation output

Parallel validation output now has a renderer seam:

  • orchestration and stats live in crates/talkbank-cli/src/commands/validate_parallel/runtime.rs
  • output shaping lives in crates/talkbank-cli/src/commands/validate_parallel/renderer.rs
  • audit-specific behavior lives in crates/talkbank-cli/src/commands/validate_parallel/audit.rs

If you need a new output mode, add a renderer implementation instead of extending a large runtime match.

Audit-mode JSONL writing is also intentionally isolated. crates/talkbank-cli/src/commands/validate/audit_reporter.rs owns a dedicated writer thread and a cloneable reporting handle for workers, so future audit changes should preserve that explicit ownership boundary instead of reintroducing shared writer locks.

Dashboard state ownership

The old test-dashboard note in this chapter referred to a module from an earlier monorepo layout and does not correspond to a live module in this repository. There is currently no src/test_dashboard/ tree in TalkBank/chatter, so treat any future dashboard work as new design work rather than following those stale paths.

Editor integration note

The VS Code extension and talkbank-lsp use a typed execute-command boundary. The contract surface is documented in:

  • book/src/vscode/reference/rpc-contracts.md: the RPC contracts the extension and LSP speak
  • book/src/vscode/developer/custom-commands.md: how to add a new custom command
  • crates/talkbank-lsp/CLAUDE.md: invariants for the server side

Coding Standards

Status: Current Last updated: 2026-05-12 17:36 EDT

Universal Rust Standards

These apply to all Rust code across the TalkBank workspace.

Edition and Tooling

  • Rust 2024 edition
  • cargo fmt before committing
  • Prefer cargo nextest run for faster test execution
  • cargo clippy --all-targets -- -D warnings periodically

Error Handling

  • No panics for recoverable conditions, use typed errors (thiserror)
  • No silent swallowing, no .ok(), .unwrap_or_default(), or silent fallbacks

Output and Logging

  • Library code: tracing macros only, never println!/eprintln!
  • CLI binaries: println!/eprintln! for user-facing output
  • Test code: println! is acceptable

Type Design

  • No boolean blindness. Enums over bools for anything beyond simple on/off. Banned: 2+ bool params, 2+ related bool fields, opposite bool pairs, ambiguous bool returns
  • BTreeMap for deterministic JSON in tests
  • Prefer explicit enums over ambiguous Option

File Size Limits

  • Recommended: 400 lines or fewer
  • Hard limit: 800 lines (must be split)

CLAN-Specific Standards

Typed Data, Not String Matching

Use the AST (word.category, word.untranscribed()) instead of string-prefix checks (starts_with('&'), == "xxx"). This is the fundamental reason for the Rust port.

No Panics

Handle missing data gracefully. No %mor tier? Skip morpheme counting. Use tracing::warn! for recoverable file-level issues.

Typed Results

Every command defines its own result struct implementing CommandOutput. Avoid the generic AnalysisResult container.

Stateless Commands

All mutable state goes in the State type. Commands hold only config.

Use Framework Utilities

  • countable_words() for word iteration
  • NormalizedWord for frequency maps
  • Never check filters in command code, the runner handles them

Library Crate

No println!/eprintln!, use tracing.

Documentation Standards

Use CLAN.html for legacy intent

When a command is documented in the CLAN manual, command docs should use that manual to explain the command’s intended semantics, examples, and tier assumptions. Do not infer intent from accidental legacy string behavior if the manual states the intended behavior more clearly.

Say when the manual is absent or incomplete

Some implemented commands do not have a standalone section in the CLAN manual, or are only mentioned indirectly. In those cases, say so explicitly in the command chapter and document what other evidence is being used instead.

Separate CLI docs from GUI docs

Carry over non-GUI command semantics into the talkbank-clan book. GUI workflows from the legacy manual should be documented in the TalkBank VS Code extension docs instead of being mixed into the CLI command reference.

Golden Tests

Status: Current Last updated: 2026-05-31 13:09 EDT

Golden tests under crates/talkbank-clan/tests/clan_golden/ (driven by the top-level clan_golden.rs entry point) and crates/talkbank-clan/tests/transform_golden.rs compare chatter-clan output against the legacy CLAN C binaries character-by-character.

How they work

  1. Run the legacy CLAN binary on a reference corpus fixture file
  2. Run the equivalent chatter-clan command on the same file
  3. Snapshot both outputs with insta (suffixed @clan and @rust)
  4. Any difference is a parity divergence that must be explained or fixed

The @clan snapshots capture CLAN’s exact output and should never change (they represent the ground truth). The @rust snapshots capture our output and should match @clan as closely as possible.

Requirements

Golden tests require CLAN binaries. The lookup is a single env var:

  • CLAN_BIN_DIR: directory containing the CLAN command binaries (check, freq, mlu, …)

See clan_bin_dir() and clan_command_available() in crates/talkbank-clan/tests/common/mod.rs. If CLAN_BIN_DIR is unset or the specific command binary is missing from that directory, the test prints a skip notice via require_clan_command() and returns early, making it CI-safe.

(Note: the legacy CLAN library paths used by database_integration.rs follow a different resolver, CLAN_SOURCE_DIR env var → sibling OSX-CLAN/ checkout → ~/OSX-CLAN/. That is unrelated to the golden-test bin lookup.)

Fixture files

Test fixtures come from the reference corpus at corpus/reference/ (at the repo root). Common fixtures include:

  • tiers/mor-gra.cha: morphology and grammar tiers
  • ca/overlaps.cha: CA overlap markers
  • Various language-specific files for encoding edge cases

Current parity

The current parity tally and the per-command divergence list live in Per-Command Divergences, that page is the single source of truth, so the numbers stay in one place instead of drifting between docs.

Adding a golden test

The harness in crates/talkbank-clan/tests/clan_golden/harness.rs provides two patterns:

  • Paired CLAN + Rust comparison: declare a ParityCase and let the parity_case_tests! macro generate the test. CLAN side is auto-skipped when clan_command_available() reports the binary missing. Example: clan_golden/check.rs:3 declares two paired CHECK cases.
  • Rust-only snapshot (when no CLAN binary corresponds, or the comparison is a one-off), call the command’s typed Command/run_xxx API directly and snapshot the output. Example: clan_golden/rust_only.rs shows the MORTABLE, RELY, and SCRIPT patterns.

Helpers used by both patterns:

  • corpus_file("tiers/mor-gra.cha"): resolve a path under corpus/reference/
  • clan_command_available("freq") / require_clan_command("freq", "skip context"), gate CLAN-side execution
  • run_clan("freq", &file, &["-t", "*CHI"]): run a legacy CLAN binary, returning Option<String>
  • run_rust(...) / run_rust_filtered(...), run the chatter side with optional filter args

The snapshot naming convention is <case>@clan for the CLAN output and <case>@rust for the chatter output; both land under tests/clan_golden/snapshots/.

For a transform command, see tests/transform_golden.rs for the pattern, transforms write to temp files rather than stdout, and run_rust_transform() returns the contents of the rewritten file.

Diagnosing parity breaks

When a golden test fails:

  1. Run cargo insta review to see the diff
  2. Check if the @clan snapshot changed (it shouldn’t, that means the CLAN binary or fixture changed)
  3. If only @rust changed, determine whether it’s a bug fix or regression
  4. If the divergence is intentional and justified, accept it and document in Per-Command Divergences

CLAN Parity Field Guide

Status: Current Last updated: 2026-06-12 19:01 EDT

This page is the distilled, cross-cutting field guide for porting a CLAN command to byte-for-byte parity in chatter-clan. It is not the mechanical how-to (see Adding a Command) and not the per-flag record (that lives in each command page’s audit table, e.g. FREQ). It is the wisdom layer: the patterns, landmines, and infrastructure that the FREQ depth-first effort surfaced, written so the next porter (FREQ flag #N, or CLAN command #2) does not re-learn them the hard way.

It is a living document: append a short “what this row taught” note whenever a flag or command surfaces a reusable lesson, and the accumulated result is the final porting report. Much of what follows was reconstructed from FREQ’s audit notes, the divergence ledger, and commit history; future rows should add their lesson as they land, not weeks later.

Why this exists. Completing FREQ to full parity is the vehicle for estimating the cost of porting all of CLAN. That estimate is only as good as the reusable template and shared primitives the work produces. This guide is that template made explicit.

1. The method: source-grounded, golden-first, depth-first

The unit of work is the command, not the flag (see the parity strategy in the repo AGENTS.md). Within a command, each flag-row follows the same loop:

  1. Read the manual section for intent. CLAN.html states what a flag is intended to do. Cite it by section. The manual and the CHAT manual are different documents; use CLAN.html for command flags.
  2. Read the command’s own getflag in CLAN source for behavior. This is the single most important habit. CLAN commands intercept flags in their own getflag() (e.g. freq.cpp:621, the case 'd'/case 'o' blocks) before falling through to the shared maingetflag (cutt.cpp). The book’s own draft notes are a map, not the authority, and have been wrong (the +c2 and +d rows both shipped with manual-only drafts that the source contradicted). Cite behavior file:line.
  3. Live-probe the binary to seed the oracle. Run the real CLAN tool on a trimmed fixture, capture the exact bytes. This is not “reading the implementation”; the binary’s output is the spec. Pin the residual uncertainties (sort order, wildcard handling, exact wording) here.
  4. Write the failing top-level test first (golden for render parity, subprocess for CLI/rewriter/error paths); see §6.
  5. Implement across the five seams (§4), then GREEN.
  6. Localize any divergence with judgment, not reflex (§5).

Every claim about CLAN carries two citations: a manual section (intent) and a file:line (behavior). Every claim about chatter carries a chatter file:line.

2. The biggest structural lesson: a flag prefix is rarely a scalar

CLAN overloads a single flag letter onto multiple orthogonal state variables, dispatched by the characters that follow it. Modeling such a prefix as one scalar “mode integer” is the worst kind of parity bug: it looks right and is silently wrong for the exact users (CLAN-trained researchers) the command targets.

FREQ +d (freq.cpp:838-913) is the canonical example. The one letter drives:

Sub-formCLAN state setchatter flag
+d1isCombineSpeakers + onlydata--word-list-only
+d2/+d3onlydata=3/4 (spreadsheet)--spreadsheet per-word/summary
+d4onlydata=5 (types/tokens text)--types-tokens-only
+d5zeroMatch (independent boolean)--include-zero-frequency
+d8isCrossTabulation(deferred, %mor cross-tier)
+d20isSpreadsheetOnePerRow(pending)
+d<N …percentC + percent (forces spreadsheet)(pending)

FREQ +o (freq.cpp:815-837) is the same shape: +o/+o0 → isSort, +o1 → revconc=1, +o2 → revconc=2+chatmode=0, +o3 → isCombineSpeakers.

Rule. Decompose the prefix into its independent axes and give each a distinct, typed chatter field (an enum when there are >2 states, a single include_*/combine_* bool only when the name fully communicates true). Never a --display-mode N catch-all, which both squats CLAN slots and reintroduces boolean/int blindness. The decomposition is also the honest unit of the porting-effort estimate: count axes, not flag letters.

3. The faithfulness rule, and un-squatting

Every CLAN flag slot implements CLAN’s documented semantic byte-for-byte. Chatter conveniences (new formats, ergonomic shortcuts) get chatter-only flag names, never a CLAN slot.

FREQ shipped several squats that had to be undone: +d2/+d3 were mapped to a chatter --format csv stdout convenience, and +d5/+d20/etc. fell through a generic +dN → --display-mode N rewrite. Un-squatting means: route the CLAN slot to a faithful implementation, and keep the chatter convenience reachable under its own name. Watch for squats whenever a rewriter arm maps a CLAN slot to a pre-existing chatter flag that does not match CLAN’s documented semantic.

4. The five implementation seams (the porting template)

A flag touches the same layers every time. Internalize this and each new flag is a fill-in-the-blanks exercise.

flowchart LR
    A["CLAN +flag<br/>(clan_args/rewriter.rs)"] -->|"--flag"| B["clap field<br/>(clan_commands/mod.rs)"]
    B --> C["dispatch + guards<br/>(commands/clan/analysis.rs)"]
    C -->|"FreqOptions"| D["service builder<br/>(service_types/builder.rs)"]
    D -->|"FreqConfig"| E["command logic<br/>(commands/freq/mod.rs)"]
    E -->|"FreqResult"| F["render<br/>(commands/freq/output.rs)"]
    G["golden harness<br/>(tests/clan_golden/harness.rs)"] -. "builds FreqConfig directly,<br/>bypassing A-D" .-> E
  1. Rewriter (clan_args/rewriter.rs): +flag → --flag, subcommand-guarded (the same +d/+o letter means different things in FREQ vs KWAL vs COOCCUR, so every arm matches on subcommand). Unmapped forms fall through to clap, which rejects the literal token, so an unimplemented flag errors on paste rather than silently no-oping.
  2. Clap field (cli/args/clan_commands/mod.rs): the typed chatter flag. Value-enums for multi-state axes; bare bool only for single include_*/combine_*.
  3. Dispatch (commands/clan/analysis.rs): map clap args → domain options via small *_to_* free functions (house style). Flag-combination guards live here, not in the command/service; see §7.
  4. Options → Config (service_types/{options,builder}.rs → commands/freq/mod.rs): typed config field. Per-row mutable state goes in the State type; pure logic in count_utterance/finalize.
  5. Render (commands/freq/output.rs): the CLAN-format render is the parity target; text/JSON/CSV are chatter’s own formats and need not match CLAN.

Sixth touch point: the golden harness (tests/clan_golden/harness.rs) constructs FreqConfig directly from the rust-side args, bypassing seams 1-4. So a new config field needs a one-line extra_args.contains(...) / parse_* addition in the harness too, or the golden cannot exercise it.

5. Localizing a divergence: four terminal states, not “make it match”

When chatter differs from the binary, the answer is judgment, grounded in the manual, into exactly one of:

  • chatter bug → fix chatter (the default when the binary agrees with the manual).
  • CLAN-binary bug → diverge deliberately; mark the golden DivergesFromClan, document with both a manual citation and a source file:line. Worked example: CLAN-DIV-003, FREQ +c1 : the manual says “uppercase in the middle,” but the binary’s isRightUpper loops from position 0 and also keeps initial-caps. chatter implements the documented semantic; the golden asserts it differs from CLAN.
  • manual mistake / outdated text → escalate; do not decide solo.
  • data / %mor tagging artifact → raise as a MOR/data matter; do not bake a workaround into the command.

There is a fourth terminal state beyond “matches/diverges”: deferred. FREQ +o2 sets chatmode=0, reinterpreting the CHAT file as plain text and counting whole input lines as tokens (%mor:/@ID:/@Begin included). That is incompatible with chatter’s AST-first model (it would require bypassing the parser), so it is a documented non-goal, not an open gap. A command is “done” when every row is matched, diverged, or deferred, not when every row has a golden. This is modeled by the Deferred BookStatus, which the parity metric excludes from the provable denominator.

6. Testing: golden is the render oracle, subprocess is the CLI oracle

The flag’s seamTop-level test
Single-file render parityGolden vs OSX-CLAN (tests/clan_golden/)
CLI parsing / rewriter / error pathsSubprocess (assert_cmd, crates/talkbank-cli/tests/)
Multi-file / directory orchestration (+u, +re)Subprocess (no single-file render exists by nature)

Write the failing test before the implementation. The golden is seeded from the binary (just regen-clan-goldens, needs CLAN_BIN_DIR); the RED is then chatter’s render not matching the committed golden.

Harness gotchas that recur for every command

  • CLAN reads stdin. The harness pipes the fixture to the binary; the banner reads From pipe input, and the raw output carries a doubled banner plus a carriage-return progress-garbage line (8\r\t ). strip_clan_header normalizes all of this; the committed golden starts at the first real content line.
  • Header-less / count-first output. strip_clan_header used to drop the first line whenever its first token was numeric, correct for the progress line, but it also ate a real count entry (1 Triangle) for output with no Speaker: banner (FREQ +o3 combined mode). Fixed to drop only a single numeric token line. Any command whose output can begin with a count rather than a header will hit this; the fix is in place but the lesson generalizes.
  • The command-echo banner echoes your search terms. A subprocess test that asserts out.contains("zzz") on a +szzz run is fooled by the echoed command line. Assert on the table entry form ( <count> <word>\n), not raw stdout. (Bit +c4, +u/+re, and +d5.)
  • Verify infra changes are benign by regenerating all goldens and confirming zero diff to existing files (the strip_clan_header fix was validated this way).
  • None (rewriter pass-through) does NOT reject a +-prefixed token, it makes it a bogus FILE argument. Many rewriter arms return None with the comment “pass through so clap rejects the literal token.” That holds for --prefixed tokens (clap treats - as its option sigil and rejects unknown shorts) but is FALSE for +-prefixed tokens: clap does not treat + as an option prefix, so +d8 / +QQQ pass through as a positional, the shared file-discovery layer warn-skipped it as a missing file, and the command exited 0 with DEFAULT output, silently wrong for the exact CLAN-trained user the command targets. Fixed systemically (2026-06-04) at the DiscoveredChatFiles boundary (talkbank-clan/src/framework/input.rs): a positional beginning with +/- (a bare - stdin marker exempt) routes to UnrecognizedClanFlagArgs, and into_files() is now fallible so every consumer (the analysis service for FREQ/MLU/…, CHECK, find, LSP) is forced by the type to handle it. Lesson: an unconsumed flag-shaped token must ERROR; prove it with a subprocess test asserting the unknown/unimplemented flag exits non-zero (inapplicable_flag_tests.rs), not just that the known flags work.

7. Where flag-combination guards live

CLAN rejects many flag combinations (+c2 needs a wildcard +s and forbids a multi-word +s; +d5 forbids wildcards/duplicates in +s and requires at least one +s). These guards depend on the extracted per-word filter, which is assembled at the CLI dispatch (analysis.rs, take_per_word_filter). So the guards live there, emitting exit_with_error, not in a service-layer TryFrom.

This was a deliberate altitude call (a /simplify pass explicitly kept the +c2 guard at dispatch): plumbing typed domain errors out of the service is unreachable from the LSP today, so dispatch is the correct, consistent home. New combination guards mirror the +c2/+d5 block exactly.

8. Shared framework primitives (the real porting accelerant)

Extracting reusable primitives is first-class work, not cleanup: the next command’s cost is dominated by whatever new primitive its hardest flags need. What FREQ has produced so far:

  • framework::diversity::moving_average_ttr (FREQ +bN MATTR): a windowed TTR average reusable by VOCD and other lexical-diversity measures.
  • framework::multiword (FREQ +s"a b", +c3/+c4/+c7) : the multi-word search engine. Its matcher returns Match spans (slot→token indices), not booleans, precisely so KWAL (context windows), COMBO (combinations), and FREQ (count + matched-words display) reuse one engine. This is the de-risking that justified doing the multi-word cluster early.
  • WordFilter with WordFilterMode::PerWordEmit and count_matching_includes : per-word include/exclude with +c2 multiplicity.
  • The match-mode axes as typed enums (MatchOrder, MatchScope, MultiWordMatch) : no boolean blindness at the seam.
  • framework::dependent_tier_tokens (FREQ +t%X): the raw dependent-tier token stream (whitespace-split, bare-. dropped) for an arbitrary %X, keyed off DependentTier::kind(). KWAL/COMBO +t%X reuse it; the byte-identical open-coded form in rely/keymap/chains (each behind a %cod special-case) should migrate onto it. Kept deliberately pure (no analysis-specific excludes) so it stays a faithful tokenizer for all consumers; CLAN’s per-command default-exclude list is layered on top by the command (see §9).

When a command’s hardest flag needs logic that another command will also need (tier scoping, cross-tabulation, context windows), build it as a framework primitive returning typed spans/values, not a command-local helper.

9. Landmines specific to CLAN semantics (verify per command)

  • Case polarity is per-command. FREQ preserves case by default (nomap=TRUE, cutt.cpp:7845) and +k folds; KWAL/COMBO/FREQPOS/DIST/MAXWD fold by default and +k preserves. Resolve once via AnalysisCommandName::effective_case_sensitive and thread the effective value to both the +s filter and the table keying. Getting the polarity backwards silently changes every count.
  • +s is a per-word emit filter for FREQ, not an utterance gate. Utterances with no matching word still appear; non-matching words inside a matching utterance are not counted. Extracted via take_per_word_filter; the framework utterance-gate filter must NOT also carry these patterns. Other commands may use +s as a true gate; check the source.
  • Word identification is AST-based, not prefix-based. CLAN drops xxx, www, and word[0] in {0,&,+,-,#} by character prefix; chatter uses is_countable_word() on semantic type, which is more precise (a filler &-um and a fragment &+fr have distinct types). This is an accepted, documented refinement, not a divergence to “fix.”
  • Spreadsheet output is the one byte-parity exception: compare parsed cells (semantic equivalence), not raw SpreadsheetML, because CLAN’s .xls/.cex carries non-semantic version/style boilerplate. Everything else stays byte-for-byte.
  • The CLAN wildcard set is * % _ (isFoundWildCard), not just *. Guards that only check * are subtly incomplete.
  • CLAN seeds a default exclude-word list at command init, distinct from tier tokenization. maingetflag/maininitwords plus per-command mor_initwords (cutt.cpp:8827-8833: beg|*,end|*,cm|*,…) and gra_initwords (cutt.cpp:8835-8840: *|*|{BEGP,ENDP,LP,PUNCT}) add patterns every token is matched against and dropped if it hits. This is why FREQ +t%gra drops the N|M|PUNCT relations and +t%mor drops markup morphemes, even though they are real whitespace tokens on the tier. The patterns are anchored (beg|* is a prefix, *|*|PUNCT a suffix), so exact prefix/suffix tests reproduce them without a general wildcard matcher. Crucially these lists are per-command: gra_initwords’s only caller is FREQ, mor_initwords is shared by ~30 commands. So the default-exclude belongs with the command’s counting, not the shared tokenizer, or sibling consumers (rely/keymap, which want the raw tokens) inherit excludes they should not.

10. The metric, and reading “how done is this command”

book/src/clan-reference/parity-status.md carries a CI-guarded, generated table: flag-rows proven (byte-parity golden) / provable rows, plus diverged (documented) and claimed-Done-no-golden (the overclaim gap the acceptance audit could never see). Regenerate with UPDATE_PARITY_METRIC=1. Deferred rows are excluded from the denominator. A row counts as proven only when a golden’s covers flag matches the book audit row, so the book table and the goldens cross-check each other; drift in either fails CI.

11. Effort model for the whole-CLAN port (the deliverable)

What FREQ is teaching about the cost of the remaining ~60 commands:

  • Cheap, once the template + primitives exist: sort variants, display modifiers, search/percent filters, speaker/tier selection: bounded, self-contained, golden-provable. These are a few hours each: audit, one golden, one subprocess test, fill the five seams.
  • Expensive: anything needing a new framework primitive (multi-word engine, cross-tabulation, context windows, tier alignment) or that reinterprets the input (chatmode=0). Cost is dominated by the primitive, which then amortizes across every command that reuses it.
  • Watch for overlap with separate commands. FREQ +d6/+d7/+d8 (%mor source/target linking, cross-tabulation) overlap mortable/freqpos; their scope is a PI decision (port inside FREQ, or share with the sibling command?), not a solo call. Flag these rather than absorb them.

The per-command estimate is therefore roughly: (source-audit time) + (Σ cheap flags × template cost) + (Σ new primitives × primitive cost). The denominator of the parity metric, read across commands, is the visible proxy for that sum.

Per-row lessons log

Append a one-paragraph note here when a flag teaches something reusable. Keep the granular per-flag behavior in the command page; keep the transferable lesson here.

  • +bN MATTR (2026-06-02): first extraction of a framework::diversity primitive; established that a lexical-diversity measure should be a shared windowed function, not a FREQ-local loop. Also the first flag with a spreadsheet-column interaction (+b adds a trailing MATTR column to +d2/+d3).

  • Multi-word cluster +s"a b"/+c3/+c4/+c7 (2026-06-02): the framework::multiword engine; the decision to return Match spans rather than booleans so KWAL/COMBO reuse it. Largest single de-risking of the remaining port.

  • +c2 (2026-06-02): source contradicted the manual-only draft (capwd==3 is single-word per-pattern multiplicity, not a multi-word mode). Established the dispatch-layer guard pattern and the “read the source, not our draft” rule.

  • +d2/+d3 spreadsheet (2026-06-02): semantic-equivalence (parsed cells) is the one byte-parity exception; reuse talkbank-model IDHeader rather than re-parsing @ID.

  • +d5 zeroMatch (2026-06-03): an independent boolean axis squatting under the +d prefix; display-only injection that must not perturb the types/tokens/TTR statistics; guards mirror +c2.

  • +o3 combine-speakers + +o2 deferral (2026-06-03): exposed the header-less-output bug in strip_clan_header; motivated the first-class Deferred terminal status and its exclusion from the metric denominator.

  • +t%X dependent-tier scoping (2026-06-03): first shared tier-token primitive (framework::dependent_tier_tokens); the “expensive but amortizing” kind of row (KWAL/COMBO reuse it). Three lessons. (1) A flag with a tier argument is still a count-source axis: use_mor: bool became a three-variant CountSource enum (MainTier/MorStructural/DependentTierTokens(TierKind)) so the nonsensical “structural-mor AND tier-gra” state is unrepresentable; the --mor-vs---tier guard lives at dispatch (§7). (2) Tokenization and the default-exclude list are different layers (§9): the bare . is dropped in the pure tokenizer, but the %gra PUNCT relations are dropped by CLAN’s FREQ-seeded exclude list (gra_initwords) layered on top in the command, keeping the primitive faithful for rely/keymap/chains. The golden RED that taught this was +t%gra over-counting N|M|PUNCT by 2, localized to a chatter bug (incomplete exclusion), not a CLAN divergence, by finding cutt.cpp:8840. (3) The CLAN slot’s faithful partner is not always chatter’s existing flag: +t%mor whitespace-counts the raw line (a clitic = one token), so it maps to --tier mor, NOT chatter’s structural --mor; the prior +t%mor↔--mor goldens were incidentally byte-equal only because the fixture is clitic-free. Also: the “%mor line forms” TTR advisory is a %mor-conditional presentation row (isMorUsed, freq.cpp:1536), proven in both directions by the gra/mor golden pair.

  • -t%X dependent-tier EXCLUSION (2026-06-03): the row that proves the manual-first/probe-first discipline pays off. The prior handoff called -t%X a “small no-op” (a dependent tier isn’t counted by default, so excluding it seemed free). The binary said otherwise: +t and -t are the two halves of CLAN’s tier-selection set, and they have OPPOSITE defaults: +t%X = “ONLY %X” (restrict), -t%X = “main tier + ALL dependent tiers EXCEPT %X” (a brand-new combined mode). The lesson: never assume a flag is a no-op; probe the binary. Implementation-wise the combined mode fell out of method extraction: pulling the MainTier and DependentTierTokens match arms into count_main_tier/count_dependent_tier methods made the new arm a literal composition (count_main_tier(...) + per-present-tier count_dependent_tier), no new counting logic. Two more transferable points: (1) the advisory tracks the explicit include, not the data: -t%X keeps the “%mor line forms” advisory even when it sweeps %mor in, because CLAN sets isMorUsed only for +t%mor; so is_mor_based stays false for the exclude mode. (2) The +t/-t combination (an include and an exclude together) is a separate tier-selection state machine, deferred; the dispatch guard errors on any --mor/--tier/--exclude-tier mix rather than half-implement it.

  • +x utterance-length filter (2026-06-03): the first reusable utterance-gate primitive added to the shared FilterConfig (UtteranceLengthFilter), alongside speaker/range/role/id; +x is a common CLAN limiting option, so the gate (not the FREQ command) is its home, and other commands’ +x reuse it. Four transferable points. (1) A multi-form flag can be landed honestly as Partial. +x C N U spans three units (w/c/m) plus a +xS content form; only the word unit is clean, so the row is Partial: implemented w, and the deferred units/forms ERROR at parse (not silent no-op). (2) A Partial row should not inflate the metric. The render golden (freq_x_wordlen_eng) deliberately carries covers: &[], so it is a regression proof without marking +x “proven”, the honest counterpart of +c4’s “Done-with-tiny-edge + cover”. (3) Reuse the project’s word identity. The gate counts via chatter’s AST countable_words rather than re-deriving CLAN’s char-level skip rules; the field-guide §9 AST-vs-char note governs any edge-token divergence. (4) The rewriter is subcommand-overloaded for a single letter. +x means the length filter for FREQ but a bare +xN for MAXWD, so the rewriter arm is if subcommand == Freq, an unconditional arm shadowed MAXWD’s (caught by unreachable_patterns).

  • +x char unit c (2026-06-03): landed as the second +x unit, byte-parity golden freq_x_charlen_eng (+x>20c drops *SPE’s 17-char utterance, 15→12 tokens). Two transferable points. (1) Generalize the threshold the moment a second unit lands. The word-only WordCountThreshold became unit-agnostic LengthThreshold and the filter gained a typed CountUnit axis (Word/Char), exactly the flag-prefix-is-not-a-scalar rule the original +x entry anticipated (“needs a unit-generic sibling or rename”). Do the rename when the second case arrives, not later. (2) Reuse an existing measurement primitive. The char count is cleaned_text().chars().count() summed over countable_words (the same primitive WDSIZE/MAXWD already use), so the char unit is byte-clean on the fixture with zero new char-tokenization logic.

  • +x morpheme unit m: the anomaly RESOLVED as a CLAN doubling bug (2026-06-03). The prior session deferred m because it “live-probed anomalously (more tokens than bare)”. Probe-first plus manual-first localized it. CLAN +x>0m (which should pass every utterance, so should equal the bare output) instead emits BOTH the main-tier words AND the %mor-tier tokens: *SPE 15->30, with Triangle and noun|triangle both counted. The morpheme-count walk (cutt.cpp:16409-16507, rightUttLen CntFUttLen==2) scans the %mor tier and leaks %mor inclusion into FREQ’s word harvest. Manual 6405 defines +x as “include only utterances which are C than N items”: a pure utterance filter, never a change to what FREQ counts. So this is a CLAN-binary bug (localization category b), not a chatter gap and not a data artifact: chatter implements m as a pure morpheme-count filter (no doubling), marked DivergesFromClan (a deliberate documented divergence). The transferable lesson: a flagged “anomaly” is a localization task, not a permanent unknown: run the limiting probe (>0, which should be a no-op filter) and the deviation from no-op exposes the leak; then the manual says whether the binary or chatter is wrong. The word and char units share +x’s filter slot and are unaffected; only the morpheme unit triggers the leak.

  • +x…m IMPLEMENTED + the parity-vs-correctness pivot (2026-06-04): the morpheme unit landed, and getting it right forced the first place chatter deliberately OUT-CORRECTS CLAN on UD data rather than reproducing it. Five transferable points. (1) “Reuse the existing counter” can hide that the existing counter is also wrong. The plan was to reuse MLU’s morpheme counter as “the correct count”; verifying it first showed chatter’s MLU had been built to MATCH CLAN’s countMorphs and so inherited the exact same gap (UD present participle -Ger was never traced, only the legacy -PRESP), undercounting “going” as 1 not 2. Lesson: verify the reused primitive’s correctness against the manual, never assume it because it passes its own (CLAN-matching) goldens. (2) When CLAN is incomplete on UD, “match CLAN” means shipping a bug. §7.21 traces “Present Participle”; CLAN’s countMorphs migrated -PL→-Plur and -PAST→-Past but never added -Ger, so the binary under-counts. chatter adds -Ger (the like-for-like UD twin of the already-traced -PRESP), computing the CORRECT count and flipping MLU MatchesClan→DivergesFromClan. The 9-character edit is the whole pivot: from “byte-match CLAN” to “be correct, document the gap.” (3) One shared primitive, not per-command copies. framework::count_traced_morphemes_in_utterance (extracted from MLU) is the single home both MLU and FREQ +x…m consume, so they cannot drift, the exact cross-command consistency CLAN lacks (its MLU countMorphs and FREQ +x…m ismorfchar disagree wildly, 4 vs 12 on the same UD line). (4) Implement the verified, escalate the inferred. The corpus uses -Ger(28) but also -Gen possessive(44), -Part(96), -Prog(4), none traced. Only -Ger is the unambiguous like-for-like UD completion of a concept the list already traces; the §7.21 mapping of the others (is -Part a past participle, which §7.21 does NOT list? is -Gen always possessive? multilingual?) is real judgment, so it was DEFERRED to a separate grounded audit, not inferred into code. (5) A “menu of morpheme modes” can dissolve into one correct notion. The three competing counts (CLAN 12, mor_item 10, MLU ~5) were not three valid choices but one manual-grounded notion (§7.21 traced) plus CLAN’s bug plus a feature-count artifact (mor_item_morpheme_count, 1+features, used by SUGAR/EVAL, kept distinct). So no force-explicit-mode framework was built; +x…m just computes the one correct count. The morpheme-anomaly investigation (the doubling, above) and this one are recorded in the project’s investigation notes.

  • +xxxx/+xyyy/+xwww marker restore + the byte-stride CLAN bug (2026-06-04): the +xS content-include form re-includes a normally-stripped unintelligible marker (xxx/yyy/www) into the +x length count. Four transferable points. (1) A “content form” can split into a high-value observable and a near-no-op; land the observable, defer the rest faithfully. +xS is two mechanisms in CLAN: the marker restore (restoreXXX, genuinely changes the count) and a general +xWORD include via the wdUttLen list, which is a near-no-op (excludeUttLen already default-counts unmatched words, so an inc='i' tag only bites as an exception to an overlapping exclude pattern). Ship the restore; keep +xWORD/+x@F fail-closed; row stays Partial. (2) When a flag ADDS a category to an existing count, parameterize the validated walker, do not write a second walk. Restored markers must obey the same group-recursion and retrace/replacement rules as countable words, or they drift from the base +x count chatter already byte-matches against CLAN. The fix was to thread a keep: &dyn Fn(&Word) -> bool predicate through the existing collect_countable recursion (countable_words passes is_countable_word; the new words_for_utterance_length passes “countable OR a restored marker”), reusing one tree-walk for both. (3) CLAN’s text-buffer scans carry position-dependent bugs; when a divergence looks data-dependent, probe by BYTE OFFSET. correctForXXXYYYWWW (cutt.cpp:16260-16311) advances i += 2 once per marker check (xxx/yyy/www) plus the for’s i++ = a stride of 7, so it only restores xxx at byte offsets ≡ 0 (mod 7). The tell that this was position, not structure: a BARE xxx at end-of-line (the dog ran xxx) was NOT restored while a bare xxx at start (xxx fell off him) WAS, ruling out “groups exclude restore”. A controlled 7-utterance probe varying only the marker’s offset (a xxx end … abcdefg xxx end) then isolated it: only offset 7 restored. Read the source to find the stride, the probe to confirm it. (4) An “off-by-i+=2” C bug is a clear bucket-2 divergence, no escalation needed. The manual (6405) states the restore unconditionally; a byte-offset dependency has no possible intended meaning, so chatter restores correctly (AST-based, position-independent) and documents CLAN-DIV-005, the same do-the-correct-thing posture as the +x…m defects above. (5) The sibling -x@FILE/+x@FILE file forms split the same way the literal forms did, and show bucket-2 (fix) vs bucket-3 (escalate) side by side. -x@FILE (exclude from file) is unambiguous, mirrors -s@F’s @FILE rewrite idiom (rest.starts_with('@') → --…-file), and feeds the same exclude_from_count list, so it just lands. The +xWORD/+x@FILE INCLUDE form is the opposite: its manual usage text (“count only this word”, cutt.cpp:9886) flatly contradicts the binary (excludeUttLen default-counts unmatched words, so the include tag is a near-no-op with an arbitrary descending-alphabetical precedence), so its correct semantic is genuinely unknown. That is a bucket-3 escalation (maintainer call), not a thing to reproduce: keep it fail-closed and put it in the report, rather than encode an arbitrary artifact. The byte-stride bug and the include contradiction, found one flag apart, are the cleanest contrast in the guide between “the binary is wrong, fix it” and “the manual and binary disagree, ask”.

  • +rN family audit, an audit can indict the DEFAULT, not just a flag (2026-06-04): auditing +r (word-form treatment: parentheses, prosodic symbols, [: text] replacement, retracings, %mor-combine; parsed cutt.cpp:9530-9583) surfaced that chatter’s default FREQ output diverges from CLAN’s, independent of any flag. Two transferable points. (1) A “cheap tail” label from a handoff is a hypothesis, not a finding, re-audit it. +r was queued as cheap; the source+manual+probe pass showed it is a word-normalization parity cluster (each sub-flag tunes how a word is cleaned for counting), with a default-parity bug underneath. Always run the audit before trusting the effort estimate. (2) A key/display split can diverge from CLAN and from itself. CLAN applies its +r1 default (remove omitted-material parens but keep the letters: bein(g) → being) once, so its grouping key and its display agree. chatter splits the two: the FREQ key is cleaned_text() (already being, +r1-correct) but the display is clan_display_form → raw_text() (bein(g), i.e. +r2). So the same word is grouped as being yet shown as bein(g), diverging from CLAN and internally inconsistent. When a command has separate normalize-for-grouping and normalize-for-display paths, audit BOTH against the binary; a flag that controls word cleaning (+r1/+r2/ +r3) must drive both consistently. This was also the root cause of the bein(g)/being contamination that blocked a clean +x golden on 1082.cha.

  • +r1/+r2/+r3 IMPLEMENTED, fixing a default and scoping the blast radius to zero (2026-06-04): the parenthesis sub-family landed as a typed framework::ParenthesisMode (RemoveParens default / KeepParens / RemoveMaterial) threaded through the full five seams plus FreqOptions -> builder -> FreqConfig. Three transferable points. (1) One axis drives both the key and the display. The fix routed BOTH parans_normalized_key (group) and parans_display (show) through the same mode, so they can never disagree again; CLAN gets this for free because it applies Parans once before counting, chatter has to wire the single mode into both of its split paths. (2) Render AST-first by parameterizing only the differing element, not by string-hacking the surface. The modes differ ONLY in how a WordContent::Shortening renders; the renderer walks Word::content and reuses each other element’s WriteChat verbatim, special-casing just the shortening (inner letters / (inner) / nothing). No stripping of (/) from raw_text() (which the no-string-hacking rule bans and which would mis-fire on any literal paren). (3) A default-changing fix can still be zero-blast-radius if you gate it on the affected feature. RemoveParens reproduces cleaned_text()/clan_display_form byte-for-byte, and the new path is taken ONLY for words that actually contain a shortening (has_shortening), so every other word, and thus every existing freq golden, is untouched, verified by the full golden suite staying green through a default-output change. The honest worst-case estimate (re-seed every golden with (…) words) turned out to be zero goldens because the affected token only occurred in a subprocess fixture.

  • A rewriter-MAPPING test is not a behavior test: +r6 was “Done” yet a no-op (2026-06-04). Auditing the +r5 neighbor surfaced that --include-retracings (+r6) is accepted, mapped, and covered by a test, yet changes nothing: the only test (combined_flags) asserts +r6 -> --include-retracings (the rewrite), never that retracings get counted. Under the hood FREQ counts via framework::countable_words (the non-retrace walker), FreqConfig has no include_retracings field, and countable_words_with_retracings is dead code with zero callers crate-wide. So the flag is wired end-to-end at the argv layer and inert at the semantic layer. Two transferable rules. (1) “Done” requires a golden (or subprocess assert) that exercises the flag’s OUTPUT against the binary, not just that the flag parses or rewrites. A row whose only evidence is a rewrite-mapping test is Wired, not Done; re-probe every such row against the binary before trusting it. (2) When a flag’s whole job is to change counts, prove it by a token-count delta against CLAN on a fixture that actually contains the construct. The one-line probe freq vs freq +flag | grep 'Total number of items' on retrace.cha (CLAN 13->18, chatter 13->13) is what exposed it; the same probe belongs in every count-affecting row’s audit. This is why the FREQ parity metric counts only rows with a behavior golden, and why +r6 was downgraded from Done to a no-op bug to FIX.

  • +r6 FIXED, and the fix was to SEPARATE two axes CLAN keeps separate (2026-06-04). Wiring --include-retracings into FREQ (a FreqConfig field + counting via countable_words_with_retracings) made +r6 count retracings, but it OVER-counted: chatter emitted male/tika@u/lɛɾɪ@u, the ORIGINALS of [: text] replacements, which CLAN never counts. Root cause: the shared word-walker’s ReplacedWord arm treated include_retracings as “count both the original AND the replacement”, conflating two independent CLAN axes, +r5 ([: text] replacement: count replacement vs original) and +r6 (retracings: include the retraced material or not). The correct model: a [: text] replacement ALWAYS counts the replacement; +r6 governs only the Retrace arm; a retraced replaced word (tika@u [: kitty] [//] kitty) is reached through the Retrace recursion and contributes its replacement (kitty), so the two compose without a “both” branch. Removing that branch (dead code until +r6 was wired) took chatter from 21/17 tokens to CLAN’s exact 18/16 on retrace.cha. Two transferable points. (1) When a binary has N independent flags over the same data, model N independent axes; a single “do more under this flag” branch that piggybacks one axis onto another is the conflation bug. (2) Verify a count-fix by DIFFING the full word list against the binary, not just the token total, the total can match by luck while individual words are wrong; here the male/tika@u over-count and a compensating miss elsewhere is exactly what a total-only check would hide. The retraced-replacement semantics ([: text] inside [//]) is the subtle case the retrace.cha fixture exists to pin; keep using it for +r5 next.

  • +r5 was cheap because +r6 paid the untangling cost first (2026-06-04). Once the walker’s ReplacedWord handling was its own axis (the +r6 fix), adding +r5 (count the [: text] original vs the replacement) was a clean enum: a ReplacementChoice (Replacement default / Original), bundled with include_retracings into one RetraceReplaceMode so the walker carries a single mode rather than parallel flags, plus a shared push_replaced_word helper both walkers call so the two cannot drift. On retrace.cha, male [: female] [/] male [: female] flips female->male, a clean swap that byte-matches CLAN (golden freq_r5_replace). Two transferable points. (1) Sequencing matters: when two flags share a code path and one is buggy, fix the bug FIRST (it forces the axes apart), then the sibling flag is additive. Had +r5 gone first it would have had to invent the same separation under more time pressure. (2) Bundle co-located axes into one typed mode at the seam (RetraceReplaceMode) rather than threading a growing list of bools/enums through every recursive call, the recursion stays one-argument and the relationship between the axes is documented in the type.

  • +r4/+r7 audit, the key/display split is a RECURRING bug, and “no-op for this command” is a real status (2026-06-04). Auditing the prosodic sub-flags surfaced two things. (1) The same key-vs-display divergence found for parens recurs for prosodic symbols. CLAN’s default strips within-word prosodic (ca:t->cat, do^g->dog, hm:->hm); chatter’s grouping key (cleaned_text(), which excludes prosodic elements) is already correct, but the display (raw_text-based) KEEPS them, so the default output diverges, the root of the pre-existing hm:->hm 1082.cha diff. Two instances (parens, prosody) of one root cause (display = surface, key = cleaned) means the display path wants a single element-selective AST renderer, not per-flag patches; the fix is Text + Shortening(per parens) + CompoundMarker by default with per-symbol opt-ins (+r7). Confirmed zero golden blast radius (no FREQ golden fixture has within-word prosodic; the passing byte-identical goldens prove it), but it needs per-WordContent-element CLAN-strip probing (Lengthening and SyllablePause confirmed stripped; Stress / CA / underline not yet) so the renderer matches CLAN element by element. (2) A flag can be a genuine no-op for one command and meaningful for others, that IS its status, document it, don’t force-wire it. +r4 (make #/: significant + clitic flags) is probe-confirmed identical to default for FREQ counting (its effect is +s-search and clitic-counting); recording it as “FREQ no-op” is the honest per-command audit result, not a gap to paper over with an accept-and-ignore.

  • Prosodic default-strip FIXED, and the key/display renderer is now the single element-selective seam predicted (2026-06-04). The default fix landed: chatter used to keep within-word prosodic in the display (hm:), CLAN strips it (hm); parans_display now renders the display AST-first as Text + Shortening(per parens) + CompoundMarker, excluding every prosodic/CA/overlap/underline/clitic element. Three transferable points. (1) The third instance of the key/display split (parens, then prosody) was resolved by GENERALIZING the parens renderer, not adding a parallel one, exactly as the prior audit note predicted: the display path wanted one element-selective AST renderer keyed on WordContent variant, and the parens work had already built the scaffold. When the same root cause bites a third time, stop patching and unify. (2) An exhaustive WordContent match (no _ =>) is the safety rail: listing every element variant explicitly (Text/Shortening/Compound kept; the eight prosodic/CA/overlap variants dropped) means a future new element type is a compile error here, not a silent keep-or-drop guess. (3) Scope a default-changing display fix with a cheap predicate (has_prosodic/has_shortening) so the common case stays on the byte-identical old path, the AST renderer runs only for words that actually carry a shortening or prosodic marker, so the full golden suite stayed green through a default-output change, the same zero-blast-radius discipline as the parens fix. Probing established CLAN strips ALL within-word prosodic by default (lengthening/syllable-pause/stress/CA all confirmed), so the strip is unconditional; the +r7 keep-SUBSET (only :/^/~, with buggy CLAN stress/CA artifacts) is the remaining, fiddlier toggle.

  • +r7 DONE, and a prior session’s “byte-identical” claim hid a real divergence (2026-06-04). The keep-toggle landed as a typed ProsodyMode (Strip/Keep) driving the same render_word_element seam (the fourth reuse of the one element-selective renderer, never a parallel one). Five transferable points. (1) Re-run the byte diff yourself; never trust a handoff’s “parity confirmed.” The pre-compaction note said +r7 was byte-identical to CLAN except a known ah@u diff. Re-diffing from the first Speaker: line (the header differs by design: CLAN says “From pipe input”, chatter echoes the command line) surfaced 12+3 extra CLAN tokens that the prior pass had missed. A parity claim is only as good as the last diff you personally ran. (2) A flag’s documented scope can be NARROWER than the binary’s actual effect, and the gap is a divergence, not a spec to reproduce. The manual scopes +r7 to within-word /~^: (line 12418); CLAN’s binary additionally retains the whole CA / satellite-delimiter family (‡ „ ≠ ↫). The manual is the authority on intent; when the binary exceeds it, diverge. (3) Invalid UTF-8 output is an automatic divergence trigger. CLAN’s 8-bit pipeline drops the 0xE2 lead byte of ‡/„ and emits byte-garbage (0x80 0xA1) as a “word type”; chatter operates on the typed AST and physically cannot, so this is the cleanest CLAN-bug-chatter-fixes case, independent of any scope debate. The guard test asserts on raw stdout bytes, not a lossy string, so it actually catches the corruption. (4) You need not pin the exact buggy C line to diverge honestly. I traced the +r7 parser (cutt.cpp:9569-9576), the cleanup gate (:7258, HandleSlash vs HandleSpCAs), and the ‡ classification (NOTCA_VOCATIVE), but could not fully explain why VOCATIVE survives when the parser explicitly clears only CROSSED_EQUAL/LEFT_ARROW. The honest move: prove the divergence empirically, cite the manual scope plus the source structures you DID verify, and do NOT fabricate the micro-mechanism (no-speculation rule). The decision stood on two independently-sufficient grounds (out-of-scope + invalid UTF-8). (5) Minimal CLAN-only probes bisect a divergence in seconds. Four one-utterance scratch files (one per CA class) x {default, +r7, +r4} localized “the whole CA-delimiter family flips under +r7, not +r4” far faster than more source reading; that 2-to-3-types signal is the cheapest possible discriminator. Documented as CLAN-DIV-006.

  • +d display-mode cluster, an audit that became a systemic fail-closed fix (2026-06-04). Picking up the +d cluster (the largest remaining FREQ block) showed the handoff’s “rewriter-only +d flags silently no-op” framing was doubly wrong; the probe (never trust the doc) found freq +d8 file.cha exited 0 with default output plus a stderr Warning: "+d8" is not a file ..., i.e. the flag was swallowed as a bogus positional file. This was systemic, not +d-specific (+QQQ and any unconsumed +-token on any command behaved the same; see the harness-gotcha bullet for the clap mechanism). Three transferable points. (1) Fail-closed by construction beats fail-closed by convention. The hole existed because skipped_paths() was an accessor consumers were trusted to warn on; adding another trust-me accessor would invite the same regression, so DiscoveredChatFiles::into_files() was made Result<_, UnrecognizedClanFlagArgs>, the compiler now forces all four consumers to handle the flag case. (2) Fail-closed vindicates the manual-first/source-first discipline. Bare +d LOOKS like “= no-flag default” per the manual, but CLAN source sets onlydata = atoi("")+1 = 1, identical to +d0 (freq.cpp:838 -> cutt.cpp:9402); erroring on +d until a per-row source analysis (and a manual-vs-source reconciliation) is done is CORRECT, implementing it from the manual alone would have shipped a subtly-wrong default. (3) An unimplemented APPLICABLE flag errors, just like an inapplicable one, until it is properly built. The implementable rows (+d20 one-per-row spreadsheet, the +d<N/+d>=N/… percent filters) and the PI-gated rows (+d0/+d6/+d7/+d8) all now error fail-closed pending their own TDD cycle, the honest state, not a silent default. The status flip was Rewriter-only -> Missing for every not-yet-built +d form.

  • +d20 one-per-row spreadsheet, the first +d spreadsheet row that MATCHES CLAN (2026-06-04). Landed as a third FreqSpreadsheetMode::PerSpeakerWord alongside +d2 (PerWord) / +d3 (TypesTokens). Four transferable points. (1) The percent filters and +d20 are a spreadsheet sub-cluster, not text rows. Both run under CLAN’s onlydata 3/4 Excel path; what looks like a “display mode” in the manual is a file-output layout in the source. Audit the output MODE (text vs spreadsheet file) before estimating a +d row. (2) A flat layout is its own builder, not a column toggle. +d2/+d3 differ by which columns appear; +d20 is a wholly different shape (File | Code | Word | Count, one row per (file, speaker, word), no @ID/Types/TTR/caveat), so to_spreadsheet early-returns a separate to_one_per_row_workbook rather than growing the wide builder’s match. (3) +d20 MATCHES CLAN where +d2/+d3 diverge, because the divergence was never about the data. +d2/+d3 are DivergesFromClan solely for the %%mor printf leak in their TTR-caveat rows (CLAN-DIV-004); +d20 has no caveat rows, so its cells are byte-identical to CLAN’s (live diff of <Data> cells) and it is MatchesClan. A command’s divergence is per-output-shape, not per-command. (4) Seed a spreadsheet golden surgically. Spreadsheet goldens hold chatter’s own deterministic XML (CLAN parity proven separately by a live cell diff), and seed_clan_golden short-circuits before any CLAN run for them, so a single golden can be seeded by writing chatter’s write_xml() output directly, no full regen-clan-goldens that might perturb other goldens. The CLAN binary lives at OSX-CLAN/src/unix/bin/ (point CLAN_BIN_DIR there); its source synced the same day it was built, so source citations and binary behavior agree.

  • +dCN percent-of-speakers filter, the last implementable +d row (2026-06-04). A comparator (</<=/=/>=/>) plus a percentage: keep words used by that fraction of speaker-rows, then report each speaker’s Types/Token/TTR over only that subset. Modeled as a payload mode FreqSpreadsheetMode::PercentOfSpeakers(SpeakerPercentFilter), rewritten from +d<=50 -> --speaker-percentage <=50. Six transferable points. (1) The audit’s predicted output shape was wrong; the binary is the oracle, even for a row your own audit wrote. The prior audit (and the row’s own text) said the percent filter “builds on the +d2 per-word sheet”; the live binary showed a +d3-shaped SUMMARY (no per-word columns), a DIFFERENT fourth-column header (Speaker, not +d2/+d3’s Code, freq.cpp:2874), and a DIFFERENT filename (words.frq.xls, not stat.frq*.xls). The tell was in the source the whole time: in statfreq_print_percent_row (freq.cpp:2806-2828) every word-name and per-word-count cell is gated on onlydata == 3, so onlydata == 4 (the percent path) emits no word cells, only the accumulated diff/total (Types/Token). Read the gated branches, then PROBE before trusting any one-line shape claim. (2) A manual metavariable is not a literal. +dCN’s C is the comparator placeholder (CLAN.html “+dCN” lists <, <=, =, =>, >); the source has no case 'C', only the </=/> parse at freq.cpp:841-861. Resolve such notation against the source, never the surface string. (3) A percent/spreadsheet sub-cluster row inherits its sibling’s parity AND its sibling’s divergence. The filter reuses the verified +d2/+d3 per-(file x speaker) aggregation wholesale; the only NEW surface is a cross-row distinct-speaker count (how many rows used each word) plus a per-row recomputation over the kept subset. Because the aggregation was reused, every data cell came out byte-identical to CLAN on the first run, and the row landed DivergesFromClan under the SAME CLAN-DIV-004 %%mor caveat as +d2/+d3, no new divergence. This completes the +d20 insight (“divergence is per-output-shape”): same machinery -> same divergence. (4) Error PRECEDENCE is part of parity, not just which errors exist. CLAN catches the percent-+d5 combination at flag-parse time (freq.cpp:867/890), BEFORE its +s-content validation; chatter’s +d5-requires-+s guard ran first, so the combination guard had to move ABOVE the +c2/+d5 content guards to emit “+d<=50 can’t be used with +d5” rather than the unrelated “+d5 needs +s”. When two guards can both fire, match CLAN’s ORDER. (5) A payload variant on a shared mode enum is fail-closed by construction. Adding PercentOfSpeakers(filter) to FreqSpreadsheetMode made every match mode (renderer, freq_spreadsheet_filename, the service) fail to compile until it handled the new mode, so no consumer could silently fall through to a wrong layout, the same fallible-by-type discipline as the fail-closed boundary above, applied to an output enum. (6) The golden-parity metric matches a golden cover against the audit row’s FIRST CELL (backticks stripped), so that cell must be a single canonical token. A compound first cell (+dCN (+d<N/...)) made the +dCN cover dangle and pushed the row into “claimed Done, no golden”; keeping the first cell exactly `+dCN` (comparator spellings moved to the Meaning column) restored the match. The metric’s denominator is row COUNT, so this does not change 47; the row moved from the (uncounted) Missing bucket to the Diverged column (3 -> 4).

  • +pS word delimiters, a tokenization-change row that MATCHES CLAN (2026-06-04). +pS adds the characters of S to CLAN’s word-delimiter set and re-tokenizes, so a counted word is split at them (+p_ breaks choo_choo into two choo). Five transferable points. (1) The “general flags FREQ inherits” table conflates cutt.cpp::mainusage generics with FREQ’s actual case overrides; verify each against FREQ’s own getflag. The audit listed +oS/-oS as “include/exclude extra output tier” and +y as “include non-tier utterances”, but FREQ OWNS case 'o' (it is the sort flag +o/+o0/+o1/+o2/+o3 and its else REJECTS +oTIER with “Invalid argument”, freq.cpp:815-836) and +y is y_option (raw-text line-vs-utterance granularity, cutt.cpp:9848) that only fires when !chatmode, a no-op for CHAT input. Only +pS was a real, implementable feature; the other two are an error-row and a CHAT no-op. Read the command’s own switch, not the shared usage text. (2) A flag enabled for many commands belongs in framework, not the command. +pS is gated on P_OPTION, which ALL_OPTIONS grants to FREQ and ~a dozen others, so the delimiter primitive is a reusable typed framework::WordDelimiters (whitespace dropped on construction, matching CLAN’s !isSpace skip), ready for the next command rather than a FREQ-local field. (3) Gate the new behaviour on is_empty() so the default path stays byte-identical. The split re-keys each segment from the rendered display string (NormalizedWord::from_text_cased), which is NOT the same as the default parans_normalized_key path (that strips compound + etc.); routing ALL words through the split keyer would have moved existing goldens. Branching on “delimiters configured?” keeps the no-+p path untouched (zero golden blast radius) and confines the new keying to the +p case. (4) Split the RENDERED form, and a word-form marker rides its segment for free. CLAN re-tokenizes the cleaned text, so the @o on chup_chup_chup_chup@o stays on the final chup@o because it is textually last; splitting chatter’s already-rendered display form (chup_chup_chup_chup@o) on _ reproduces this without modelling the marker specially. Applying the split AFTER the +r treatment matches CLAN’s order for the common case. (5) Scope the combination honestly. The +s/+c per-word filters still gate on the whole pre-split word, so +p combined with +s/+c (and dependent-tier +t%X splitting) is a documented deferral, not silently half-done; the base +pS is byte-parity MatchesClan (full 79-line *MOT output diffed against CLAN).

  • FREQ depth-completion: the tail is reclassification + a deferral taxonomy, not more implementation (2026-06-04). Driving FREQ to “done” did NOT mean implementing every remaining flag; past a point the remaining rows are all decisions or inapplicabilities, and the work is to classify them honestly. Four transferable points for completing any CLAN command. (1) “Inapplicable to a CHAT-only tool” is a Done state, reached by rejection, not implementation. +y (sets chatmode = 0, raw-text mode) and the non-sort +o forms (+o2 “non-CHAT”, +oS which FREQ rejects outright) are not features to build; CLAN itself either errors or empties its output on a CHAT file. The +w precedent generalizes: a flag whose CLAN machinery produces nothing useful for typed CHAT is rejected, and that rejection is the correct, pinned, Done behaviour. (2) An audit row’s one-line description can mis-assign the flag’s owner. The “general flags FREQ inherits” table (copied from cutt.cpp::mainusage) listed +oS as “extra output tier” and +y as “include non-tier utterances”; reading FREQ’s OWN getflag showed +o is the sort flag (rejects +oTIER) and +y is raw-text mode. Verify every inherited-flag row against the command’s own case, not the shared usage text. (3) A finished command has a deferral TAXONOMY, not a “Missing” pile. Every non-Done FREQ row resolves into exactly one scope-gate category: %mor/cross-tier (needs the shared MOR-analysis subsystem: +d6/+d7/+d8/+r8/+r50/+c5), non-CHAT raw-text mode (+y/+o2), CA-construct-needs-parser (+c6, a ↫ repeat-segment span type), manual-vs-binary contradiction escalated to the maintainer (+xWORD/+x@FILE, +a), or output-routing infra (+f). “Missing without a reason” must reach zero; each deferral carries a source file:line. (4) The completion deliverable is the maintainer report, not the code. The point of depth-first-one-command is to produce a grounded porting estimate; FREQ’s output is the maintainer porting report, which separates “decisions the maintainers owe” from “labor that reuses existing primitives”. The key finding: per-command cost is front-loaded into shared machinery, and the dominant remaining cost is verification (running CLAN vs chatter and reconciling divergences), not typing.

  • MLU as the second command: the discount is real and explained (2026-06-05). Driving MLU’s remaining rows validated the “second command is cheaper” claim and sharpened it. Three transferable points for the next command. (1) A command’s rows sort into shared / nearly-free / full-price, and only the last costs. MLU was mostly already Done because it rides the shared filters / file-loader / morpheme counter FREQ built; several remaining rows (+pS, +r1/+r2/+r3/+r4/+r5/+r7) were faithful no-ops that the FREQ domain lesson (%mor-based counting ignores main-tier word-FORM flags) let me classify on sight, with a one-line probe and a vec![] rewriter arm; only the command-specific semantics (+o3 combine, and the deferred clause-markers / Excel) cost full price. The effort multiplier is not one number, it is proportional to a command’s command-specific surface. (2) A no-op is a real parity row: verify it, do not assume it. +pS/+rN are ACCEPTED by MLU (P_OPTION/R_OPTION in option_flags[MLU]) and must not error (the +w-reject rule is for flags CLAN itself rejects/empties; these CLAN accepts and ignores). Confirm “no effect” by running the binary in BOTH modes (morpheme and -bw) on a discriminating fixture, then consume the flag; pin it with a body-level byte-identical test (strip the command-echo banner line, which legitimately differs when a flag is passed, for CLAN too). (3) Reuse the flag NAME and rewriter shape, re-implement the command logic. MLU +o3 reused FREQ’s --combine-speakers flag + (b'+', b'o') ... rest == "3" rewriter shape, but the combine itself (pool per-speaker utterance_lengths, render the *COMBINED* label) was MLU-specific. Extract the per-speaker aggregate (aggregate_mlu(speaker, lengths)) first, then the combine branch is “pool, call the aggregate once” with no duplicated stats math. (4) The statistic itself is a shared primitive, not just the command shape. MLU and MLT both report CLAN’s population standard deviation (/ n, “NA” when n <= 1) over a slice of per-utterance counts; they had byte-identical inlined loops. Extracting framework::population_sd(&[u64]) -> f64 (in framework/stats.rs) collapses both to one call and is the home for the next aggregate’s SD (WDLEN, MAXWD, …). The lesson generalizes the FREQ MATTR finding: when two commands compute the same number, the number belongs in the framework, keyed off the count slice, not re-derived per command. The full effort assessment is recorded internally.

  • MLU default-exclusions are parity rows, and the count tier != the exclusion tier (2026-06-05): MLU’s biggest parity gaps were not flags at all but DEFAULT behavior. Three base-command bugs hid behind a passing bare golden on a clean fixture: (1) xxx/yyy/www exclude the WHOLE utterance they appear in (manual §7.21 pt2), not just utterances that are entirely unintelligible; (2) the [+ mlue] postcode excludes its utterance (mlu.cpp:503); both were counted by chatter. The transferable lessons: (a) A passing bare golden on a tidy fixture does not mean the base command is correct, run it against a corpus that actually exercises the construct (the xxx bug only shows on it xxx xxx, a mixed utterance; the clean xxx . case chatter already handled via “no countable words”). (b) The tier that DRIVES exclusion can differ from the tier that drives the count. MLU counts morphemes off %mor but excludes off the MAIN tier (and off postcodes); it xxx xxx has %mor pron|it yet is dropped because the main line carries xxx. Localize each parity dimension to its own tier. (c) When real data is the only source of a rare construct ([+ mlue] exists in one Japanese corpus with @k confounds), trim a fixture that isolates the dimension under test: in the DEFAULT case the tagged utterance is dropped, so its messy internal count never reaches the golden, the confound is sidestepped. Verify the trimmed fixture passes the reference-corpus roundtrip/validate gates before adding it.

  • A re-include flag toggles a default exclusion AND repaints the header; model the toggle as a domain-type set, not bools (2026-06-05): +sxxx/+syyy don’t add a filter, they SUBTRACT from the default xxx/yyy/www exclusion and switch CLAN to a different two-line header (mlu.cpp:246-253). Modeled as re_included: Vec<UntranscribedStatus> (the domain enum) rather than include_xxx: bool, include_yyy: bool, so the exclusion predicate is a single !re_included.contains(status) and the header picks its branch off the same set, no boolean-blindness. www is simply never placed in the set.

  • Manual vs binary: the binary is the chatter-clan oracle; reproduce, then escalate the conflict, do not diverge solo (2026-06-05): +syyy is the textbook case. The binary accepts it and re-includes yyy, but the manual says yyy “cannot be included,” and the binary itself has no yyy-only header branch (so +syyy alone prints the default header while changing the count, a self-inconsistency). chatter reproduces the binary BYTE-for-byte (including the quirk) because the binary is the parity target for chatter-clan output, and records the manual conflict in the command’s “Documented CLAN-bug divergences” table for PI adjudication. Reproducing-plus-documenting beats a solo decision to “fix” what the manual and binary disagree on.

  • A reject only fails closed if no chatter short-flag shadows the CLAN flag (2026-06-05): returning None from the rewriter (the normal “unrecognized CLAN flag” path) did NOT fail closed for -sxxx/-syyy/-swww, because chatter’s --speaker owns the -s short flag, so clap silently re-read -sxxx as --speaker xxx (no such speaker -> empty output, exit 0). The fix: map the reject forms to a self-documenting NON-EXISTENT long flag (--xxx-is-excluded-by-default-and-cannot-be-excluded) so clap fails closed with a message that explains itself. General rule: before relying on None to reject a -X CLAN flag, check whether any chatter short flag would intercept it first. (The +-prefixed reject path is safe, clap never claims +.)

  • usage() lies; read getflag (2026-06-05): MLU’s usage() advertises -bc (count characters), but the character branch is #ifndef UNX (mlu.cpp:678-680), so the unix binary, our parity target, ERRORS on -bc. Parity for an advertised-but-compiled-out flag is to REJECT it, not implement it. Always confirm a flag’s real behavior in the command’s getflag/case, not in the usage banner.

  • Flag growth has a hidden platform cost: the Windows 1 MiB main stack (2026-06-12): the FREQ flag explosion (2026-06-03/04) pushed clap’s debug-build command-tree construction past 1 MiB of stack, aborting EVERY chatter invocation on Windows (STATUS_STACK_OVERFLOW) before parsing; the windows-latest job sat red for a week before anyone looked. Three transferable rules. (1) Each ported command’s flags add stack to one giant generated augment_args frame, and debug builds give every temporary its own slot, so the cost is the SUM of all flags, ever. (2) The fix is owning the budget explicitly: the program now runs on a 16 MiB PROGRAM_STACK_BYTES thread (see the CLI Startup and the Program Stack architecture page), so porting the remaining ~60 commands cannot re-break this. (3) Watch ALL CI jobs after landing a command: a Windows-only, debug-only failure is exactly the shape a per-command porting session misses.

Testing Strategy

Status: Current Last updated: 2026-05-12 21:14 EDT

Unit tests

Each command module includes #[cfg(test)] unit tests that verify counting logic, edge cases, and output formatting against known inputs.

cargo nextest run -p talkbank-clan          # All tests (preferred)
cargo test -p talkbank-clan                 # Alternative
cargo test --doc -p talkbank-clan           # Doctests only (nextest can't run these)

Snapshot tests

Snapshot tests use insta to capture command output and detect regressions. They live alongside the test that produces them:

  • crates/talkbank-clan/tests/snapshots/: snapshots from transform_golden.rs, converter_golden.rs, and other top-level tests in the tests/ directory
  • crates/talkbank-clan/tests/clan_golden/snapshots/: snapshots produced by the clan_golden test module (paired @clan/@rust pairs)
cargo insta review -p talkbank-clan         # Review pending snapshot changes
cargo insta accept --all                    # Accept all pending changes

When you change a command’s output format, the snapshot test will fail. Review the diff to confirm the change is intentional, then accept.

Golden tests

Golden tests compare our output against legacy CLAN C binaries. See Golden Tests for details.

Running specific tests

# By name pattern
cargo nextest run -p talkbank-clan -E 'test(freq)'

# Only golden tests
cargo nextest run -p talkbank-clan -E 'test(golden)'

# Only indent tests
cargo nextest run -p talkbank-clan -E 'test(indent)'

Test fixtures

Test fixtures are real CHAT files from the reference corpus at corpus/reference/ (at the repo root). Never create ad hoc .cha test files, use existing corpus files or ask for new ones to be added to the reference corpus.

Current test counts

The talkbank-clan suite spans unit, snapshot, golden, and integration tests. The absolute count moves as commands are added or extended; get the live number with:

cargo nextest list -p talkbank-clan

The last line of the summary is the total count.

Command Status Matrix

Status: Historical coverage snapshot; re-baseline pending Last updated: 2026-10-31

Historical status of CLAN commands in the Rust reimplementation, as audited 2026-06-15. The coverage counts below have not been refreshed since the project resumed in October 2026.

Parity authority. This matrix is a coverage cut: which CLAN commands are implemented and which have golden tests. It is not a byte-for-byte parity claim. Byte-for-byte CLAN parity is tracked authoritatively in Parity Status, and per that page no command yet achieves byte-for-byte CLAN parity in that historical snapshot. FREQ was the active depth-first command then (25/44 flag-rows byte-parity proven as of that sweep). A row below that reads “Implemented” with “Golden Tests: Yes” means the command exists and has golden coverage; it does not mean its output byte-matches legacy CLAN. Consult Parity Status for the honest per-command signal.

Coverage: 70/70 CLAN binaries (100%). Every CLAN binary in OSX-CLAN/src/unix/bin/ has a corresponding module. The 6 NLP commands (MOR, POST, MEGRASP, etc.) are deliberately not implemented but produce clear error messages. Additionally, 7 implemented commands are outside that local binary inventory: COMPLEXITY, CORELEX, WDSIZE, LAB2CHAT, RTF2CHAT, ROLES, and TRIM.

CategoryCountGolden Tests
Validation1,
Analysis3453
Transforms2330
Converters1515
Not implemented6,
Total7998

Validation Commands (1)

CommandStatusNotes
CHECKImplementedFull flag support (+cN, +eN, +gN, +u), 161 error numbers mapped

Analysis Commands (34)

The “Parity” column was removed: its per-command “Verified” / “100%” values asserted byte-for-byte parity that Parity Status does not support for any command. This table now records only the verifiable coverage facts (implemented + golden tests present). For the honest byte-parity signal, see Parity Status.

CommandStatusGolden Tests
CHAINSImplementedYes
COMPLEXITYImplementedYes (new; auto-detects UD/legacy)
CORELEXImplementedYes (new command, not in CLAN)
CHIPImplementedYes
CODESImplementedYes
COMBOImplementedYes
COOCCURImplementedYes
DISTImplementedYes
DSSImplementedYes
EVALImplementedYes
EVAL-DImplementedVariant of EVAL (DementiaBank norms)
FLUCALCImplementedYes
FREQImplementedYes (active depth-first target in this historical snapshot)
FREQPOSImplementedYes
GEMLISTImplementedYes
IPSYNImplementedYes
KEYMAPImplementedYes
KIDEVALImplementedYes
KWALImplementedYes
MAXWDImplementedYes
MODREPImplementedYes
MLTImplementedYes
MLUImplementedYes
MORTABLEImplementedYes
PHONFREQImplementedYes
RELYImplementedYes
SCRIPTImplementedYes
SUGARImplementedYes
TIMEDURImplementedYes
TRNFIXImplementedYes
UNIQImplementedYes
VOCDImplementedYes
WDLENImplementedYes
WDSIZEImplementedYes (new; mor stem lengths)

Transform Commands (23)

CommandStatusGolden Tests
CHSTRINGImplementedYes
COMBTIERImplementedYes
COMPOUNDImplementedYes
DATACLEANImplementedYes
DATESImplementedYes
DELIMImplementedYes (4 accepted divergences)
FIXITImplementedYes
FIXBULLETSImplementedYes
FLOImplementedYes
GEMImplementedYes (2 tests: all gems + filtered)
INDENTImplementedYes (CLAN binary has infinite-loop bug, Rust-only)
LINESImplementedYes
LONGTIERImplementedYes
LOWCASEImplementedYes
MAKEMODImplementedYes
ORTImplementedYes
POSTMORTEMImplementedYes
QUOTESImplementedYes
REPEATImplementedYes
RETRACEImplementedYes
ROLESImplementedYes
TIERORDERImplementedYes
TRIMImplementedYes (2 tests: exclude-mor + exclude-all)

Format Converters (15)

CommandStatusNotes
CHAT2TEXTImplementedPlain text export
CHAT2ELANImplementedReverse of ELAN2CHAT
CHAT2PRAATImplementedPraat TextGrid export (bidirectional in praat2chat module)
CHAT2SRTImplementedSRT subtitle export
CHAT2VTTImplementedWebVTT subtitle export (Rust-side extension of the SRT converter; not in CLAN)
ELAN2CHATImplementedELAN XML import
LAB2CHATImplementedLAB format import
LENA2CHATImplementedLENA ITS import
LIPP2CHATImplementedLIPP format import
PLAY2CHATImplementedPLAY format import
PRAAT2CHATImplementedPraat TextGrid import
RTF2CHATImplementedRich Text import
SALT2CHATImplementedSALT format import
SRT2CHATImplementedSubtitle import
TEXT2CHATImplementedPlain text import

Deliberately Not Implemented (6)

These commands depend on the legacy CLAN MOR data model (trie-based lexicons, HMM/Brill taggers, MaxEnt parsers) which is incompatible with the UD-style morphological representation used in the current CHAT grammar. Use batchalign’s neural pipeline instead.

CommandPurposeRationale
MOR / MOR_PMorphological analysis~11K lines C, trie lexicon + 5 rule engines, legacy format
POSTPOS disambiguationRequires ^-separated ambiguity format not in grammar
MEGRASPDependency parsingRequires trained MaxEnt model weights
POSTLISTPOST database listingOperates on proprietary binary format
POSTMODRULESPOST rule modificationOperates on proprietary binary format
POSTTRAINPOST model trainingOperates on proprietary binary format

Compatibility-Alias Subcommands

These CLAN binaries have their own clap subcommand variant, exposed under the same name as the legacy CLAN binary, but are categorized as compatibility aliases in crates/talkbank-cli/src/cli/args/clan_commands.rs (search for CompatibilityAlias). The dedicated subcommand exists so legacy CLAN scripts that invoke the binary by name continue to work.

Five subcommand names are bucketed as CompatibilityAlias: check, fixit, indent, longtier, and gemfreq. Only gemfreq is documented in detail here because its dispatch target differs from its name; the other four (check, fixit, indent, longtier) are listed in the main category tables above and dispatch to their namesakes through the standard pipeline.

SubcommandDispatches toNotes
gemfreqfreq (with --gem required)See GEMFREQ. Implemented via Gemfreq enum variant + clap ArgGroup::required(true) on --gem; routes to AnalysisCommandName::Freq.

CLAN Parity Roadmap

Status: Historical snapshot; re-baseline pending Last modified: 2026-10-31

Historical planning snapshot for CLAN flag-parity work, last counted on 2026-06-15. Its totals and tier assignments predate the project’s October resumption and subsequent changes; they are not a current work inventory. Reconcile against current per-command audits before using them to plan work.

Byte-parity authority. This page counts flag-implementation progress (does a flag have a consuming field, does it behave on the common case). It is not the byte-for-byte parity signal; “Done” here means implemented and accepted, not output-byte-matched against legacy CLAN. The honest byte-parity status, including the generated golden-coverage table, lives in Parity Status, and per that page no command yet achieves byte-for-byte parity.

Historical headline numbers (2026-06-15)

Counted from the Audit-summary tables in every book/src/clan-reference/commands/*.md (80 command pages). See status-matrix.md for the per-command-binary coverage table, which is a different cut (binary modules exist; flags on those modules are what this page tracks).

BucketCount%Meaning
Done22033%Implemented and accepted (not necessarily byte-parity)
Partial518%Common case works; edge cases incomplete
Rewriter only15323%CLAN +flag rewrites to a chatter --flag that clap rejects, no consuming field yet
Missing24937%No rewriter, no clap field
Total flag rows673

Raw counts mislead, flag rows aren’t equal-weight. The breakdown by tier below is what should drive sequencing.

Why parity matters (strategic framing)

This is a long-haul succession project, not a sprint. The original CLAN is in production today and works for its users; nobody is blocked on chatter completing parity. The reasons to keep chipping away:

  1. TalkBank longevity. The legacy C/C++ CLAN codebase is decades old and accreted; a modern Rust reimplementation gives new developers a stack they can actually learn and contribute to in the post-current-team era.
  2. AST-based unification. chatter’s parser/model/validation are already AST-based for CHAT; getting all CLAN command logic on the same AST eliminates the “two semantic models” tax (legacy CLAN’s string-tokenization model vs. chatter’s typed model).
  3. Reproducibility from source. The whole stack, grammar, parser, commands, tests, CI, built and tested from cargo against a checked-in toolchain. No “CLAN binary on the maintainer’s laptop” provenance for output that researchers cite in papers.

Cadence: chip away over weeks and months, prioritize correctness over speed, keep the audit tables and this roadmap current as the single canonical view of remaining work. No external deadline.

Historical context

CLAN is the work of decades (Spektor, with MacWhinney, since roughly the early 1980s). The flag long-tail reflects 40+ years of feature accretion across commands as researchers asked for more ways to slice the same corpora. Many flags are display-mode variants that produce alternate output shapes for the same analysis; some are inherited from the cutt.cpp::mainusage general flag set and act as no-ops on commands that don’t semantically use them. A handful are genuinely domain-heavy linguistic features (FLUCALC syllable mode, IPSYN rules) that need PI input on semantics before they can be implemented.

Tier breakdown

Tier 1, Blocked on upstream phases (~30 rows)

The single biggest unlock. Most of these are +f/+fEXT (file output) which depend on the sidecar-file pattern.

PhaseDescriptionStatusUnlocks
Phase 0OSX-CLAN makefile fixes (wdsize/complexity/corelex)Pending, upstream CLAN, not chatter workSnapshot generation for those commands
Phase 1.1Sidecar-file output pattern (pipeout.<cmd>.{cex,xls})Pending~20 +f/+fEXT rows across most commands
Phase 1.24th banner shape for codes/complexityPendingCodes/complexity byte-parity
Phase 1.8Side-effect files (codes, chains)PendingCodes, chains output files

Effort: Phase 1.1 is ~2-3 days for the pattern + ~1 day per consuming command. Phase 1.2 and 1.8 are smaller (~1 day each).

Tier 2, Inherited no-ops (~40-60 rows of the 153 “Rewriter only”)

Shared flags from cutt.cpp::mainusage (+k, +wN/-wN, +t%X, +f/+fEXT) appear on every command that links the general flag table, but they’re semantic no-ops for commands that don’t use the relevant subsystem:

  • +k (case-sensitive), meaningful only for commands that key words (FREQ/KWAL/VOCD/COMBO/FREQPOS/DIST/MAXWD, all Done). No-op for MLU/MLT/WDLEN/WDSIZE/CHAINS/CODES which don’t word-match.
  • +wN/-wN (context window), meaningful for match-and-emit commands (KWAL/COMBO, Done). No-op for aggregate commands.
  • +t%X (dependent-tier filter), semantic varies per command; KWAL/COMBO would use it as alternate search target (a real feature, see Tier 4), most others just filter.
  • +f/+fEXT, see Tier 1.

CLAN itself silently accepts these as no-ops. Current chatter behavior is “clap errors,” so a user pasting mlu +k file.cha gets rejected. Fix is either accept-and-ignore at the clap layer (~1 day across commands) or document as deliberate-strict. Not functionality.

Tier 3, Display modes requiring CLAN binary snapshots (~50-80 rows)

Per-command +dN variants: each N (often 0..8, 20, 30, 40, 90, 99) selects a different output shape for the same analysis. Many audit-page draft sections list these with manual quotes, marked “pending PI review” because the exact byte format isn’t fully specified, only a CLAN binary run produces the authoritative output.

Concrete instances (all currently Rewriter-only):

  • KWAL: +d1..+d4, +d7, +d30/+d31, +d40, +d90/+d99
  • COMBO: +d1..+d5, +d7
  • FREQ: +d0, +d5/+d6/+d7/+d8, +d20, +dCN/+d<N/+d>=N/+d=N/+d>N
  • VOCD: +d/+d1/+d2/+d3
  • DIST: +d
  • DSS: +d/+d1
  • CHAINS: +d/+d1
  • GEM/GEMFREQ/COREELEX/FLUCALC: +dN variants

Each requires:

  1. Run real CLAN with the flag → capture byte-exact output snapshot
  2. Add the snapshot to tests/fixtures/clan-snapshots/
  3. Implement against the snapshot with TDD

Effort: ~1 hour per snapshot, ~2-4 hours per mode implementation. Bounded by snapshot generation speed. ~150 person-hours if all done.

Tier 4, Genuine implementable features in heavily-used commands (~50-80 rows)

Real engineering work, command-specific:

  • +t%X tier-search switching (KWAL/COMBO): currently main-tier search only. Switching the search target to a dependent tier (%mor, %gra, %pho) is a multi-day change per command because the word-collection layer needs an alternate path.
  • +nS/-nS speaker context windows (KWAL): like +wN but bounded by speaker rather than utterance count.
  • +bN MATTR sliding-window (FREQ): Moving-Average TTR.
  • +c2/+c3/+c4/+c7 multi-word search variants (FREQ): multi-word groups with various boundary semantics.
  • +gnS/-gnS/+gdS/-gdS LRD computation (VOCD): Limiting Relative Diversity numerator/denominator filters.
  • +o2 reverse concordance + non-CHAT (FREQ): separate format.
  • +pS word-delimiter customization (most commands): tokenizer config.
  • +x exclude-utterances-by-content (FREQ).

Effort: Bulk of the real engineering left. ~3-6 weeks for the top 10 commands if pursued sequentially.

Tier 5, Domain-heavy specialty commands (~80-120 rows)

These commands need PI input on linguistic semantics; some need ML models. Multi-week per command if implemented end-to-end.

CommandOpen workEstimate
FLUCALCSyllable-vs-word mode, side-effect files, pause computation, repetition counting1-2 weeks
IPSYNRule customization, custom-pattern files1-2 weeks
DSSRule customization1-2 weeks
CHIP+dN display modes and option-specific parity evidence; -hFILE supports exact and * patterns; see CHIP status1-2 weeks
COMPLEXITYComplexity-specific metrics~1 week
KIDEVALDatabase modifications, output extensions1-2 weeks
COREELEXThreshold/comparison modes~1 week
MORTABLECustomization~1 week

These could be deferred to a “v2 / post-practical-parity” milestone if not on the critical path.

Tier 6, Lower-priority format converters (~30-50 rows)

Default mode works; flag variants are mostly cosmetic.

Converters: chat2elan, chat2srt, chat2vtt, chat2text, praat2chat, chstring, lowcase, fixbullets, dataclean, dates, indent, postmortem, trim, retrace, tierorder, delim, quotes, repeat, combtier, compound, flo.

Effort: ~1-2 weeks if all done.

Milestones

These are rolling targets, not deadlines. Cadence is “chip away”, batch a few items per session, keep the audit tables current.

“Practical parity”, common-use flags across the top 10 commands

Target commands: FREQ, KWAL, COMBO, VOCD, DIST, COOCCUR, MAXWD, FREQPOS, MLU, MLT.

Scope: Tier 1 (sidecar pattern), Tier 3 (high-traffic +dN modes), Tier 4 (real features), Tier 2 cleanup pass.

Effort, if pursued sequentially: roughly the equivalent of 3-6 focused work-weeks. At a chip-away cadence (a few items per session, intermixed with other priorities), spread over a few months of calendar time.

“Full byte-level parity”, every flag in every command

Adds Tier 5 (domain-heavy commands) and Tier 6 (format converter flags).

Effort, if pursued sequentially: equivalent of 3-6 work-months. At chip-away cadence, spread over a year or more of calendar time. Some Tier 5 items may never be worth it for chatter’s mandate; that’s fine; we can decide per command as we approach it.

Current blockers

  1. CLAN binary access for snapshot generation. Tier 3 work is gated on running real CLAN with specific flags and capturing byte-exact output. The discrepancy-adjudication rule says “stop and ask” rather than guess, so snapshot-less display modes shouldn’t be implemented by inference.

  2. Phase 1.1 sidecar pattern not designed. Until the pattern is landed, ~20 +f/+fEXT rewriter-only entries can’t be unblocked.

  3. PI clarification needed on several open questions flagged in per-command audit pages (KWAL +d1 format, DIST +d ↔ --format csv mapping, COMBO +d3 @Comment headers).

Recently completed (last batch)

Tracking what just landed so future sessions have context. Before this repo became standalone, each item was typically a single commit on main in the earlier monorepo.

Conversation batch May 22-23, 2026 (~22 commits, ~30 new tests):

  • COOCCUR +d strip frequency counts
  • FREQ +d1/+d2/+d3/+d4 (word list / CSV / types-tokens-only)
  • +k case-sensitive rollout across all 7 search/frequency commands: FREQ, KWAL, VOCD, COMBO, FREQPOS, DIST, MAXWD (now fully landed; cross-cutting migration docs updated)
  • KWAL +d legal-CHAT-fragment output
  • KWAL +wN/-wN context window (stateful VecDeque + awaiting- after machinery)
  • COMBO +wN/-wN context window
  • MLU/MLT +g@F solo-word exclusions from file
  • COOCCUR +nN cluster size (generalized bigrams → N-grams via SmallVec)
  • Two /simplify passes: NormalizedWord::from_word_cased helper unification, KWAL hot-path precomputed-keyword fix, AnalysisRequest::kwal config-instead-of-bools, KWAL/COMBO zero-context fast path (skip to_chat_string per utterance when no window is active), COOCCUR SmallVec<[N; 2]> for bigram inline storage

Tests: 966 → 1006 (+40 over the batch).

Audit-vs-runtime sweep (2026-05-23 evening, 3 commits):

  • MLU/MLT/WDLEN +k audit-page flip. The prior +k rollout reached these non-word-keying commands via the CommonAnalysisArgs.case_sensitive flatten, but their audit pages still said Rewriter only. Verified by direct probe and flipped to Done (no-op per CLAN). Pure documentation; no code change.
  • +re global no-op rewriter arm. CLAN’s +re requests subdirectory recursion; chatter already recurses by default. The rewriter had no arm for the token, so +re survived to clap’s path-arg list and emitted a confusing Warning: "+re" is not a file or directory on every invocation. Added a one-line (b'+', b'r') if rest == "e" => Some(vec![]) next to the existing +u no-op. ~10 commands’ “Done” rows are now truthful in addition to operationally correct.
  • MLU/MLT -bw → --words rewriter arm. Audit-vs-code drift: audit pages had marked -bw Done forever, but the rewriter only had a comment, no actual arm. clap parsed -bw as a -b -w short-flag pair and errored on the unknown -b. Added the missing (b'-', b'b') if matches!(subcommand, Mlu | Mlt) && rest == "w" arm. Three regression tests guard the rollout and the scope boundary.

Three new rewriter tests (mlu_minus_bw_to_words, mlt_minus_bw_to_words, freq_minus_bw_unchanged, recurse_flag_dropped) shipped with the second and third commits.

Audit-vs-runtime sweep, second pass (2026-05-26, 5 commits):

  • COMBTIER +tS bare-prefix intercept + Combtier enum variant. COMBTIER overloads +tS away from the analysis-command convention (+tCHI = speaker filter), for combtier, S is the tier label to combine (per OSX-CLAN/src/clan/combtier.cpp). Added Combtier to ClanSubcommandKind + a per-Combtier bareword intercept routing +tcom to --tier com. The +t%com percent-prefix form was already handled by the existing % branch in rewrite_tier_speaker. Pinned by combtier_bare_tier_routes_to_tier_not_speaker and the regression guard combtier_percent_tier_form_still_works.

    Open follow-up: a diagnostic this session showed ~40 chatter commands are absent from ClanSubcommandKind. Most don’t need per-command intercepts, but the remaining Category-B candidates (chstring, chat2elan, chat2srt, lab2chat) should be walked in a future enum-population sweep.

  • LOWCASE +d2 no-op rewriter arm + Lowcase enum variant. lowcase was missing from ClanSubcommandKind, so the rewriter could not route any per-command logic to it; the generic +dN → --display-mode N catch-all fired for lowcase +d2 and produced clap rejection (error: unexpected argument '--display-mode' found). The audit page already claimed +d2 was Done (chatter’s transforms/lowcase.rs matches the CLAN +d2 semantic of “ignore dict, lowercase everything”). Added Lowcase to the enum + detect arm + a per-Lowcase no-op for +d2. Cleared the misleading rejection. The broader cleanup of the dead generic +dN → --display-mode catch-all (chatter has zero --display-mode consumers anywhere) is a separate future commit. Pinned by lowcase_d2_dropped.

  • COOCCUR +o + FREQ +o / +o0 no-op rewriter arms. Both audit pages claimed Done with “(default)”, the no-op claim is semantically correct (chatter’s FREQ and COOCCUR finalize steps both sort by count descending unconditionally, matching CLAN’s +o BST-larger-goes-left invariant), but the rewriter had no arm for the tokens. The tokens survived to clap as path args and triggered Warning: "+o" is not a file or directory on every invocation. The FREQ comment at the existing +o1 arm already acknowledged the gap (“+o / +o0 are the descending- frequency default… only +o1 flips to the alternate sort”). Added 4 rewriter tests (cooccur_sort_flag_dropped, freq_o_dropped, freq_o0_dropped, and a regression guard freq_o1_still_routes_to_reverse_concordance to pin the match- arm ordering).

Tier-2 follow-on (2026-05-26, 2 commits):

  • +wN / -wN inherited context window on the six aggregate commands (MLU, MLT, WDLEN, MAXWD, FREQPOS, FREQ). CLAN exposes the post-/pre-context flags on every analysis command via shared common-args; on aggregate commands (means, totals, histograms) they are runtime no-ops, but CLAN’s parser still accepts them. Chatter’s rewriter at clan_args.rs:411-412 already converts +w3 / -w2 to --context-after 3 / --context-before 2 globally; only the clap-side consumer was missing on the six aggregate commands, so the rewritten flag arrived as error: unexpected argument '--context-after' found. Landed via a shared InheritedContextArgs sub-args group flattened into each of the six command variants. KWAL/COMBO are deliberately excluded; they have real consumers driving per-match context emission. 6 audit-table rows flipped from Rewriter only to Done (no-op per CLAN).

One feat commit (feat(clan): InheritedContextArgs accept-and-ignore on 6 aggregate commands) plus a docs commit (audit-page flips + this roadmap entry). 7 new clap-acceptance tests (mlu_accepts_inherited_context_after + 6 parameterized <cmd>_inherits_context_both_directions); 12 end-to-end smokes against corpus/reference/core/basic-conversation.cha.

Next-up candidates

Pick one when you have a session. Not a sequence, each is self-contained and any can come first. Update this list as items land so future sessions don’t re-derive priorities.

  1. Tier 1: Land Phase 1.1 sidecar pattern. Single biggest unlock; cascades across most commands. Design a SidecarWriter trait + a per-command pipeout.<cmd>.{cex,xls} consumer. Multi- day investment but unblocks ~20 entries at once.

  2. Tier 2: Accept-and-ignore inherited no-ops at clap layer. ~1 day. Flips ~40-60 “Rewriter only” rows to “Done (no-op per CLAN’s no-op semantic)” with matching audit-doc updates. Low risk, mechanical.

  3. Tier 3: Generate CLAN snapshots for KWAL +d1 and +d2. The two most-cited “pending PI review” modes; a single CLAN run capturing snapshot output unblocks implementation. Needs CLAN binary access.

  4. Tier 4: Pick one heavily-used command’s real feature. Candidates: FREQ +c2/+c3 (multi-word search), KWAL +nS (speaker-bounded context), VOCD +gnS/+gdS (LRD), FREQ +bN (MATTR sliding window). Each is 1-3 commits.

  5. Tier 6: One format-converter flag pass. Lowest-stakes; good for a “warm up” session. chstring / chat2text / etc.

Methodology notes

  • Counts re-derived per session from awk -F'|' '/^\| Done.*\| [0-9]+ \|$/ { ...}' book/src/clan-reference/commands/*.md to keep this doc in sync. Update the headline numbers when the per-command audit tables change.

  • Tier categorization is judgement-based, not encoded in the audit-summary tables. If a row’s tier is unclear, look at the command’s +-flag table notes column, entries like “same as KWAL” or “EVAL-style overload” hint at Tier 4/5; entries like “rewriter target” hint at Tier 2 (if the flag is a shared no-op for that command) or Tier 1 (if it’s +f/+fEXT).

  • The audit pages themselves are the source of truth. This doc is a navigational summary; per-flag implementation details live on each command’s page.

CLAN Command Divergences & Improvements

Status: Current Last updated: 2026-05-30 18:59 EDT

This document tracks every divergence between the original CLAN commands and the Rust chatter-clan reimplementation. It covers CLI interface, output format, counting semantics, error handling, and intentional improvements.

Audience: Researchers who have existing CLAN pipelines and need to know what will change, and developers extending these commands.

Backward compatibility: Where CLAN’s behavior is well-defined and pipeline-critical, we aim to provide a --clan-compat mode in the future. Until then, this document serves as the authoritative migration reference.


Table of Contents


Philosophical Divergence

The most fundamental difference between CLAN and chatter-clan is not in any individual command, but in the underlying approach to analysis.

CLAN: String Matching Without a Data Model

CLAN was written in the late 1970s before the CHAT format had a formal specification. It operates directly on raw text strings, using character-level prefix matching to classify content:

// CLAN's approach to excluding non-lexical items (freq.c, mlu.c, etc.)
if (word[0] == '0') continue;     // skip omitted words
if (word[0] == '&') continue;     // skip fillers/nonwords
if (word[0] == '+') continue;     // skip terminators
if (word[0] == '-') continue;     // unclear intent
if (word[0] == '#') continue;     // skip pauses
if (strcmp(word, "xxx") == 0) continue;  // skip unintelligible
if (strcmp(word, "yyy") == 0) continue;  // skip phonetic coding
if (strcmp(word, "www") == 0) continue;  // skip untranscribed

This approach is duplicated across commands and conflates string representation with semantic meaning. For example, &-um (a filler) and &~gaga (a nonword) and &+fr (a phonological fragment) are all lumped together because they share the & prefix, even though they have distinct linguistic meanings.

Our Approach: Semantic Classification via AST

Our parser produces a typed AST where each of these categories is a distinct type. Analysis commands operate on semantic types, not string prefixes:

CLAN text patternSemantic intentOur AST representationAnalysis filtering
word[0] == '#'Skip pausesPause (separate AST node)Tree walk never visits
word[0] == '+'Skip terminatorsTerminator (separate AST level)Tree walk never visits
&=laughsSkip eventsEvent (separate AST node)Tree walk never visits
word == "xxx"Skip unintelligibleWord { untranscribed: Unintelligible }is_countable_word() returns false
word == "yyy"Skip phonetic codingWord { untranscribed: Phonetic }is_countable_word() returns false
word == "www"Skip untranscribedWord { untranscribed: Untranscribed }is_countable_word() returns false
word[0] == '0'Skip omitted wordsWord { category: Omission }is_countable_word() returns false
word[0] == '&'Skip fillers/nonwordsWord { category: Filler|Nonword|Fragment }is_countable_word() returns false
word[0] == '-'(unclear)Not a meaningful CHAT categoryNot applicable

Key insight: Pauses, events, actions, and terminators are already separate AST node types that our tree walk never visits. We only need explicit filtering on Word nodes that carry semantic annotations. The is_countable_word() function in framework/word_filter.rs encodes this logic once, and all analysis commands share it.

What This Means for Compatibility

The results should be equivalent: words that CLAN excludes via string prefix matching, we exclude via semantic type checking. But the mechanism is fundamentally different:

  • CLAN can be tricked by unusual formatting (e.g., a real word that happens to start with & due to a transcription error), our AST only marks words as fillers if the parser recognized the &- prefix and classified them as such during parsing.
  • CLAN’s word[0] == '-' exclusion has unclear intent and may exclude legitimate content; we omit this because there is no corresponding semantic category in CHAT.
  • CA (Conversation Analysis) omissions ((word)) are countable in our system (they represent uncertain but present speech), matching the linguistic intent even though CLAN may exclude them via the 0 prefix check.

General Framework Divergences

CLI Syntax

Both legacy CLAN +flag/-flag and modern --flag syntax are accepted. The CLI auto-translates via clan_args::rewrite_clan_args().

AspectCLANchatter-clan
Invocationfreq file.chachatter-clan freq file.cha
Speaker include+t*CHI--speaker CHI
Speaker exclude-t*INV--exclude-speaker INV
Tier include+t%mor--tier mor
Tier exclude-t%gra--exclude-tier gra
Word include+s"word"--include-word "word"
Word exclude-s"word"--exclude-word "word"
Gem include+g"Story"--gem "Story"
Gem exclude-g"Warmup"--exclude-gem "Warmup"
ID filter+t@ID="..."--id-filter "..."
Utterance range+z25-125--range 25-125
Include retracings+r6--include-retracings
Case-sensitive+k--case-sensitive
Display mode+dN--display-mode N
Output to file+fEXT--output-ext EXT
Context window+wN / -wN--context-after N / --context-before N
Merge across files+uDefault behavior (always on)
Output formatText only--format text|json|csv|clan
Multiple filesfreq *.cha (glob)chatter-clan freq dir/ (recursive)

Output Envelope

CLAN wraps output in a verbose envelope (command echo, timestamp, filter summary). chatter-clan uses render_clan() for CLAN-compatible output format and render_text() for clean output. The envelope is omitted in both modes, the information is available via shell history and date.

Error Handling

BehaviorCLANchatter-clan
Unparseable filePrints error, continuesLogs warning (via tracing), continues
No .cha files foundVaries by commandPrints error, exits with code 1
Missing %mor tierSkips silentlyReports 0 utterances (MLU), skips (FREQ --mor)

Multi-File Aggregation

BehaviorCLANchatter-clan
DefaultPer-file outputMerged across files
MergedRequires +u flagDefault behavior

File Output

CLAN’s +f flag writes output to auto-named files (e.g., sample.frq.cex). chatter-clan always writes to stdout. Use shell redirection:

# CLAN:
freq +f sample.cha              # -> sample.frq.cex

# chatter:
chatter-clan freq sample.cha > sample.frq.txt
chatter-clan freq sample.cha --format json > sample.frq.json

Analysis Commands

Clinically Critical Commands

FREQ, Word Frequency

  • AST-based is_countable_word() replaces string-prefix matching
  • NormalizedWord lowercases and strips compound markers for grouping
  • Deterministic sort (count descending, then alphabetical); CLAN’s order varies
  • JSON and CSV output; --format clan for character-level CLAN compatibility
  • Golden test parity: verified

MLU, Mean Length of Utterance

  • Population SD (/ n), not sample (/ n-1). Verified against CLAN output.
  • Brown’s morpheme rules: Only 7 suffix strings count: PL, PAST, Past, POSS, PASTP, Pastp, PRESP. Each adds +1 to the stem count. Fusional features (&PRES, &INF) do NOT count.
  • When no %mor tier exists and not in --words-only mode, reports 0 utterances (matching CLAN).
  • Golden test parity: 100%

MLT, Mean Length of Turn

  • Population SD (/ n), matching CLAN.
  • SD basis: Computed over per-utterance word counts, not per-turn totals.
  • Turn boundaries detected when a different speaker produces the next utterance.
  • Golden test parity: 100%

DSS, Developmental Sentence Scoring

  • Built-in rules are a simplified subset; supply full .scr file for clinical scoring.
  • Sentence-point assignment uses heuristic (subject + verb POS) rather than full syntax.
  • Up to 50 utterances per speaker scored (configurable via max_utterances).
  • Golden test parity: verified

EVAL, Language Sample Evaluation

  • AST-based word/morpheme identification and typed POS categories.
  • Error counts ([*]) extracted from parsed AST annotations, not text patterns.
  • JSON and CSV output (CLAN produces text only).
  • Golden test parity: verified

KIDEVAL, Child Language Evaluation

  • Same AST-based approach as EVAL with age-normed scoring.
  • Shares the semantic POS classification and error extraction infrastructure.
  • Golden test parity: verified

IPSYN, Index of Productive Syntax

  • Parses %mor tier structure for syntactic pattern matching.
  • The built-in scoring covers a representative subset of the ~56 grammatical categories in the full English IPSyn rule set (see crates/talkbank-clan/src/commands/ipsyn.rs). Full coverage requires supplying an external rule file.
  • Golden test parity: verified for the built-in subset

VOCD, Vocabulary Diversity (D Statistic)

  • Bootstrap sampling of TTR across sample sizes 35-50, least-squares D-curve fitting.
  • Fusional feature stripping: &PRES, &INF etc. stripped from lemmas in %mor echo output.
  • Echoes %mor lemma lines after speaker header for insufficient-token warnings.
  • D values may differ slightly due to random sampling (stochastic algorithm).
  • Golden test parity: 100%

FLUCALC, Fluency Calculation

  • Counts disfluency types (repetitions, revisions, fillers) from main tier annotations.
  • Operates on parsed retrace groups and filler categories, not text patterns.
  • Golden test parity: verified

SUGAR, Grammatical Analysis

  • SUGAR scoring from %mor tier POS categories.
  • AST-based morpheme and word classification.
  • Golden test parity: verified

Other Analysis Commands

CHAINS, Clause Chain Analysis

  • Walks parsed %gra tier dependency structure instead of text-based bracket matching.
  • Clause boundaries identified from dependency relations, not punctuation heuristics.
  • Golden test parity: verified

CHIP, Child/Parent Interaction Profile

  • 36-measure matrix format matching CLAN exactly (ADU/CHI/ASR/CSR columns).
  • Echo: Main tier + %mor only (not %gra tiers), matching CLAN.
  • Interaction scoring (imitation, expansion, reduction) computed from %mor tier alignment.
  • Golden test parity: 100%

CODES, Code Frequency

  • Counts codes from %cod tier annotations using AST structure.
  • Golden test parity: verified
  • Operates on parsed AST content rather than raw text pattern matching.
  • Boolean AND/OR/NOT composition on word-level matches.
  • Golden test parity: verified

COOCCUR, Word Co-occurrence

  • Bigram counting from countable words per utterance.
  • Uses NormalizedWord for consistent key normalization.
  • Golden test parity: verified

DIST, Word Distribution Across Turns

  • Every utterance is its own turn (no speaker-continuity grouping), matching CLAN.
  • Per-speaker distribution of words across turn positions.
  • Golden test parity: 100%

FREQPOS, Positional Frequency

  • Word frequency by utterance position (initial, final, other, one-word).
  • AST-based word identification and position tracking.
  • Golden test parity: verified

GEMLIST, Gem Segments

  • Lists @Bg/@Eg gem boundaries from file headers.
  • Golden test parity: verified

KEYMAP, Contingency Tables

  • Reads coded data from %cod tier, builds contingency matrix.
  • Golden test parity: verified

MAXWD, Longest Words

  • Reports all occurrences with line numbers, matching CLAN.
  • Golden test parity: 100%

MODREP, Model/Replica Comparison

  • Compares %mod (model) and %pho (replica) tiers phonologically.
  • AST-based phonological comparison rather than string distance.
  • Golden test parity: verified

MORTABLE, Morphology Tables

  • Tabulates POS categories and morphological features from %mor tier.
  • Golden test parity: verified

PHONFREQ, Phonological Frequency

  • Frequency counts from %pho tier phonological transcription.
  • Golden test parity: verified

RELY, Inter-rater Agreement

  • Cohen’s kappa for inter-rater reliability between two transcription files.
  • Golden test parity: verified

SCRIPT, Template Comparison

  • Compares transcript against template script, computes accuracy metrics.
  • Golden test parity: verified

TIMEDUR, Time Duration

  • Computes duration from media timestamp bullets.
  • Interaction matrix header includes leading space, matching CLAN exactly.
  • Golden test parity: 100%

TRNFIX, Tier Comparison

  • Compares two dependent tiers side-by-side.
  • Uses ∅ for length mismatches between compared tiers.
  • Golden test parity: verified

UNIQ, Repeated Utterances

  • Includes %mor/%gra dependent tiers in counts, matching CLAN.
  • Splits multi-line headers for counting, matching CLAN.
  • 1 accepted divergence: Unicode sort order for U+230A (LEFT FLOOR), C-locale strcoll() vs Rust byte-order. Single line position swap, identical content and counts.
  • Golden test parity: 99%

WDLEN, Word Length Distribution

  • 6-section format: characters (1), words (2), morphemes (3), per-utterance (4), per-word morphemes (5), per-word with POS (6).
  • Brown’s morpheme rules: Section 5 = stem + Brown’s suffix (no POS). Section 6 = POS + stem + Brown’s suffix.
  • Clitic handling: Section 5 merges main+clitics as one word. Section 6 counts POS only for main word.
  • Apostrophe stripping: Characters counted after removing apostrophes, matching CLAN.
  • Reverse speaker order: CLAN’s linked-list prepend pattern replicated.
  • XML footer: </Table></Worksheet></Workbook> appended to match CLAN output.
  • Golden test parity: 100%

Transform Commands

All transforms use the AST pipeline: parse → transform → serialize → write.

CHSTRING, String Replacement

  • Operates on parsed AST word nodes, not raw text. Structural integrity preserved.
  • Does not support CLAN’s regex-based patterns in changes files.

COMBTIER, Combine Tiers

  • Merges multiple dependent tiers of the same type via AST manipulation.

COMPOUND, Compound Normalization

  • Normalizes compound word formatting (dash to plus) in the AST.

DATACLEAN, Format Cleanup

  • Fixes common CHAT formatting errors (spacing, brackets) in serialized text.
  • Operates on serialized output rather than AST (custom run function).

DATES, Age Computation

  • Computes participant ages from @Birth and @Date headers.
  • Uses Rust chrono date arithmetic rather than C-style manual calculation.

DELIM, Add Terminators

  • Sets the Terminator field on the AST, not scanning line endings.
  • 4 accepted divergences: CLAN writes empty file when no changes needed; we always write the full file.

FIXBULLETS, Timing Repair

  • Enforces monotonic timing bullet ordering via AST timestamp fields.

FLO, Fluent Output

  • Walks AST nodes (retrace groups, replaced words, events, pauses) instead of regex-stripping.
  • Uses shared is_countable_word() for filtering.

GEM, Gem Extraction

  • Extracts utterances within @Bg/@Eg boundaries.
  • Also available as a filter on analysis commands.

LINES, Line Numbers

  • Operates on serialized text (custom run function).

LOWCASE, Lowercase

  • Lowercases word content in AST nodes, preserving annotations.

MAKEMOD, Model Tier

  • Generates %mod tier from pronunciation lexicon lookup.

ORT, Orthographic Conversion

  • Dictionary-based orthographic conversion via AST word replacement.

POSTMORTEM, Mor Post-processing

  • Pattern-matching rules applied to %mor tier AST structure.
  • Rule application is structural (MorWord fields) rather than text-based.

QUOTES, Extract Quotes

  • Operates on serialized text (custom run function).

REPEAT, Mark Repetitions

  • Marks utterances containing revisions with [+ rep] postcode.
  • Detection via parsed retrace group annotations.

RETRACE, Retrace Tier

  • Generates retrace annotation tier from AST structure.

TIERORDER, Reorder Tiers

  • Reorders dependent tiers by priority (standard CHAT ordering).
  • Operates on DependentTier vector in the AST.

Format Converters

All converters build/consume ChatFile AST structures, not raw text.

CHAT2ELAN, CHAT to ELAN

  • Produces EAF 3.0 XML with time-aligned annotation tiers.
  • CLAN equivalent: separate chat2elan binary.

CHAT2SRT, CHAT to Subtitles

  • Strips CHAT annotations by walking AST content variants.
  • Supports both SRT and WebVTT output formats (CLAN: SRT only).

ELAN2CHAT, ELAN to CHAT

  • ELAN tier IDs mapped to 3-character uppercased speaker codes.
  • Simple string-based XML parsing (no quick-xml dependency).

LAB2CHAT, LAB to CHAT

  • Timing label files from speech research converted to timed CHAT utterances.

LENA2CHAT, LENA to CHAT

  • LENA device XML (.its) import with segment timing.
  • Maps LENA speaker categories to CHAT participant codes.

LIPP2CHAT, LIPP to CHAT

  • LIPP phonetic profile import with %pho tier generation.

PLAY2CHAT, PLAY to CHAT

  • PLAY annotation format import.

PRAAT2CHAT, Praat TextGrid

  • Bidirectional: TextGrid → CHAT and CHAT → TextGrid in one module.
  • Supports both long and short TextGrid formats.
  • CLAN has separate commands for each direction.

RTF2CHAT, Rich Text to CHAT

  • Rich Text Format import with formatting strip.

SALT2CHAT, SALT to CHAT

  • SALT transcription format import with speaker/utterance mapping.
  • Handles SALT-specific conventions (utterance boundaries, codes).

SRT2CHAT, Subtitles to CHAT

  • SRT subtitle import with timing bullet generation.
  • Handles subtitle numbering, multi-line entries, and timestamp parsing.

TEXT2CHAT, Plain Text to CHAT

  • Plain text import with sentence splitting heuristics.
  • Generates minimal CHAT headers (@Begin, @Participants, @End).

Key Discoveries

These findings were established during parity verification (golden tests comparing against CLAN C binaries):

  1. Brown’s Morpheme Rules: CLAN MLU/WDLEN count only 7 suffix strings as bound morphemes: PL, PAST, Past, POSS, PASTP, Pastp, PRESP.

  2. Population SD: Both MLU and MLT use population SD (/ n), not sample (/ n-1).

  3. MLT SD basis: Computed over per-utterance word counts, not per-turn totals.

  4. DIST turns: Every utterance is its own turn (no speaker-continuity grouping).

  5. WDLEN morphemes: Section 5 = stem + Brown’s suffix (no POS). Section 6 = POS + stem + Brown’s suffix. Clitic pairs = one word in section 5, POS counted only for main word in section 6.

  6. WDLEN characters: CLAN strips apostrophes before counting character length.

  7. Speaker ordering: CLAN outputs speakers in reverse encounter order (linked-list prepend pattern from the C implementation).

  8. Fusional features: &PRES, &INF etc. are stored as part of the lemma string in our model (for roundtrip fidelity). Strip with split('&') when needed.

  9. CHIP echo: CLAN echoes main tiers + %mor only, not %gra tiers.


Parity Status

95% (113/118): 5 accepted divergences across 2 commands.

CommandDivergencesStatus
DELIM4Accepted: CLAN writes empty file when no changes needed
UNIQ1Accepted: Unicode sort order edge case (U+230A)

All other commands: 100% parity with CLAN C binary output in golden tests.


Last Updated: 2026-03-05 Based on CLAN manual (January 27, 2026 edition) and golden test verification

Transform Taxonomy

Status: Current Classification of the 23 transform commands by operation level.

Text/Layout Transforms (5)

These transforms operate on serialized CHAT text, not the AST. They handle formatting concerns that have no structural representation in the data model.

CommandOperationWhy Text-Level
LONGTIERRemove continuation line wrapping (\n\t → single line)Line wrapping is a display concern
LINESAdd/remove line number prefixesLine numbers have no AST representation
INDENTAlign CA overlap markers by columnColumn alignment is visual, not structural
LOWCASELowercase main tier wordsOperates on AST (Word.text), but simple enough to be text-like
CHSTRINGFind/replace strings using a changes fileText substitution by design

Structured/AST Transforms (15)

These transforms modify the parsed AST and re-serialize. They use typed model fields, not string manipulation.

CommandOperationKey AST Types
QUOTESExtract quoted text to separate utterancesUtterance, Postcode
ORTOrthographic conversion via dictionaryWord.text
RETRACECopy main tier to %ret dependent tierMainTier → DependentTier
COMBTIERMerge duplicate dependent tiersDependentTier list
POSTMORTEMPattern rules on %mor itemsMorTier.items (partially; %mor rewrite pending)
FLOGenerate %flo tier (simplified fluent output)MainTier.content → DependentTier::Flo
FIXBULLETSRepair timing bullet orderingBullet.timing (start_ms, end_ms)
TIERORDERReorder dependent tiers to canonical orderUtterance.dependent_tiers
TRIMRemove selected dependent tiersUtterance.dependent_tiers.retain()
MAKEMODGenerate %mod tier from pronunciation lexiconWord → DependentTier::Mod
COMPOUNDNormalize compound word formatting (dash → plus)Word.text compound markers
REPEATMark utterances with revisions as [+ rep]Utterance retrace annotations
ROLESRename speaker codesSpeakerCode in headers + utterances
DATESCompute participant ages from @Birth/@DateHeader::ID age field
DELIMAdd missing terminatorsMainTier.terminator

Mixed/Hybrid Transforms (3)

These transforms use a combination of AST and text-level operations.

CommandOperationNotes
DATACLEANFix CHAT formatting errors (brackets, tabs, ellipsis)Text-level by design: fixes sub-token formatting that the parser accepts as-is
FIXITNormalize via parse-serialize roundtripAST transform is a no-op; normalization comes from the serializer’s canonical formatting
GEMExtract utterances within @Bg/@Eg gem boundariesAST-based: filters ChatFile.lines by gem header state

Pipeline Patterns

Standard AST pipeline (most transforms)

read file → parse → validate → transform(AST) → serialize → write

Handled by framework::run_transform().

Text-level pipeline (DATACLEAN, LINES)

read file → parse → validate → serialize → transform(text) → write

Uses custom run functions that operate on the serialized string.

File-argument pipeline (COMPOUND, DATES)

copy to temp → run with file path → read output

Some CLAN binaries don’t support stdin; these use file arguments.

Dependent Tier Semantics Matrix

Status: Current Last updated: 2026-05-11 23:50 EDT

Classification of the 31 DependentTier variants (crates/talkbank-model/src/model/dependent_tier/types.rs) by structural complexity and how commands access them.

Fully Structured (10 tiers)

These tiers have dedicated AST types with typed items. Commands should iterate typed fields, never split_whitespace() on serialized text.

TierAST TypeTyped ItemsUsed By
%morMorTierVec<Mor> → MorWord { pos, lemma, features }EVAL, KIDEVAL, MLU, VOCD, DSS, IPSYN, SUGAR, FREQ, etc.
%graGraTierVec<GrammaticalRelation> → { head, dependent, relation }EVAL, KIDEVAL, SUGAR, IPSYN
%phoPhoTierVec<PhoItem> → PhoWord { phones }PHONFREQ
%modMod(PhoTier)Same structure as %phoMODREP, MAKEMOD
%sinSinTierSinGroupGestures(not directly analyzed)
%actActTierBulletContent (text with optional timing)(situational)
%codCodTierBulletContent → CodSemanticElement via cod.rsCODES, CHAINS, KEYMAP, RELY
%xmodsylModsyl(SylTier)Vec<NonEmptyString>, syllabified target IPA (Phon)(see Phon Tiers)
%xphosylPhosyl(SylTier)Vec<NonEmptyString>, syllabified actual IPA (Phon)(see Phon Tiers)
%xphoalnPhoaln(PhoalnTier)Vec<WordAlignment>, segmental target↔actual mappings (Phon)(see Phon Tiers)

Bullet-Bearing Text (7 tiers)

These tiers contain free text with optional timing bullets. The text content is not further parsed into typed items. Commands access via BulletContent.text.

TierAST TypeContentUsed By
%addAddTierBulletContent (addressee annotations)(rare)
%comComTierBulletContent (comments)(metadata)
%expExpTierBulletContent (explanations)(metadata)
%gpxGpxTierBulletContent (gestural/proxemic)(situational)
%intIntTierBulletContent (intonation)(situational)
%sitSitTierBulletContent (situational notes)(situational)
%spaSpaTierBulletContent (speech act)(pragmatic analysis)

Simple Text (10 tiers)

These tiers contain plain text without timing bullets. They have minimal structure.

TierContentNotes
%altAlternative transcription
%cohCohesion annotation
%defDefinitions
%engEnglish gloss
%errError coding
%facFacial expression
%floFluent outputGenerated by FLO transform
%glsGloss
%ortOrthographic representation
%parParalinguistic

Special (4 tiers)

TierAST TypeNotes
%timTimTierTiming offset (numeric, not text)
%worWorTierWord-level alignment tier (generated from main tier)
UserDefinedUserDefinedTierArbitrary %xyz tiers not in the standard set
UnsupportedUnsupportedTierParser catch-all for unrecognized tier prefixes

Command Access Patterns

Correct: Typed access

// EVAL, KIDEVAL, iterate typed MorTier items
if let Some(mor_tier) = mor::extract_mor_tier(utterance) {
    for item in mor_tier.items.iter() {
        mor::classify_mor_item(item, &mut counts);
    }
}

Correct: Generic fallback for untyped tiers

// RELY, KEYMAP, split_whitespace() on tiers without typed representation
codes.extend(
    dependent_tier_content_text(dep)
        .split_whitespace()
        .filter(|t| !t.is_empty() && *t != ".")
        .map(str::to_owned),
);

Incorrect: Serializing typed tier then re-tokenizing

// DO NOT: serialize %mor then split_whitespace()
let text = dependent_tier_content_text(dep);
for token in text.split_whitespace() { ... }
// Instead: iterate MorTier.items directly

Flag Translation Guide

Status: Current Last updated: 2026-05-12 04:20 EDT

Complete mapping between legacy CLAN +flag/-flag syntax and modern --flag equivalents. Both styles are accepted by chatter-clan. Translation lives in crates/talkbank-clan/src/clan_args.rs.

Speaker and tier filters

CLANModernDescription
+t*CHI--speaker CHIInclude speaker
-t*CHI--exclude-speaker CHIExclude speaker
+t%mor--tier morInclude dependent tier
-t%gra--exclude-tier graExclude dependent tier
+t@ID="..."--id-filter "..."Filter by @ID fields

Word filters

CLANModernDescription
+s<word>--include-word <word>Include word
-s<word>--exclude-word <word>Exclude word
+k--plus-k (--case-sensitive alias)Toggle command-specific case handling

Gem and range

CLANModernDescription
+g<label>--gem <label>Include gem segment
-g<label>--exclude-gem <label>Exclude gem segment
+z25-125--range 25-125Utterance range

Display and output

CLANModernDescription
+dN--display-mode NDisplay mode
+fEXT--output-ext EXTOutput file extension
+u (CHECK)--check-udValidate UD features (CHECK-specific)
+u (other commands)(no-op)Legacy “merge speakers”; chatter always merges, so this is a no-op
+r6--include-retracingsCount retraced material

Context

CLANModernDescription
+wN--context-after NContext lines after match
-wN--context-before NContext lines before match

CLAN Manual Audit

Status: Current This appendix tracks how the CLAN manual covers the commands currently implemented in talkbank-clan.

The purpose of this audit is to keep the book honest about command intent:

  • when the manual has a command section, that section is the starting point for legacy semantics
  • when the manual is silent or incomplete, the command chapter should say so explicitly
  • GUI-oriented legacy material should move to the TalkBank VS Code extension docs, not this CLI book

Status legend

StatusMeaning
SectionThe legacy manual has a recognizable standalone command section.
IndirectThe command is mentioned or implied, but not documented as a standalone section.
MissingNo clear standalone coverage was found in the legacy manual.

Validation and Analysis Commands

CommandManual statusNotes
CHECKSectionNeeds a dedicated modernization pass.
FREQSectionPresent in CLAN.html.
MLUSectionPresent in CLAN.html.
MLTSectionPresent in CLAN.html.
VOCDSectionPresent in CLAN.html.
DSSSectionPresent in CLAN.html; manual also references the MOR pipeline.
EVALSectionPresent in CLAN.html.
EVAL-DMissingNo standalone section was found in the published CLAN manual.
KIDEVALSectionPresent in CLAN.html.
IPSYNSectionPresent in CLAN.html.
FLUCALCSectionPresent in CLAN.html.
SUGARMissingNo standalone section was found in the published CLAN manual.
MORTABLESectionPresent in CLAN.html.
KWALSectionPresent in CLAN.html.
COMBOMissingNo standalone section was found in the published CLAN manual.
CODESMissingNo standalone section found; codes.ord is mentioned inside CHAINS.
COMPLEXITYMissingNo standalone section was found in the published CLAN manual.
CORELEXSectionPresent in CLAN.html.
CHAINSSectionExplicit coding-tier semantics in manual.
CHIPSectionPresent in CLAN.html.
COOCCURMissingNo standalone section was found in the published CLAN manual.
DISTSectionPresent in CLAN.html.
FREQPOSSectionPresent in CLAN.html.
GEMLISTSectionPresent in CLAN.html.
KEYMAPSectionExplicit coding-tier semantics in manual; non-$ strings ignored.
MAXWDSectionPresent in CLAN.html.
MODREPSectionPresent in CLAN.html.
PHONFREQMissingNo standalone section was found in the published CLAN manual.
RELYSectionExplicit %cod/%spa coding-tier semantics and +c1 code-prefix comparison.
SCRIPTSectionPresent in CLAN.html.
TIMEDURSectionPresent in CLAN.html.
TRNFIXMissingNo standalone section was found in the published CLAN manual.
UNIQMissingNo standalone section was found in the published CLAN manual.
WDLENSectionPresent in CLAN.html.
WDSIZEMissingNo standalone section was found in the published CLAN manual.

Transform Commands

CommandManual statusNotes
CHSTRINGSectionPresent in CLAN.html.
COMBTIERSectionManual intent is narrow: combining duplicate %com lines.
COMPOUNDMissingNo standalone section was found in the published CLAN manual.
DATACLEANMissingNo standalone section was found in the published CLAN manual.
DATESSectionPresent in CLAN.html.
DELIMSectionPresent in CLAN.html.
FIXITSectionPresent in CLAN.html.
FIXBULLETSSectionPresent in CLAN.html.
FLOSectionPresent in CLAN.html.
GEMSectionPresent in CLAN.html.
INDENTSectionManual confirms text/layout purpose.
LINESSectionManual confirms text/layout purpose.
LONGTIERSectionManual confirms text/layout purpose.
LOWCASESectionPresent in CLAN.html.
MAKEMODMissingNo standalone section was found in the published CLAN manual.
ORTMissingNo standalone section was found in the published CLAN manual.
POSTMORTEMIndirectMentioned only through the mor *.cha pipeline in the published CLAN manual.
QUOTESSectionPresent in CLAN.html.
REPEATSectionPresent in CLAN.html.
RETRACESectionPresent in CLAN.html.
ROLESMissingNo standalone section was found in the published CLAN manual.
TIERORDERSectionPresent in CLAN.html.
TRIMSectionPresent in CLAN.html.

Format Converters

CommandManual statusNotes
CHAT2TEXTSectionPresent in CLAN.html.
CHAT2ELANSectionPresent in CLAN.html.
CHAT2PRAATSectionPresent in CLAN.html.
CHAT2SRTSectionPresent in CLAN.html.
ELAN2CHATSectionPresent in CLAN.html.
LAB2CHATSectionPresent in CLAN.html.
LENA2CHATSectionPresent in CLAN.html.
LIPP2CHATSectionPresent in CLAN.html.
PLAY2CHATMissingNo standalone section was found in the published CLAN manual.
PRAAT2CHATSectionPresent in CLAN.html.
RTF2CHATMissingNo standalone section was found in the published CLAN manual.
SALT2CHATMissingNo standalone section was found in the published CLAN manual.
SRT2CHATSectionPresent in CLAN.html.
TEXT2CHATMissingNo standalone section was found in the published CLAN manual.

Priorities

The next documentation passes should focus on:

  1. commands with strong manual semantics that should constrain implementation behavior, especially CHAINS, KEYMAP, and RELY
  2. commands whose current docs over-generalize legacy intent, especially COMBTIER
  3. commands with no standalone CLAN.html section, where the book needs to say what evidence is being used instead of pretending the manual is explicit

Glossary

Status: Current Last updated: 2026-05-12 04:22 EDT

CHAT Format Terms

CHAT (Codes for the Human Analysis of Transcripts)
The transcription format used by TalkBank. Files have .cha extension.
Main tier
The primary transcription line beginning with *SPK: (e.g., *CHI:). Contains the spoken text.
Dependent tier
Lines beginning with % that provide annotations for the preceding main tier (e.g., %mor: for morphology, %gra: for grammar).
Speaker code
Short identifier for a participant, up to seven characters from A-Z, 0-9, _, -, '; three uppercase letters is the convention (e.g., CHI = child, MOT = mother, FAT = father, INV = investigator).
%mor tier
Morphological analysis tier containing POS tags and morpheme breakdowns.
%gra tier
Grammatical relations tier containing dependency structure.
Gem
A marked segment of transcript bounded by @Bg (begin gem) and @Eg (end gem) headers. See Filtering gems.
Terminator
Utterance-ending punctuation (. period, ? question, ! exclamation) that appears at the end of main tier lines.

Analysis Terms

MLU (Mean Length of Utterance)
Average number of morphemes (or words) per utterance. The primary measure of grammatical development in child language.
TTR (Type-Token Ratio)
Ratio of unique words (types) to total words (tokens). A basic measure of lexical diversity.
NDW (Number of Different Words)
Count of unique word types in a sample.
D statistic
Vocabulary diversity measure computed by VOCD. More stable than TTR because it accounts for sample size.
DSS (Developmental Sentence Scoring)
Clinical scoring system for grammatical complexity (Lee & Canter).
IPSyn (Index of Productive Syntax)
Syntactic complexity score based on the presence of specific grammatical structures.
SLD (Stuttering-Like Disfluencies)
Disfluency types characteristic of stuttering: prolongations, blocks, part-word repetitions.
TD (Typical Disfluencies)
Normal disfluency types: phrase repetitions, revisions, filled pauses.

Technical Terms

AST (Abstract Syntax Tree)
The typed, structured representation of a CHAT file produced by the parser. All analysis operates on the AST, not raw text.
Countable word
A word with genuine lexical content, as determined by is_countable_word(). Excludes fillers, fragments, untranscribed markers, and omissions.
NormalizedWord
Canonical lowercased word form used as frequency map key. Implements Borrow<str> for zero-allocation lookups.
Golden test
A test that compares output against the original CLAN C binary to verify parity.
CUTT (CLAN Utility Template Toolkit)
The 17,926-line C framework underlying original CLAN. Replaced by the Rust framework in src/framework/.
Framework
The shared infrastructure (src/framework/) that handles filtering, command lifecycle, and output formatting for all commands.