Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
123 commits
Select commit Hold shift + click to select a range
11c19f5
fix(repo-map): detect nested Next.js router roots
profmohit-edu Sep 14, 2026
0e48c7b
test(repo-map): cover src and monorepo Next.js routes
profmohit-edu Sep 14, 2026
f0d3f55
fix: harden nested Next.js route normalization
profmohit-edu Sep 14, 2026
feaf079
fix(recommender): correct cached-token double-counting
PREMRAJESH Sep 15, 2026
19614ff
fix(scanner): classify generated assets correctly
Divyanshu-2907 Sep 15, 2026
c6a7971
fix(dashboard): protect saved report reads
Divyanshu-2907 Sep 15, 2026
3ec8547
fix(recommender): honor preferredModelIds when breaking recommendatio…
Divyanshu-2907 Sep 15, 2026
dabcb34
fix(recommender): thread preferredModelIds into generateAgentRules tool
Divyanshu-2907 Sep 15, 2026
c75510d
fix(cli): surface malformed workspace config (#28)
profmohit-edu Sep 15, 2026
90025ce
fix(scanner): honor ignore rules for symlinked files (#35)
profmohit-edu Sep 15, 2026
d3d7c77
fix(repo-map): preserve generated-file metadata after exclusion (#23)
Divyanshu-2907 Sep 15, 2026
47cbafc
Run CI for Development pull requests
krishika08 Sep 15, 2026
48e6f8e
fix(recommender): validate workspaceTokens, budget and outputTokens i…
Kailashsharma282 Sep 15, 2026
6d38403
fix(tokenizers): parse file extension via path.extname
Kailashsharma282 Sep 15, 2026
69ef6b1
fix(repo-map): validate tokenBudget is finite and positive
Kailashsharma282 Sep 15, 2026
cf73bb7
fix(model-catalog): only fallback on ENOENT, rethrow corrupt catalog …
Kailashsharma282 Sep 15, 2026
a265754
fix(cli): surface recommendation errors in report warnings
Kailashsharma282 Sep 15, 2026
13b51dc
fix(recommender): guard divide-by-zero for empty workspaces
Kailashsharma282 Sep 15, 2026
96dafb6
fix(jetbrains): persist plugin settings across restarts
profmohit-edu Sep 16, 2026
39fb1db
fix(vscode): stop advertising virtual workspace support
profmohit-edu Sep 16, 2026
5f7265b
fix(catalog): remove existsSync precheck, surface corrupt catalog err…
Kailashsharma282 Sep 16, 2026
fcf7304
fix(catalog): add strict option for required loads
Kailashsharma282 Sep 16, 2026
1a31523
test(cli): add end-to-end team.json coverage for preferredModelIds
Divyanshu-2907 Sep 16, 2026
aa50d97
fix(scanner): block path traversal in additionalIgnoreFiles (#48)
Kailashsharma282 Sep 16, 2026
12a9b9b
fix(mcp-server): add timeout to workspace scan tool (#53)
Kailashsharma282 Sep 16, 2026
34d22ff
fix(scanner): scan full file text for secrets, not just 4KB preview (…
Kailashsharma282 Sep 16, 2026
84f485c
test(jetbrains): cover settings restoration and defaults
profmohit-edu Sep 16, 2026
d44eae7
fix(vscode): block virtual workspaces with actionable message
profmohit-edu Sep 16, 2026
26ae654
test(vscode): cover non-file workspace rejection
profmohit-edu Sep 16, 2026
17428f5
fix(recommender): enforce local execution in local-first mode (#31)
profmohit-edu Sep 16, 2026
4a59138
test(jetbrains): round-trip settings through XML
profmohit-edu Sep 16, 2026
b5eb13e
fix(scanner): honor nested gitignore rules
profmohit-edu Sep 17, 2026
938b0be
test(scanner): cover nested gitignore scoping
profmohit-edu Sep 17, 2026
9ab48fb
fix(scanner): distinguish SQL source from dumps
profmohit-edu Sep 17, 2026
20925a7
fix(scanner): invalidate stale SQL classifications
profmohit-edu Sep 17, 2026
e6eb154
test(scanner): cover SQL source classification
profmohit-edu Sep 17, 2026
47a046a
test(scanner): rebuild stale SQL classification cache
profmohit-edu Sep 17, 2026
debf39c
fix(repo-map): require Next project signals for routes
profmohit-edu Sep 17, 2026
e0f162a
test(repo-map): reject non-Next app routes
profmohit-edu Sep 17, 2026
e6dc80c
fix(reports): preserve scan insights without recommendations
profmohit-edu Sep 17, 2026
cbfce40
fix(reports): align Markdown folder token totals
profmohit-edu Sep 17, 2026
8f3717d
test(reports): cover scan-only JSON insights
profmohit-edu Sep 17, 2026
c1273e8
test(reports): compare JSON and Markdown folder totals
profmohit-edu Sep 17, 2026
9b9f220
docs(scanner): explain SQL dump heuristic
profmohit-edu Sep 17, 2026
488a0b7
test(scanner): expand SQL dump heuristic cases
profmohit-edu Sep 17, 2026
57e1694
test(scanner): prove nested ignores stay out of repo maps
profmohit-edu Sep 17, 2026
34dd006
docs(scanner): define ignore precedence
profmohit-edu Sep 17, 2026
db1745f
feat(reports): add workspace token drift and trend analyzer with poli…
Kailashsharma282 Sep 17, 2026
2017624
feat(agent-rules): support Windsurf, GitHub Copilot, and Gemini multi…
Kailashsharma282 Sep 17, 2026
0dc622b
feat(tokenizers): implement heuristic AST token density estimator and…
Kailashsharma282 Sep 17, 2026
5f6a34a
feat(repo-map): implement progressive 4-stage context compaction engine
Kailashsharma282 Sep 17, 2026
f631a0e
feat(mcp-server): add estimate_files_tokens batch inspection and cont…
Kailashsharma282 Sep 17, 2026
bcc2c8b
feat(recommender): add cost optimization and model switching advisor …
Kailashsharma282 Sep 17, 2026
f8d55d8
feat(scanner): add git-status porcelain parser and staged-files scann…
Kailashsharma282 Sep 17, 2026
34403ff
feat(model-catalog): add declarative semantic query and filtering engine
Kailashsharma282 Sep 17, 2026
da063de
feat(cli): add interactive workspace config init wizard
Kailashsharma282 Sep 17, 2026
0ab8bf2
fix(recommender): honor preferredModelIds when breaking recommendations
Sandesh13fr Sep 18, 2026
59add98
Merge pull request #47 from Kailashsharma282/up/recommender-input-val…
Sandesh13fr Sep 18, 2026
139a3c2
Merge pull request #49 from Kailashsharma282/up/tokenizer-extension-p…
Sandesh13fr Sep 18, 2026
e6ab25a
Merge pull request #50 from Kailashsharma282/up/repo-map-budget-valid…
Sandesh13fr Sep 18, 2026
17a216c
Merge pull request #51 from Kailashsharma282/up/catalog-error-handling
Sandesh13fr Sep 18, 2026
f90df75
Merge pull request #52 from Kailashsharma282/up/cli-report-error-surface
Sandesh13fr Sep 18, 2026
913ccd8
Merge pull request #55 from Kailashsharma282/up/recommender-zero-cont…
Sandesh13fr Sep 18, 2026
b55fa31
Merge pull request #59 from profmohit-edu/osci/44-virtual-workspaces
Sandesh13fr Sep 18, 2026
80e5d6f
Merge pull request #58 from profmohit-edu/osci/39-jetbrains-settings
Sandesh13fr Sep 18, 2026
039d1ff
Merge pull request #24 from profmohit-edu/fix/19-preserve-scan-insigh…
Sandesh13fr Sep 18, 2026
1f514c0
Merge pull request #25 from profmohit-edu/fix/18-nextjs-nested-routes
Sandesh13fr Sep 18, 2026
9448c76
Merge pull request #26 from profmohit-edu/profmohit/nested-gitignore-…
Sandesh13fr Sep 18, 2026
775869b
Merge pull request #32 from profmohit-edu/profmohit/sql-source-not-dump
Sandesh13fr Sep 18, 2026
1f5b509
Merge pull request #46 from krishika08/fix/ci-development-pr
Sandesh13fr Sep 18, 2026
0707b96
Merge pull request #60 from Kailashsharma282/feat/workspace-drift-ana…
Sandesh13fr Sep 18, 2026
3093518
Merge pull request #62 from Kailashsharma282/feat/agent-rules-multi-f…
Sandesh13fr Sep 18, 2026
6e263b5
Merge pull request #63 from Kailashsharma282/feat/ast-token-density-e…
Sandesh13fr Sep 18, 2026
84e8783
Merge pull request #64 from Kailashsharma282/feat/context-window-comp…
Sandesh13fr Sep 18, 2026
e0cf7a3
Merge pull request #66 from Kailashsharma282/feat/mcp-batch-tokens-tool
Sandesh13fr Sep 18, 2026
4247c40
Merge pull request #68 from Kailashsharma282/feat/model-cost-optimizer
Sandesh13fr Sep 18, 2026
8cdfaeb
Merge pull request #69 from Kailashsharma282/feat/scanner-git-status-…
Sandesh13fr Sep 18, 2026
ad8d49a
Merge pull request #71 from Kailashsharma282/feat/model-catalog-query…
Sandesh13fr Sep 18, 2026
6810206
Merge pull request #74 from Kailashsharma282/feat/cli-init-config-wizard
Sandesh13fr Sep 18, 2026
9972d26
fix(reports): read scan totals from totalEstimatedTokens
sgoel2be24-cyber Sep 22, 2026
c62b1ac
fix(agent-rules): return valid mode and token budget
sgoel2be24-cyber Sep 22, 2026
b6fb1f0
fix(cli): stop init from writing a dangling schema
sgoel2be24-cyber Sep 22, 2026
7a90cd2
test(vscode): implement onDidChangeFile on virtual provider
sgoel2be24-cyber Sep 22, 2026
05fe051
test(scanner): assert current scan cache version
sgoel2be24-cyber Sep 22, 2026
38acf45
fix(scanner): match git-status paths on segment boundaries
sgoel2be24-cyber Sep 22, 2026
5f95d35
test(cli): fix nested-ignore assertion to sum all non-generated file …
jasonjose007 Oct 1, 2026
6a836fe
fix(mcp-server): use shared tokenizer for estimate_files_tokens (#108)
sageofninetale Oct 1, 2026
24039d4
Validate model-catalog pagination inputs
chykB Oct 2, 2026
852b98e
Merge pull request #142 from chykB/fix/model-catalog-pagination-103
Sandesh13fr Oct 3, 2026
b46c856
fix(cli): escape Markdown scan output
rithishkumarab-cs Oct 4, 2026
7fd7c2d
Merge pull request #161 from rithishkumarab-cs/issue-152-escape-markdown
Sandesh13fr Oct 5, 2026
ffdc5b9
fix(recommender): report absolute added spend for a free baseline
qiqqqqq517 Oct 5, 2026
3797d30
Merge pull request #180 from qiqqqqq517/fix/174-free-baseline-tradeoff
Sandesh13fr Oct 5, 2026
cd10b80
fix(recommender): validate estimateCost token counts are finite and n…
sgoel2be24-cyber Oct 7, 2026
eafc28e
fix(vscode): handle multi-root workspaces explicitly (#181)
sivaadithya25 Oct 11, 2026
ec499f8
fix(repo-map): parse comma-separated Python imports (#183)
kspraveen-07 Oct 11, 2026
6cc7cdf
fix(repo-map): support JS/TS module extensions (#187)
teajas14 Oct 11, 2026
a822da0
fix(core): reject blank active team-policy profiles and whitespace pr…
shrinivas-sn Oct 11, 2026
a448483
fix(repo-map): preserve control-flow blocks during compaction (#184)
CristonInfantoRex Oct 11, 2026
381a8d5
fix(recommender): recommend only genuinely cheaper candidates (#185)
ZarrarPeshimam Oct 11, 2026
8e79591
fix(vscode): preserve repo map save flow on fallback (#170)
shivanimourya2 Oct 11, 2026
811d5b8
fix(dashboard): update Next.js without unrelated dependency upgrades …
MMeghana8 Oct 11, 2026
139199c
docs: welcome and guide first-time contributors
Oct 11, 2026
73a42a7
Merge pull request #190 from Sandesh13fr/codex/first-timer-onboarding
Sandesh13fr Oct 11, 2026
9705340
docs(readme): note Node.js 22 and pnpm 11.5.2 prerequisites
ArthurJosephLawson Oct 11, 2026
fa15f51
fix: standardize language breakdown percentages
SherlinJeri Oct 11, 2026
3ecaa92
Merge pull request #192 from ArthurJosephLawson/docs/readme-build-pre…
Sandesh13fr Oct 12, 2026
de9282d
fix(reports): escape token drift Markdown values
shrinivas-sn Oct 13, 2026
2f68efb
fix(mcp): preserve overflow warnings in compact recommendations
kspraveen-07 Oct 13, 2026
5fc8b66
ci: trigger required PR checks
SherlinJeri Oct 14, 2026
4f29d70
Merge pull request #201 from shrinivas-sn/fix/drift-markdown-151
Sandesh13fr Oct 14, 2026
309bda2
Merge branch 'Development' into fix/mcp-overflow-warnings
Sandesh13fr Oct 14, 2026
98eaf7f
Merge branch 'Development' into fix/language-breakdown-percentage
Sandesh13fr Oct 14, 2026
b6e7dc0
Merge pull request #202 from kspraveen-07/fix/mcp-overflow-warnings
Sandesh13fr Oct 14, 2026
64e56ed
Merge branch 'Development' into fix/language-breakdown-percentage
Sandesh13fr Oct 14, 2026
0fa3638
Merge pull request #193 from SherlinJeri/fix/language-breakdown-perce…
Sandesh13fr Oct 14, 2026
ee7f72d
fix(agent-rules): preserve model recommendations in all formats (#248)
sowmiya120607-create Nov 13, 2026
5d56395
fix(mcp): explicit goal wins over team policy defaultGoal (#204)
vishalhabib99 Nov 13, 2026
879a6d6
feat(cli): add common usage examples to help (#109)
Ananyapselvam Nov 13, 2026
06f6090
fix(recommender): validate cost advisor inputs (#199)
Pranitha06sri Nov 13, 2026
1027d63
Merge main into Development to prepare release to main
Nov 13, 2026
f59e93a
fix(cli): stop catalog tests failing as the bundled catalog ages (#266)
Sandesh13fr Nov 13, 2026
004ca2a
Merge remote-tracking branch 'origin/Development' into release/develo…
Nov 13, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Explain the problem, the approach, and any user-visible behavior. Link the issue
## Contribution prerequisite

- [ ] I starred the [TCalc repository](https://github.com/Sandesh13fr/TCalc) before starting this contribution.
- [ ] I checked the issue and existing PRs for overlapping work. I understand that assignment is not required and any contributor may propose a focused solution.
- [ ] The linked issue is assigned to me, and this is my only open PR (drafts included).
- [ ] This PR targets the `Development` branch (unless a maintainer explicitly approved another base).

## Affected areas
Expand All @@ -31,6 +31,7 @@ List the exact commands run and their results. If a relevant check was not run,
- [ ] `pnpm test`
- [ ] `pnpm lint`
- [ ] `pnpm typecheck`
- [ ] The `CI Success` status check passes
- [ ] CLI/MCP smoke, VSIX packaging, or JetBrains verification as applicable

## Review notes
Expand Down
12 changes: 12 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -308,3 +308,15 @@ jobs:

- name: Check extension metadata
run: pnpm check:extension-metadata

ci-success:
name: CI Success
runs-on: ubuntu-latest
needs: [build, test, cli-smoke, vsix-package, no-telemetry, extension-metadata]
if: always()
steps:
- name: Verify all required jobs succeeded
if: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') }}
run: exit 1
- name: All checks passed
run: echo "All required CI jobs passed."
12 changes: 12 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Code of Conduct

Everyone is welcome to participate, including people who are new to programming, Git, or open source.

- Be patient, respectful, and specific. Critique code and ideas, not people.
- Ask questions freely and help others without ridicule or pressure.
- Do not harass, threaten, discriminate, post sexualized content, or share someone else's private information.
- Respect issue assignments and first-time contributor reservations. Do not pressure maintainers to merge unreviewed work or bypass checks.

Maintainers may edit or remove harmful public content, ask participants to change their behavior, or restrict participation for serious or repeated violations. These expectations apply to repository issues, pull requests, reviews, and discussions.

Do not publish sensitive details in an issue. Use GitHub's **Report content** / **Report abuse** controls for harassment or other platform violations. Report security vulnerabilities through the process in [SECURITY.md](./SECURITY.md), not in public threads.
25 changes: 24 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,34 @@

Thank you for contributing. TCalc is local-first: workspace source must not be uploaded or sent to an external service by default.

## Your first open-source contribution

You are welcome here, even if you have never opened a pull request. Questions are part of the process, not a reason to hesitate.

- Browse [available beginner tasks](https://github.com/Sandesh13fr/TCalc/issues?q=is%3Aissue%20is%3Aopen%20label%3A%22good%20first%20issue%22%20label%3Aup-for-grabs%20no%3Aassignee).
- `good first issue` means approachable work with a bounded scope. `up-for-grabs` means it is available; check the assignee and recent comments before starting.
- `first-timers-only` tasks are reserved for people making their first open-source pull request, not just their first TCalc contribution. Experienced contributors should choose another issue.
- Comment with a short approach and the test/check you plan to use. For documentation, one sentence is enough. Mention if this is your first open-source PR and ask for help with any unfamiliar step.
- Wait for assignment before working. If you are assigned, the maintainer will remove `up-for-grabs`. Please do not work on someone else's assigned issue.
- Fork the repository, create a branch from `Development`, make only the assigned change, and open a PR targeting `Development` with `Fixes #<issue-number>` in its description.
- Only one open PR per external contributor is allowed. Keep drafts on your own branch until your current PR is resolved.
- For a documentation-only task, you may use GitHub's web editor without installing the project. Preview Markdown and check the links and commands you changed. Say which checks you ran; the maintainer will still require the relevant CI checks before merging.
- If setup fails or feedback is confusing, comment on the issue or PR with the error and ask for the next step. Never post tokens, passwords, private workspace paths, or source from a private project.

For a guided practice run, see [First Contributions](https://github.com/firstcontributions/first-contributions). Our approach follows [First Timers Only](https://www.firsttimersonly.com/): small tasks and patient help with the contribution process. Please follow our [Code of Conduct](./CODE_OF_CONDUCT.md).

## Set up

- Node.js 22 (the version used in CI)
- pnpm 11.5.2 (see `packageManager` in the root `package.json`)
- JDK 21 if you change the JetBrains plugin

```bash
git clone https://github.com/Sandesh13fr/TCalc.git
git clone https://github.com/<your-GitHub-username>/TCalc.git
cd TCalc
git remote add upstream https://github.com/Sandesh13fr/TCalc.git
git fetch upstream
git switch -c my-first-fix upstream/Development
corepack enable
pnpm install --frozen-lockfile
pnpm build
Expand Down Expand Up @@ -42,6 +61,10 @@ Select **every** affected area in the PR template. A change in `packages/recomme
6. Fill out the PR template: affected areas, issue link, behavior change, tests run with results, documentation, and privacy or compatibility impact. If a check was not run, say why. Add screenshots or a short recording for visible web/editor changes.
7. Do not commit generated `dist/`, VSIX, `.next/`, or JetBrains `build/` files.

## Required status checks

Pull requests targeting **`Development`** must pass the **CI Success** status check before they can be merged. This aggregate check ensures that the required CI jobs complete successfully.

## Project layout

```text
Expand Down
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ See the [VSIX installation guide](./docs/install-vsix.md) for the local package

Build once, then scan, compare, or generate only the context you need:

Building from source needs **Node.js 22** and **pnpm 11.5.2**. For the fork, clone, and setup walkthrough, see [CONTRIBUTING.md](./CONTRIBUTING.md).

```bash
pnpm install
pnpm build
Expand All @@ -76,6 +78,40 @@ pnpm cli rules ./my-project --target codex --mode repo-map-first

Other commands generate Markdown/JSON reports, validate model catalogs, create MCP configs, and start the local MCP server. Run `pnpm cli --help` for the complete command list.

### Ignore sources and precedence

TCalc applies ignore patterns in this order, with later matching rules taking precedence under normal gitignore semantics:

1. root `.gitignore`;
2. root `.cursorignore`;
3. root `.aiderignore`;
4. root `.continueignore`;
5. root `.tcalcignore`;
6. any explicit additional ignore files supplied by an integration;
7. nested `.gitignore` files, scoped to their containing directory;
8. workspace `exclude` patterns from TCalc configuration.

Nested ignore discovery skips version-control metadata and directories already excluded by higher-level rules. As with Git, a file cannot be re-included when its parent directory remains ignored. File-size, binary, generated-file, secret, and other safety exclusions are applied separately after path ignores and cannot be weakened by a negated ignore rule.

## Choose a privacy mode

TCalc applies the same privacy setting in its CLI, VS Code UI, and shared configuration:

| Mode | Recommendation guarantee |
| --- | --- |
| `local-first` (default) | Only catalog entries with `supportsLocal: true` are eligible. Cloud models and hybrid entries without a verified local execution path are rejected. If none qualify, TCalc reports that no eligible model is available instead of silently falling back to cloud execution. |
| `cloud-ok` | Cloud, hybrid, and local catalog entries may be recommended according to fit, quality, and cost. This expands recommendation eligibility; it does not upload source code or invoke a provider by itself. |

Set `privacyMode` in the workspace's `.tcalc.json` or use the corresponding privacy selector exposed by the CLI/VS Code integration. For example:

```json
{
"privacyMode": "local-first"
}
```

Workspace scanning, token estimation, repo-map generation, and reports remain local in both modes. Selecting `cloud-ok` only permits cloud-capable models to appear in recommendations; any later provider execution and credentials are controlled by the user's chosen external tool.

## Connect your coding agent

TCalc can expose the same scan, recommendation, repo-map, rules, and report capabilities over stdio MCP. It also generates agent rule files and client configuration without uploading source code.
Expand Down Expand Up @@ -129,6 +165,12 @@ pnpm cli mcp

## Project guides

### First contribution? Start here

[![First-timers-only friendly](https://img.shields.io/badge/first--timers--only-friendly-blue.svg?style=flat-square)](https://www.firsttimersonly.com/)

Browse [available beginner issues](https://github.com/Sandesh13fr/TCalc/issues?q=is%3Aissue%20is%3Aopen%20label%3A%22good%20first%20issue%22%20label%3Aup-for-grabs%20no%3Aassignee) and read the [first-contribution walkthrough](./CONTRIBUTING.md#your-first-open-source-contribution). Tasks labelled `first-timers-only` are reserved for your first open-source PR. Comment to request assignment before starting; maintainers can help with setup and review feedback.

### Troubleshooting VS Code test output

- Missing `catalogs/models.json` or `.tcalc/models.json` files are optional workspace overrides; TCalc uses the catalogue bundled with the extension when neither exists.
Expand Down
4 changes: 3 additions & 1 deletion apps/cli/src/commands/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export interface CatalogValidateOptions {
path?: string;
format?: string;
debug?: boolean;
maxAgeDays?: number;
now?: Date;
}

export async function executeCatalogFetch(url: string): Promise<string> {
Expand All @@ -26,7 +28,7 @@ export async function executeCatalogValidate(options: CatalogValidateOptions): P
};
}

const errors = [...validateModelCatalog(catalog.models), ...validateCatalogFreshness(catalog)];
const errors = [...validateModelCatalog(catalog.models), ...validateCatalogFreshness(catalog, options.maxAgeDays, options.now)];
if (errors.length > 0) {
const msg = options.format === "json"
? JSON.stringify({ valid: false, catalogPath, modelCount: catalog.models.length, errors }, null, 2)
Expand Down
149 changes: 149 additions & 0 deletions apps/cli/src/commands/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import { access, writeFile, readFile } from "node:fs/promises";
import path from "node:path";
import { DEFAULT_CONFIG, type PrivacySetting, type WorkspaceGoal, type WmaConfig } from "@wma/core";
import { resolveTargetPath } from "../utils/paths.js";
import { CliError } from "../utils/errors.js";

export interface InitOptions {
target?: string;
goal?: string;
privacy?: string;
force?: boolean;
dryRun?: boolean;
}

export interface DetectedStack {
primaryLanguage: "typescript" | "javascript" | "python" | "rust" | "go" | "generic";
isMonorepo: boolean;
detectedFrameworks: string[];
recommendedExcludes: string[];
recommendedBudget: number;
}

async function fileExists(filePath: string): Promise<boolean> {
try {
await access(filePath);
return true;
} catch {
return false;
}
}

export async function detectProjectStack(rootPath: string): Promise<DetectedStack> {
const hasPkgJson = await fileExists(path.join(rootPath, "package.json"));
const hasTsConfig = await fileExists(path.join(rootPath, "tsconfig.json"));
const hasPyProject = await fileExists(path.join(rootPath, "pyproject.toml"));
const hasRequirements = await fileExists(path.join(rootPath, "requirements.txt"));
const hasCargo = await fileExists(path.join(rootPath, "Cargo.toml"));
const hasGoMod = await fileExists(path.join(rootPath, "go.mod"));
const hasPnpmWorkspace = await fileExists(path.join(rootPath, "pnpm-workspace.yaml"));
const hasNx = await fileExists(path.join(rootPath, "nx.json"));
const hasTurbo = await fileExists(path.join(rootPath, "turbo.json"));

const isMonorepo = hasPnpmWorkspace || hasNx || hasTurbo;
const detectedFrameworks: string[] = [];
const recommendedExcludes: string[] = [...DEFAULT_CONFIG.exclude];

let primaryLanguage: DetectedStack["primaryLanguage"] = "generic";

if (hasCargo) {
primaryLanguage = "rust";
recommendedExcludes.push("target");
} else if (hasGoMod) {
primaryLanguage = "go";
recommendedExcludes.push("vendor", "bin");
} else if (hasPyProject || hasRequirements) {
primaryLanguage = "python";
recommendedExcludes.push(".venv", "venv", "__pycache__", ".pytest_cache", ".ruff_cache", "*.pyc");
} else if (hasPkgJson || hasTsConfig) {
primaryLanguage = hasTsConfig ? "typescript" : "javascript";
recommendedExcludes.push("dist", "build", ".next", ".turbo", "coverage", "storybook-static");

// Inspect package.json for frameworks
if (hasPkgJson) {
try {
const pkgRaw = await readFile(path.join(rootPath, "package.json"), "utf8");
const pkg = JSON.parse(pkgRaw) as { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };
const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
if (allDeps["next"]) detectedFrameworks.push("Next.js");
if (allDeps["vite"]) detectedFrameworks.push("Vite");
if (allDeps["react"]) detectedFrameworks.push("React");
if (allDeps["vue"]) detectedFrameworks.push("Vue");
if (allDeps["vitest"] || allDeps["jest"]) detectedFrameworks.push("Testing (Vitest/Jest)");
} catch {
// Ignore JSON read errors
}
}
}

// Deduplicate excludes
const uniqueExcludes = [...new Set(recommendedExcludes)];
const recommendedBudget = isMonorepo ? 200_000 : 128_000;

return {
primaryLanguage,
isMonorepo,
detectedFrameworks,
recommendedExcludes: uniqueExcludes,
recommendedBudget,
};
}

export async function executeInit(options: InitOptions): Promise<string> {
const rootPath = resolveTargetPath(options.target);
const configPath = path.join(rootPath, ".workspace-model-advisor.json");

const stack = await detectProjectStack(rootPath);

const goal = (options.goal as WorkspaceGoal) ?? DEFAULT_CONFIG.defaultGoal;
const privacy = (options.privacy as PrivacySetting) ?? (stack.primaryLanguage === "rust" ? "local-first" : DEFAULT_CONFIG.privacyMode);

const newConfig: Partial<WmaConfig> = {
defaultGoal: goal,
privacyMode: privacy,
exclude: stack.recommendedExcludes,
tokenBudget: {
defaultContextBudget: stack.recommendedBudget,
maxFullWorkspaceScan: stack.recommendedBudget * 2,
warnAt: Math.round(stack.recommendedBudget * 0.8),
},
};

const formattedJson = JSON.stringify(newConfig, null, 2);

if (options.dryRun) {
return [
`[DRY RUN] Inferred configuration for ${stack.primaryLanguage} project (${stack.isMonorepo ? "Monorepo" : "Single Package"}):`,
formattedJson,
].join("\n");
}

const alreadyExists = await fileExists(configPath);
if (alreadyExists && !options.force) {
throw new CliError(
`Configuration file already exists at ${configPath}. Use --force to overwrite it.`,
);
}

await writeFile(configPath, formattedJson, "utf8");

const lines: string[] = [
`Initialized TCalc workspace configuration!`,
`File written: ${configPath}`,
``,
`Project Diagnostics:`,
`- Primary Language: ${stack.primaryLanguage}`,
`- Monorepo: ${stack.isMonorepo ? "Yes" : "No"}`,
stack.detectedFrameworks.length > 0 ? `- Frameworks: ${stack.detectedFrameworks.join(", ")}` : "",
`- Calibrated Context Budget: ${stack.recommendedBudget.toLocaleString()} tokens`,
`- Default Goal: ${goal}`,
`- Privacy Mode: ${privacy}`,
`- Tailored Excludes: ${stack.recommendedExcludes.length} rules active`,
``,
`You can now run:`,
` wma scan`,
` wma recommend`,
].filter(Boolean);

return lines.join("\n");
}
2 changes: 1 addition & 1 deletion apps/cli/src/commands/recommend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ export async function executeRecommend(options: RecommendOptions): Promise<strin

const result = recommendModels({
models,
preferredModelIds: profile?.preferredModelIds,
workspaceTokens: scanResult.includedTokens,
goal,
privacyMode: privacy,
budget: options.tokenBudget,
preferredModelIds: profile?.preferredModelIds,
});

const fmt = options.format ?? "table";
Expand Down
8 changes: 5 additions & 3 deletions apps/cli/src/commands/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@ export async function executeReport(options: ReportOptions): Promise<string> {
try {
recommendation = recommendModels({
models,
preferredModelIds: profile?.preferredModelIds,
workspaceTokens: scanResult.includedTokens,
goal,
privacyMode: privacy,
preferredModelIds: profile?.preferredModelIds,
});
} catch {
// proceed without recommendations
} catch (error) {
const reason = error instanceof Error ? error.message : String(error);
scanResult.warnings.push(`Recommendations unavailable: ${reason}`);
if (options.debug) console.warn(`Recommendation failed: ${reason}`);
}
}

Expand Down
9 changes: 5 additions & 4 deletions apps/cli/src/commands/scan.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { scanWorkspace } from "@wma/scanner";
import { escapeMarkdownText, markdownCode } from "@wma/core";
import { formatScanTable, formatScanJson } from "../utils/output.js";
import { resolveTargetPath } from "../utils/paths.js";
import { loadWorkspaceConfig } from "../utils/loadWorkspaceConfig.js";
Expand Down Expand Up @@ -46,7 +47,7 @@ function formatScanMarkdown(scan: import("@wma/core").WorkspaceScanResult): stri
const lines: string[] = [];
lines.push("# Workspace Scan Report");
lines.push("");
lines.push(`**Workspace Root:** \`${scan.rootPath}\``);
lines.push(`**Workspace Root:** ${markdownCode(scan.rootPath)}`);
lines.push(`**Scanned At:** ${scan.scannedAt}`);
lines.push("");
lines.push("## Summary");
Expand All @@ -72,7 +73,7 @@ function formatScanMarkdown(scan: import("@wma/core").WorkspaceScanResult): stri
lines.push("| --- | ---:| ---:|");
for (const f of sortedFiles) {
const pc = (scan.includedTokens > 0 ? (f.estimatedTokens / scan.includedTokens) * 100 : 0).toFixed(1);
lines.push(`| \`${f.relativePath}\` | ${f.estimatedTokens.toLocaleString()} | ${pc}% |`);
lines.push(`| ${markdownCode(f.relativePath)} | ${f.estimatedTokens.toLocaleString()} | ${pc}% |`);
}
lines.push("");
}
Expand All @@ -85,7 +86,7 @@ function formatScanMarkdown(scan: import("@wma/core").WorkspaceScanResult): stri
const sortedLangs = [...scan.languages].sort((a, b) => b.totalTokens - a.totalTokens);
for (const l of sortedLangs) {
const pc = (l.percentage * 100).toFixed(1);
lines.push(`| ${l.language} | ${l.fileCount} | ${l.totalTokens.toLocaleString()} | ${pc}% |`);
lines.push(`| ${escapeMarkdownText(l.language)} | ${l.fileCount} | ${l.totalTokens.toLocaleString()} | ${pc}% |`);
}
lines.push("");
}
Expand All @@ -94,7 +95,7 @@ function formatScanMarkdown(scan: import("@wma/core").WorkspaceScanResult): stri
lines.push("## Warnings");
lines.push("");
for (const w of scan.warnings) {
lines.push(`- ${w}`);
lines.push(`- ${escapeMarkdownText(w)}`);
}
lines.push("");
}
Expand Down
Loading
Loading