Ask your agent: “Add agent-first-slug to my project and use it to slugify titles for URL path segments.”
A slug here is one path segment, generated by rules the caller writes down:
which characters survive, what becomes the delimiter, how dots, case, length
and empty results are handled, and which surface — a local filesystem path
segment or a URL path segment — the result is checked against. Nothing is
guessed from the input, so the same configuration gives the same slug
everywhere. The Rust library embeds that pipeline; the afslug CLI exposes the
same configuration as flags and validates values you already have.
Install the Library
cargo add agent-first-slug --no-default-features
The default cli feature only builds the afslug binary; a library consumer
does not need it.
Default Unicode Slugs
SlugConfig::default() keeps Unicode letters and numbers, lowercases, turns
every other run of characters (dots included) into one -, trims the ends, and
validates nothing. An input with nothing to keep gives an empty slug.
use agent_first_slug::{slugify, SlugConfig};
let config = SlugConfig::default();
assert_eq!(slugify("Hello", &config)?.slug, "hello");
assert_eq!(slugify("Hello, world!!!", &config)?.slug, "hello-world");
assert_eq!(slugify("-- already -- spaced --", &config)?.slug, "already-spaced");
assert_eq!(slugify("現在的Nobody,未來的Somebody!", &config)?.slug, "現在的nobody-未來的somebody");
assert_eq!(slugify("お元気ですか?", &config)?.slug, "お元気ですか");
assert_eq!(slugify("!!!", &config)?.slug, "");
let result = slugify("hello", &config)?;
assert!(!result.changed_from_input);
# Ok::<(), agent_first_slug::SlugError>(())
Use the default only when it matches the target. For anything stored or
routed, write every SlugConfig field at the call site, as below, so the rules
are visible where the slug is made.
Choosing The Target Surface
Slugify one segment at a time; never pass a whole filesystem path or URL through one call. Then pick the surface the segment will live in:
| Rejected by | LocalPathSegment | UrlPathSegment |
|---|---|---|
empty value, ., .. | yes | yes |
/ and \ | yes | yes |
| Unicode whitespace and control characters | yes | yes |
?, #, % | no | yes |
Both checks are structural: they reject what would split a segment, change its
meaning, or be read as an escape. They do not know a particular filesystem’s
reserved names or punctuation (CON and : on Windows), a trailing dot that
some filesystems strip, or a byte-length limit. What keeps a generated slug
portable is the configuration that produced it: the character set, the
delimiter and the dot policy decide every character it can contain.
Local Filesystem Path Segment
Replace dots unless the caller explicitly wants them in a filename, and supply a fallback so an input with nothing to keep still names a file.
use agent_first_slug::{
slugify, AllowedCharacterSet, DotHandlingPolicy, EmptyOutputPolicy, SlugConfig,
SlugValidationPolicy, TransliterationPolicy,
};
let config = SlugConfig {
replacement_delimiter: '-',
lowercase_enabled: true,
max_slug_chars: None,
allowed_character_set: AllowedCharacterSet::UnicodeAlphanumericCharacters,
dot_handling_policy: DotHandlingPolicy::ReplaceAllDots,
transliteration_policy: TransliterationPolicy::None,
validation_policy: SlugValidationPolicy::LocalPathSegment,
empty_output_policy: EmptyOutputPolicy::UseFallbackSlug("fallback".to_string()),
};
assert_eq!(slugify("Ubuntu 16.04", &config)?.slug, "ubuntu-16-04");
assert_eq!(slugify("你好,世界", &config)?.slug, "你好-世界");
assert_eq!(slugify("!!!", &config)?.slug, "fallback");
# Ok::<(), agent_first_slug::SlugError>(())
When the name has to survive tools that only handle ASCII, keep only ASCII letters and digits. Text in other scripts then falls back:
use agent_first_slug::{
slugify, AllowedCharacterSet, DotHandlingPolicy, EmptyOutputPolicy, SlugConfig,
SlugValidationPolicy, TransliterationPolicy,
};
let config = SlugConfig {
replacement_delimiter: '-',
lowercase_enabled: true,
max_slug_chars: None,
allowed_character_set: AllowedCharacterSet::AsciiAlphanumericCharacters,
dot_handling_policy: DotHandlingPolicy::ReplaceAllDots,
transliteration_policy: TransliterationPolicy::None,
validation_policy: SlugValidationPolicy::LocalPathSegment,
empty_output_policy: EmptyOutputPolicy::UseFallbackSlug("fallback".to_string()),
};
assert_eq!(slugify("Hello 世界", &config)?.slug, "hello");
assert_eq!(slugify("你好,世界", &config)?.slug, "fallback");
# Ok::<(), agent_first_slug::SlugError>(())
URL Path Segment
The slug is returned raw — UTF-8 text, never percent-encoded — and
UrlPathSegment validates that raw value. The two jobs are separate:
- Validation refuses the characters that end or split a path segment
(
/,?,#) or start a percent escape (%). - Encoding belongs to whoever builds the URL. Everything validation lets
through — non-ASCII letters included — still goes through a URL library’s
path-segment encoder (for example
url::Url::path_segments_mut().push). Never concatenate a slug into a URL by hand.
use agent_first_slug::{
slugify, AllowedCharacterSet, DotHandlingPolicy, EmptyOutputPolicy, SlugConfig,
SlugValidationPolicy, TransliterationPolicy,
};
let config = SlugConfig {
replacement_delimiter: '-',
lowercase_enabled: true,
max_slug_chars: None,
allowed_character_set: AllowedCharacterSet::UnicodeLettersAndDecimalDigits,
dot_handling_policy: DotHandlingPolicy::PreserveDotsBetweenDecimalDigits,
transliteration_policy: TransliterationPolicy::None,
validation_policy: SlugValidationPolicy::UrlPathSegment,
empty_output_policy: EmptyOutputPolicy::KeepEmptySlug,
};
assert_eq!(slugify("Ubuntu 16.04", &config)?.slug, "ubuntu-16.04");
assert_eq!(slugify(".18 increased ! ", &config)?.slug, "18-increased");
assert_eq!(slugify("お元気ですか?", &config)?.slug, "お元気ですか");
// With KeepEmptySlug, the surface check is what refuses an empty segment.
assert_eq!(
slugify("!!!", &config),
Err(agent_first_slug::SlugError::EmptyPathSegment)
);
# Ok::<(), agent_first_slug::SlugError>(())
Character Sets And Combining Marks
AllowedCharacterSet | Keeps |
|---|---|
UnicodeAlphanumericCharacters (default) | Rust’s char::is_alphanumeric: letters, every Unicode number, and the combining marks Unicode calls alphabetic |
AsciiAlphanumericCharacters | a–z, A–Z, 0–9 |
UnicodeLettersAndDecimalDigits | Unicode letters and decimal digits; no marks |
UnicodeLettersMarksAndDecimalDigits | the above plus any combining mark that follows a kept character |
Thai, Lao, Devanagari, Tamil and many other scripts write vowels, viramas or
tones as combining marks after a base letter. Only
UnicodeLettersMarksAndDecimalDigits keeps those words whole.
UnicodeLettersAndDecimalDigits turns every mark into a delimiter, and the
default keeps most vowel signs but still splits at viramas and tone marks.
use agent_first_slug::{slugify, AllowedCharacterSet, SlugConfig};
let marks = SlugConfig {
allowed_character_set: AllowedCharacterSet::UnicodeLettersMarksAndDecimalDigits,
..SlugConfig::default()
};
assert_eq!(slugify("नमस्ते ไม่ใช่", &marks)?.slug, "नमस्ते-ไม่ใช่");
assert_eq!(slugify("नमस्ते ไม่ใช่", &SlugConfig::default())?.slug, "नमस-ते-ไม-ใช");
# Ok::<(), agent_first_slug::SlugError>(())
A mark with nothing kept before it — at the start, after a delimiter, after a dot — is filtered like any other character, so a slug never begins with a stray mark.
Dot Handling
Dots are decided before other filtered characters become delimiters.
PreserveDotsBetweenDecimalDigits keeps a dot only between two decimal digits
the character set itself keeps, which preserves version numbers without
keeping sentence punctuation.
use agent_first_slug::{slugify, DotHandlingPolicy, SlugConfig};
let replace_all_dots = SlugConfig {
dot_handling_policy: DotHandlingPolicy::ReplaceAllDots,
..SlugConfig::default()
};
let preserve_all_dots = SlugConfig {
dot_handling_policy: DotHandlingPolicy::PreserveAllDots,
..SlugConfig::default()
};
let preserve_version_dots = SlugConfig {
dot_handling_policy: DotHandlingPolicy::PreserveDotsBetweenDecimalDigits,
..SlugConfig::default()
};
assert_eq!(slugify("Ubuntu 16.04", &replace_all_dots)?.slug, "ubuntu-16-04");
assert_eq!(slugify("A.B..C", &preserve_all_dots)?.slug, "a.b..c");
assert_eq!(slugify("T.U.S.F.G.E.3.0.8", &preserve_version_dots)?.slug, "t-u-s-f-g-e-3.0.8");
# Ok::<(), agent_first_slug::SlugError>(())
PreserveAllDots can leave a trailing dot (a. stays a.), which both
surfaces accept and some filesystems strip; keep it away from local paths
unless that is intended.
Transliteration
Transliteration is a caller-provided static map, applied before lowercasing and filtering, so a legacy scheme can be expressed without a named preset in the library. At each position the longest matching pattern wins, whatever the order of the slice. Patterns must be nonempty and unique — even a repeated entry with the same replacement is refused — and an invalid map is refused for every input, including an empty one.
use agent_first_slug::{
slugify, AllowedCharacterSet, SlugConfig, TransliterationPolicy,
};
static MAP: &[(&str, &str)] = &[("Æ", "AE"), ("東京", "Tokyo")];
let config = SlugConfig {
allowed_character_set: AllowedCharacterSet::AsciiAlphanumericCharacters,
transliteration_policy: TransliterationPolicy::StaticReplacementMap(MAP),
..SlugConfig::default()
};
assert_eq!(slugify("Æther 東京", &config)?.slug, "aether-tokyo");
# Ok::<(), agent_first_slug::SlugError>(())
Truncation And Empty Output
max_slug_chars counts Unicode scalar values. A cut never separates a kept
character from the combining marks after it — that character is dropped whole —
and any trailing delimiter the cut exposes is then stripped, including a
trailing dot under PreserveDotsBetweenDecimalDigits. A filesystem or URL
length limit is usually counted in bytes, and a scalar takes up to four UTF-8
bytes (twelve characters once percent-encoded), so size the cap for the unit
the limit counts.
Empty handling runs after truncation. A fallback is inserted as written rather
than run through the pipeline, but UseFallbackSlug still requires it to be a
value this configuration could have produced — character set, delimiter, dot
policy, case and length. Otherwise an ASCII-only, length-capped configuration
could return an arbitrary Unicode string and report it as validated.
UseVerbatimFallbackSlug waives that for a value that has to match something
already stored, and checks only the target surface. Either fallback must be
nonempty, and both are checked before any input is read, so a broken fallback
fails on the first call rather than on the first empty slug.
use agent_first_slug::{slugify, EmptyOutputPolicy, SlugConfig, SlugError};
let truncated = SlugConfig {
max_slug_chars: Some(8),
..SlugConfig::default()
};
let fallback = SlugConfig {
max_slug_chars: Some(8),
empty_output_policy: EmptyOutputPolicy::UseFallbackSlug("untitled".to_string()),
..SlugConfig::default()
};
let legacy = SlugConfig {
max_slug_chars: Some(8),
empty_output_policy: EmptyOutputPolicy::UseVerbatimFallbackSlug(
"Legacy Name".to_string(),
),
..SlugConfig::default()
};
assert_eq!(slugify("Long Example", &truncated)?.slug, "long-exa");
assert_eq!(slugify("!!!", &fallback)?.slug, "untitled");
assert_eq!(slugify("!!!", &legacy)?.slug, "Legacy Name");
// Too long for this configuration's own budget, so it is refused — here for
// an input that never needed the fallback.
let over_budget = SlugConfig {
empty_output_policy: EmptyOutputPolicy::UseFallbackSlug("far-too-long".to_string()),
..fallback
};
assert!(matches!(
slugify("hello", &over_budget),
Err(SlugError::FallbackViolatesConfig { .. })
));
# Ok::<(), agent_first_slug::SlugError>(())
The replacement_delimiter is held to the same standard: one the character
set keeps, a dot that a dot policy preserves, or a character lowercasing would
change is refused (SlugError::AmbiguousReplacementDelimiter) before any input
is read, because a delimiter indistinguishable from typed text lets two
different inputs collapse into one slug.
Generate Slugs From The CLI
# prebuilt binary
brew install agentfirstkit/tap/afslug # macOS / Linux
scoop bucket add agentfirstkit https://github.com/agentfirstkit/scoop-bucket && scoop install afslug # Windows
# or from crates.io
cargo install agent-first-slug
Prebuilt archives are also available from GitHub Releases.
afslug slugify runs the same pipeline and emits one AFDATA protocol event.
JSON is the default; --output yaml and --output plain render the same
event.
afslug slugify "Hello, 世界!"
# {"kind":"result","result":{"changed_from_input":true,"code":"slugify","slug":"hello-世界"},"trace":{}}
afslug slugify "Hello, World!" --output plain
# kind=result result.changed_from_input=true result.code=slugify result.slug=hello-world trace={}
afslug slugify "Ubuntu 16.04" --charset unicode-letters-digits --dots preserve-between-digits --validation url-path
# {"kind":"result","result":{"changed_from_input":true,"code":"slugify","slug":"ubuntu-16.04"},"trace":{}}
Each flag sets one SlugConfig field, and an omitted flag leaves the field at
its SlugConfig::default() value:
| Flag | Field | Default |
|---|---|---|
--delimiter <CHAR> | replacement_delimiter | - |
--no-lowercase | lowercase_enabled: false | lowercase |
--max-chars <N> | max_slug_chars | no cap |
--charset unicode-alphanumeric|ascii-alphanumeric|unicode-letters-digits|unicode-letters-marks-digits | allowed_character_set | unicode-alphanumeric |
--dots replace|preserve|preserve-between-digits | dot_handling_policy | replace |
--validation none|local-path|url-path | validation_policy | none |
--fallback <SLUG> / --fallback-verbatim <SLUG> | UseFallbackSlug / UseVerbatimFallbackSlug | keep an empty slug |
For input beginning with -, put all options before -- and supply the input
after it, as in afslug slugify --output plain -- "-x". A cap of
--max-chars 0 forces the empty-output policy. A nonempty strict fallback
cannot fit that cap, while a verbatim fallback still follows the selected
target-surface policy.
The two fallback flags are separate registered shapes, so passing both is
refused as cli_unregistered_combination. Transliteration is library-only: its
static replacement map cannot be built from arguments.
A rule the configuration or the value breaks is an AFDATA error event whose
error.code is the rule’s name:
error.code | Exit | Raised when |
|---|---|---|
ambiguous_replacement_delimiter, fallback_violates_config, empty_fallback_slug | 2 | the flags describe a configuration that is refused for every input |
empty_path_segment, path_segment_separator, path_segment_whitespace, path_segment_control_character, path_segment_dot_value, url_path_segment_reserved_character | 1 | the slug, or the value given to validate, fails the selected surface |
Argument errors the parser catches — an unknown flag, a --delimiter longer
than one character, a mix of flags no shape registers — exit 2 with a cli_*
code. Under the default --output-to split, results go to stdout and errors to
stderr; --output-to stdout puts both on stdout, except a cli_* rejection,
which is decided before the routing flag is read and always goes to stderr.
docs/cli.md is the full generated reference, and
afslug <command> --help returns every shape of a command in one call.
Validate An Existing Value
To check a value you did not generate — a stored slug, a name from a request — validate it against a surface without running the pipeline:
use agent_first_slug::{validate_slug, SlugError, SlugValidationPolicy};
assert_eq!(validate_slug("safe-name", SlugValidationPolicy::LocalPathSegment), Ok(()));
assert_eq!(
validate_slug("a/b", SlugValidationPolicy::LocalPathSegment),
Err(SlugError::PathSegmentSeparator { character: '/' })
);
assert_eq!(validate_slug("a?b", SlugValidationPolicy::LocalPathSegment), Ok(()));
assert_eq!(
validate_slug("a?b", SlugValidationPolicy::UrlPathSegment),
Err(SlugError::UrlPathSegmentReservedCharacter { character: '?' })
);
afslug validate "my-slug" --policy url-path
# {"kind":"result","result":{"code":"validate","valid":true,"value":"my-slug"},"trace":{}}
afslug validate "a?b" --policy url-path
# {"error":{"code":"url_path_segment_reserved_character","message":"URL path segment must not contain reserved character `?`","retryable":false},"kind":"error","trace":{}}
--policy defaults to local-path. A valid value is a result with
valid: true; an invalid one is an error event that exits 1 — there is no
valid: false result to look for. Validation checks the surface only, not
whether some configuration could have produced the value.
Agent Skill
skills/agent-first-slug/SKILL.md teaches a
coding agent when to embed the library or run afslug, and how to keep
existing identifiers stable. afslug skill install installs it.
Upgrading
Rust matches that bind the old reason field on FallbackViolatesConfig or
AmbiguousReplacementDelimiter should use rule: GeneratedSlugRule or
conflict: DelimiterConflict, respectively. The CLI error codes are unchanged.
Changing the delimiter, case, transliteration, dots, character set or
truncation changes slugs, and so can an upgrade. If slugs are already stored,
run the old and new versions over your corpus and diff before upgrading. Each
release that changes output says so in the
release notes. Nothing
normalizes input: canonically equivalent text (a precomposed é and e plus a
combining accent) gives different slugs, so normalize first if stability
across input methods matters.