TypeAgent / ts
CLAUDE.md745 starsChanged 5 months agoMITView on GitHub
A fresh checkout of this repo — a new clone, a git worktree (each Copilot CLI session gets its own), or a cloud/container workspace — has the committed files but not the gitignored files that let the repo install and run. Those must be provisioned once. From ts/: On a brand-new machine where pnpm isn't cached yet, pnpm run setup can't bootstrap itself (corepack would try to fetch pnpm from the blocked public registry). Start with the pnpm-free entrypoint instead…
- Reads credentials
- Installs packages
In this repository11 other files it gives its agents.
- ts/packages/agents/onboarding/AGENTS.mdAGENTS.md
- ts/packages/typeagent-core/AGENTS.mdAGENTS.md
- ts/packages/typeagent-studio/AGENTS.mdAGENTS.md
- ts/examples/planValidationDemo/CLAUDE.mdCLAUDE.md
- ts/packages/agents/powershell/CLAUDE.mdCLAUDE.md
- ts/packages/agents/taskflow/CLAUDE.mdCLAUDE.md
- dotnet/autoShell/.github/copilot-instructions.mdCopilot instructions
- .github/copilot-instructions.mdCopilot instructions
- typeagent-memorySkill
- typeagent-macrosSkill
- typeagent-setupSkill
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
18 rules. About 0 are common, 8 are distinctive, and 10 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈8
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 42
Never build or run before setup has provisioned ts/.npmrc: the first pnpm command otherwise hits the blocked public npm registry.
- Very specific: line 102
Do not rely on a bare npx prettier for validation — always use the repo's pinned version (node_modules/.bin/prettier, pnpm exec prettier, …
- Distinctive: line 181
API / embedding / LLM cost is not a constraint: Don't gate features on token budget, don't apologize for "5× embedding cost," don't add …
- Very specific: line 192
Every .ts/.js file must start with:
- Distinctive: line 200
Write comments in plain, direct language.
- Very specific: line 205
Don't use em-dashes (—) in comments.
- Very specific: line 226
Test timeout: 90 seconds (configured in root jest.config.js)
- Distinctive: line 237
Use these criteria both when writing changes and when reviewing code (your own or a diff you are asked to review).
- Distinctive: line 247
Clarity first: Prefer straightforward, self-explanatory code over clever one-liners.
- Distinctive: line 264
Clean up as you go: Remove stale comments and tests that reference relocated or deleted code.
- Distinctive: line 271
When two implementations of the same logic diverge (even slightly), extract one shared helper and route both callers through it — divergent …
- Distinctive: line 274
Before adding a new helper, check whether an existing utility already covers it (search the package and its workspace dependencies).
- Very specific: line 290
Every .ts/.js file must carry the Microsoft copyright header.
- Distinctive: line 300
Prefer the simplest design that satisfies the requirement.
- Very specific: line 310
When a temporary workaround is genuinely needed, make it opt-in and self-deleting: gate it behind an explicit flag/option and add a TODO to …
- Very specific: line 314
Before adding a new error path or constraint, confirm the existing intended behavior from the relevant docs/architecture doc and …
- Very specific: line 320
Check edge cases, error/exception paths, async/await correctness, and resource cleanup.
- Very specific: line 340
Avoid duplicate coverage: check whether existing tests already cover the behavior, and prefer shared/parameterized harnesses (e.g., …
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
TypeAgent — AI Assistant Instructions
First-run setup (fresh checkout)
A fresh checkout of this repo — a new clone, a git worktree (each Copilot CLI
session gets its own), or a cloud/container workspace — has the committed files
but not the gitignored files that let the repo install and run. Those must be
provisioned once. From ts/:
pnpm run setup # provision .npmrc + config.local.yaml, then install
pnpm run setup --build # same, plus a full build at the endOn a brand-new machine where pnpm isn't cached yet, pnpm run setup can't
bootstrap itself (corepack would try to fetch pnpm from the blocked public
registry). Start with the pnpm-free entrypoint instead — it provisions .npmrc
(which also seeds corepack's pnpm) before it uses pnpm:
node tools/scripts/setupWorktree.mjssetup does not build by default — a full build of every package is
redundant for most sessions. fluid-build is incremental and dependency-aware,
so build just the package you touch, on demand (pnpm run build <package>). Use
--build only when you want a full build warmed up front.
Order matters, and setup handles it:
ts/.npmrcpoints pnpm at the internal Azure Artifacts feed. It must exist beforepnpm install, or pnpm/corepack reach the (blocked) public npm registry and install fails.setupcopies it from the main checkout when available; if it can't, setup runsnode tools/scripts/getNPMRC.mjsautomatically (fetches only an npm token, no secrets, and seeds corepack's pnpm — invoked via node so it works before pnpm is available).pnpm install.ts/config.local.yamlholds API keys.setupcopies it from the main checkout when available; if it can't, setup warns and continues (only running the app needs keys) and prints thepnpm run getKeyscommand.
Never build or run before setup has provisioned ts/.npmrc: the first pnpm
command otherwise hits the blocked public npm registry.
setup auto-provisions .npmrc (copy, else getNPMRC) but treats
config.local.yaml differently: it only copies it and never runs getKeys
itself, because getKeys signs in to Azure and fetches secrets (it can open a
browser sign-in). Agent: never run getKeys automatically. Ask the user
first and run it only after they approve, or let the user run it.
Build & Test
This is a pnpm monorepo rooted at ts/. All commands run from the ts/ directory.
# Install & build
pnpm i
pnpm run build # Uses fluid-build to build all packages
pnpm run build <directory> # Uses fluid-build to build directory (and dependencies)
pnpm run build <package name regexp> # Uses fluid-build to build a package which name matches the regexp (and dependencies)
pnpm run build:shell # Build only the shell app and its dependencies
# Clean
pnpm run clean # works at the root and per package
# Test
pnpm run test:local # All unit tests (*.spec.ts) across packages
pnpm run test:live # Integration tests (*.test.ts) — requires API keys
pnpm run test # Both local + live + shell tests
# Run tests for a single package
pnpm --filter <package-name> test
# e.g., pnpm --filter action-grammar test
# Run a single test file (cd into the package directory first)
# The jest-esm script wraps `node --experimental-vm-modules jest` — use it
# instead of invoking node/jest directly.
pnpm run jest-esm --testPathPattern="merge.spec.js"
# Run a single test by name (cd into the package directory first)
pnpm run jest-esm --testNamePattern="your test name"
# Lint
pnpm run prettier # Check formatting
pnpm run prettier:fix # Fix formattingTests run against compiled output in dist/test/ — you must build before running tests.
Before considering any change complete, ensure the affected build, relevant tests, formatting check, complexity ratchet, and lint ratchet all pass. CI enforces these separately, so it is easy to miss them if you only build and test:
pnpm run build <package>
pnpm --filter <package-name> test
pnpm run prettier:changed:fix # Fix formatting for files changed vs origin/main (matches CI's check)
pnpm run code-complexity:ci # Complexity ratchet against origin/main
pnpm run code-lint -- --ratchet --base origin/mainDo not rely on a bare npx prettier for validation — always use the repo's pinned version
(node_modules/.bin/prettier, pnpm exec prettier, or npx prettier@<version from package.json>),
since a newer/older Prettier version can produce spurious reformatting diffs.
PR-only gates: build and tests passing is not enough
build-ts.yml runs four ratchets that only fire on pull requests, so they are
invisible until CI fails. Each compares the files your change touches against
the base branch. Run all four before calling a change done:
npm run code-lint -- --ratchet --base origin/main # no new eslint violations
npm run code-complexity -- --ratchet --base origin/main --cyclomatic 25 --cognitive 30 \
--new-file-cyclomatic 25 --new-file-cognitive 30
npm run code-circular -- --ratchet --base origin/main \
--exceptions-file tools/scripts/code/circular-baseline-exception.json
npm run code-debt -- --gate --base origin/main # no .only / newly skipped testsThe lint ratchet bites most often, usually on no-explicit-any. A new file
counts entirely as added violations, so a new module written with any fails
even though it changed nothing that existed before. Prefer unknown with a
narrow cast where the value is actually used.
Nothing outside ts/ is checked at all — not by these ratchets, not by
prettier:changed, and no CI job builds the Kotlin under android/. Verify
those files by hand (cd android/samples/mobile-2 && ./gradlew assembleDebug
testDebugUnitTest) and read the final diff, since formatting mistakes there
reach main unchallenged.
Architecture
TypeAgent is a personal agent that routes natural language requests to specialized application agents (plugins). The core flow is:
User input → Grammar matcher → Typed action → Dispatcher → Agent handler → ActionResultDetail architecture descriptions are located in the docs/architecture directory.
Key packages
packages/dispatcher/— Core routing engine. Matches user input to agents and dispatches typed actions.packages/agentSdk/— Interface definitions (AppAgent) that all agents must implement.packages/actionSchema/— Parses TypeScript action types into JSON Schema for validation.packages/actionGrammar/— NFA/DFA compiler that converts.agrgrammar files into matchers for natural language understanding.packages/cache/— Caches action translations to minimize LLM calls.packages/knowPro/— Structured RAG implementation for conversational memory.packages/agents/— All application agents (player, calendar, email, list, browser, etc.).packages/shell/— Electron GUI app.packages/cli/— Console app (connected-mode only; all commands route throughagent-servervia WebSocket RPC).
Agent plugin structure
Each agent follows this layout:
packages/agents/<name>/src/
<name>Manifest.json # Agent metadata, schema pointers, emoji
<name>Schema.ts # TypeScript action/activity type definitions
<name>Schema.agr # Grammar rules (NL patterns → structured actions)
<name>ActionHandler.ts # Implements instantiate(): AppAgentAgents export an instantiate() function returning an AppAgent object. The dispatcher calls executeAction(action, context) with already-validated, typed actions — agents never parse natural language directly.
Dispatcher ↔ Agent interface
Agents implement AppAgent from @typeagent/agent-sdk:
initializeAgentContext()— One-time setupupdateAgentContext()— Enable/disable per sessionexecuteAction(action, context)— Handle a typed action, returnActionResult- Optional:
handleChoice(),resolveEntity(),getActionCompletion(),getDynamicDisplay()
Conventions
Engineering tradeoffs
- API / embedding / LLM cost is not a constraint. Don't gate features on token budget, don't apologize for "5× embedding cost," don't add cost-saving caveats unless the user asks for them. If the right experiment runs every embedding twice or every LLM call three times, that's fine.
Code style
- 4-space indentation for TypeScript/JavaScript, 2-space for JSON
- LF line endings
- Prettier for formatting (no
.prettierrc— uses defaults) - Every
.ts/.jsfile must start with:// Copyright (c) Microsoft Corporation. // Licensed under the MIT License.
Comments
- Write comments in plain, direct language. Say what the code does and why. Avoid "consultant speak" - filler like "owns its own X," "single source of truth," "never has to know about Y," or restating a design principle instead of explaining the code. Technical terms are fine; use the precise word rather than talking around it.
- Don't use em-dashes (—) in comments. Use
-,:, parentheses, or two sentences instead.
Package references
- Internal packages use
"workspace:*"protocol inpackage.json - Build is orchestrated by
fluid-buildat the workspace root; individual packages usetsc -b - TypeScript targets ES2021, module system is Node16, strict mode enabled
File types
.ts/.mts— TypeScript source (.mtsfor ES module contexts).agr— Grammar rule definitions (natural language patterns for action matching).ag.json— Compiled grammar output.pas.json— Grammar metadata for schema-to-grammar generation
Testing conventions
- Unit tests:
test/*.spec.ts→ run viatest:local - Integration tests:
test/*.test.ts→ run viatest:live(require API keys) - Tests compile to
dist/test/and Jest runs against the compiled JS - Test timeout: 90 seconds (configured in root
jest.config.js)
Environment
- Requires Node ≥22, pnpm ≥10
- API keys go in
ts/config.local.yaml(seeconfig.sample.yamlfor reference). Legacy.envis still supported but deprecated. - User data stored in
~/.typeagent/ - Tracing via the
debugpackage — enable withDEBUG=typeagent:*env var
Code Review Guidelines
Use these criteria both when writing changes and when reviewing code (your
own or a diff you are asked to review). Report only high-confidence, substantive
issues — prefer a short list of real problems over an exhaustive nitpick list. For
each issue, name the file/line, explain why it matters, and suggest a concrete
fix. Do not comment on formatting that Prettier already enforces. Formatting in
files Prettier does not cover (anything outside ts/, notably Kotlin under
android/) is fair game — nothing else will catch it.
Readability & maintainability
- Clarity first. Prefer straightforward, self-explanatory code over clever one-liners. A reader should be able to follow the intent without reverse-engineering it.
- Meaningful names. Names should describe intent (
isSchemaEnabled, notflag). Match the vocabulary already used in the surrounding module. - Small, focused units. Functions should do one thing. Flag deeply nested logic, long parameter lists, and functions that mix unrelated concerns — suggest extracting a helper.
- Comment the "why," not the "what." Per repo style, only comment code that needs clarification (non-obvious intent, workarounds, invariants). Remove redundant comments that merely restate the code. Comment intent accurately — distinguish a temporary NYI (TODO) from a fundamental limitation.
- Clear signatures. Order parameters so common callers rely on defaults, make
optional callbacks optional, and drop dead/unused parameters instead of threading
constants through. This extends to whole members: an added function or property
with no caller is dead code unless it is deliberate public API of a published
package (
agentSdkand friends). Nothing warns about an unused public member, so review is the only thing that catches it. - Clean up as you go. Remove stale comments and tests that reference relocated or deleted code.
DRY — avoid redundancy
- Flag copy-pasted logic, duplicated constants/literals, and parallel code paths that should share a single implementation.
- When two implementations of the same logic diverge (even slightly), extract one shared helper and route both callers through it — divergent copies drift and cause bugs. Aim for a single source of truth.
- Before adding a new helper, check whether an existing utility already covers it (search the package and its workspace dependencies). Reuse over reinvention.
- Balance DRY against clarity — don't over-extract. A small, incidental duplication is preferable to a premature or leaky abstraction that couples unrelated call sites, and a helper with a single real caller — or one that forces the reader to jump away to follow otherwise-simple logic — is a code smell; inline it.
Consistency with the codebase
- New code should follow the conventions of the surrounding context and the
broader codebase: file layout, naming, error-handling patterns, import style,
and the
AppAgent/ dispatcher contracts described above. - Reuse established patterns (e.g., the agent plugin structure,
ActionResultreturn shapes,debug-based tracing) instead of introducing new ones without justification. - Every
.ts/.jsfile must carry the Microsoft copyright header. Internal dependencies useworkspace:*. - Match the established file-naming pattern of the area (e.g., grammar matcher
tests are
grammarMatcher<Name>.spec.ts).
Abstractions & design
- Abstractions should have a clear, single responsibility and hide the right details. Flag leaky abstractions, unnecessary indirection, and over-engineering (interfaces/layers with a single implementation and no foreseeable second one).
- Prefer the simplest design that satisfies the requirement. Don't add configurability, generality, or extension points that aren't needed yet.
- Watch module boundaries: respect package dependency direction and avoid reaching into another package's internals.
Root-cause fixes & workarounds
- Fix the underlying cause rather than routing around a not-yet-implemented (NYI) gap by weakening defaults or disabling a feature. Prefer making an unsupported path work over changing a default to avoid triggering it.
- When a temporary workaround is genuinely needed, make it opt-in and
self-deleting: gate it behind an explicit flag/option and add a
TODOto remove it once the root fix lands. A workaround baked into a default reads as the intended long-term design. - Before adding a new error path or constraint, confirm the existing intended
behavior from the relevant
docs/architecturedoc and surrounding code — don't over-constrain a previously-valid case, and keep code and docs in sync.
Correctness & robustness
- Check edge cases, error/exception paths,
async/awaitcorrectness, and resource cleanup. Remember that some constructors (e.g., embedding-model creation) can throw rather than returnundefined— guard construction, not just the call. - Validate inputs at trust boundaries; agents receive already-typed, validated actions, so avoid re-parsing natural language in handlers.
- Validate invariants once, early, and unconditionally — hoist a distinct check (e.g., rejecting an unsupported shape) to a single location rather than mixing it into unrelated logic, which conflates concerns and yields differently-worded errors depending on which branch is hit.
- Distinguish user-facing validation errors from internal invariant errors ("should never happen") so the latter aren't mistaken for user mistakes.
Test coverage
- New or changed behavior should be covered by tests. Unit tests are
test/*.spec.ts(run offline viatest:local); live/integration tests aretest/*.test.ts(test:live, require API keys). - Tests must exercise meaningful behavior and edge cases, not just the happy path, and should assert on outcomes rather than restating the implementation.
- Avoid duplicate coverage: check whether existing tests already cover the behavior,
and prefer shared/parameterized harnesses (e.g.,
describeForEachMatcher, which runs a case across AST/NFA/DFA) so behavior is verified across all variants. Assert on actual error messages, not guessed substrings. - Remember tests run against compiled output in
dist/test/— build before running, and after switching branches runpnpm run cleanfirst to purge stale compiled specs.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

