@localness/cli 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,83 +18,95 @@ Node 18.3 or later. The token is `LOCALNESS_TOKEN`, read from `.env.local` next
18
18
  LOCALNESS_TOKEN=lnk_...
19
19
  ```
20
20
 
21
+ ## Terms
22
+
23
+ - **remote**: the texts of the configured project on the Localness instance.
24
+ - **local**: the locale files in the repository.
25
+ - **project**: the Localness project named by `project` in `localness.config.json`.
26
+ - **Localness**: the product and its instance (web app, API, AI naming).
27
+ - **locale**: a language, such as `en` or `ja`.
28
+
29
+ Identifiers keep the name `platform` for remote: kinds such as `platform-added` and `--json` fields such as `platform` and `onPlatform`.
30
+
21
31
  ## Commands
22
32
 
23
33
  ```sh
24
34
  localness init --base-url https://localness.example.com # find the locale files, write localness.config.json
25
- localness diff # compare the files with the project
26
- localness pull # write the project's changes into the files
35
+ localness diff # compare the files with remote
36
+ localness pull # write remote changes into the files
27
37
  localness push # plan sending local changes; prints a plan id
28
- localness apply 3f9a1c2e # write that plan to the project as drafts
38
+ localness apply 3f9a1c2e # write that plan to remote as drafts
29
39
  localness sync # pull, then plan a push
30
40
  localness match "Save" "Cancel" # existing keys holding these texts
31
- localness suggest-name "Save changes" # ask the project's AI for a key name
41
+ localness suggest-name "Save changes" # ask Localness AI for a key name
32
42
  localness review start texts.json # page to decide keys for extracted texts
33
43
  localness review wait 1a2b3c4d # the decisions, once approved
34
44
  localness releases use v2.4 # label the keys push creates with release v2.4
35
45
  localness skill install # teach coding agents this workflow
36
46
  ```
37
47
 
38
- | Command | What it does |
39
- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
40
- | `init` | Looks for `dir/{locale}.json` or `dir/{locale}/name.json` layouts, detects flat or nested JSON and writes `localness.config.json`. With `LOCALNESS_TOKEN` set it also fills `project` and maps project locales to file names. |
41
- | `diff` | Classifies each difference (see below). Read only; never writes the base. |
42
- | `pull` | Writes `platform-added`, `platform-changed` and `different` into the files and records the base. Local-only keys are kept unless `--prune`. Keys whose path collides with the file's structure are skipped and reported. |
43
- | `push` | Plans `local-added` and `local-changed` into `.localness/plans/<id>.json` and prints the id. Writes nothing to the project. Keys without source text, with a reserved name, or new keys whose name breaks a strict convention rule (prefix, characters, empty segment) are listed as blocked; new keys off the suggested separator, casing or depth are created and listed as warnings. |
44
- | `apply [id]` | Re-reads the planned keys; if any changed on the project since the plan, or the plan is over an hour old, deletes the plan and writes nothing. Otherwise creates new keys and writes drafts. No id: lists pending plans. |
45
- | `sync` | Pulls `platform-added` and `platform-changed`, then plans a push like `push`. Never touches `different` or `conflict`. |
46
- | `match` | For each text, the keys whose source text (draft or published) equals it after whitespace normalisation, plus keys only in the source-locale file (marked `local`, not pushed yet). Several keys per text are all listed. `--json` adds the project's key convention (prefix, separator, style, max depth, naming guidance) and namespace names, for naming new keys. Read only. |
47
- | `suggest-name` | Prints the project's suggested key name for a source text. Uses AI quota; writes nothing. |
48
- | `review` | `start <file>` reads `{ "items": [{ "text", "file", "line", "key" }] }`, looks up each text like `match` and opens a page: a tab in VS Code or Cursor when the Localness extension has the project open (it announces itself in `.localness/editors/`), otherwise a browser page (127.0.0.1, random port, secret token in the URL); `--open browser` or `--open editor` forces one. `--json` prints `{ id, url, rows, openedIn }`, `url` null in the editor. Per text the person picks reuse, new key or skip; new names are checked live against the convention and the existing keys (errors block approval, style suggestions only warn), and checked again on approval. `wait <id> [--timeout <s>]` prints the decisions as JSON, or `status: "pending"` after the timeout (default 90 s). Writes nothing to the project or the code; the browser page stops after approval, cancel or two hours. |
49
- | `releases` | Lists the project's releases (`*` marks the config's). `use <name>` / `use --none` sets the release new keys get; `create <name> [--use]` adds one (project owners). `add\|remove <release> <key...>` relabels existing keys; `--match <glob>` selects keys and asks before changing them (`--yes` skips the question). |
50
- | `skill install` | Installs the Agent Skill for coding agents; see [Coding agents](#coding-agents). |
51
-
52
- `push` and `apply` only write drafts; publishing stays on the platform. A plan holds at most 200 keys.
48
+ | Command | What it does |
49
+ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
50
+ | `init` | Looks for `dir/{locale}.json` or `dir/{locale}/name.json` layouts, detects flat or nested JSON and writes `localness.config.json`. With `LOCALNESS_TOKEN` set it also fills `project` and maps project locales to file names. |
51
+ | `diff` | Classifies each difference (see below). Read only; never writes the base. |
52
+ | `pull` | Writes `platform-added`, `platform-changed` and `different` into the files and records the base. Local-only keys are kept unless `--prune`. Keys whose path collides with the file's structure are skipped and reported. New keys go to the directory their `match` picks; keys no directory fits (`unrouted`) and `duplicate` keys are left, listed, and make `pull` exit 1. |
53
+ | `push` | Plans `local-added` and `local-changed` into `.localness/plans/<id>.json` and prints the id. Writes nothing to remote. Keys without source text, with a reserved name, or new keys whose name breaks a strict convention rule (prefix, characters, empty segment) are listed as blocked; new keys off the suggested separator, casing or depth are created and listed as warnings. |
54
+ | `apply [id]` | Re-reads the planned keys; if any changed on remote since the plan, or the plan is over an hour old, deletes the plan and writes nothing. Otherwise creates new keys and writes drafts. No id: lists pending plans. |
55
+ | `sync` | Pulls `platform-added` and `platform-changed`, then plans a push like `push`. Never touches `different` or `conflict`. |
56
+ | `match` | For each text, the keys whose source text (draft or published) equals it after whitespace normalisation, plus keys only in the source-locale file (marked `local`, not pushed yet). Several keys per text are all listed. `--json` adds the project's key convention (prefix, separator, style, max depth, naming guidance) and namespace names, for naming new keys. Read only. |
57
+ | `suggest-name` | Prints Localness AI's suggested key name for a source text. Uses AI quota; writes nothing. |
58
+ | `review` | `start <file>` reads `{ "items": [{ "text", "file", "line", "key" }] }`, looks up each text like `match` and opens a page: a tab in VS Code or Cursor when the Localness extension has the project open (it announces itself in `.localness/editors/`), otherwise a browser page (127.0.0.1, random port, secret token in the URL); `--open browser` or `--open editor` forces one. `--json` prints `{ id, url, rows, openedIn }`, `url` null in the editor. Per text the person picks reuse, new key or skip; new names are checked live against the convention and the existing keys (errors block approval, style suggestions only warn), and checked again on approval. `wait <id> [--timeout <s>]` prints the decisions as JSON, or `status: "pending"` after the timeout (default 90 s). Writes nothing to remote or the code; the browser page stops after approval, cancel or two hours. |
59
+ | `releases` | Lists the project's releases (`*` marks the config's). `use <name>` / `use --none` sets the release new keys get; `create <name> [--use]` adds one (project owners). `add\|remove <release> <key...>` relabels existing keys; `--match <glob>` selects keys and asks before changing them (`--yes` skips the question). |
60
+ | `skill install` | Installs the Agent Skill for coding agents; see [Coding agents](#coding-agents). |
61
+
62
+ `push` and `apply` only write drafts; publishing stays in Localness. A plan holds at most 200 keys.
53
63
 
54
64
  | Kind | Meaning | Handled by |
55
65
  | ------------------ | -------------------------------------------------------------- | -------------------- |
56
- | `platform-added` | The project has text the file lacks | pull, sync |
57
- | `platform-changed` | The project changed since the base; the file did not | pull, sync |
58
- | `platform-deleted` | The key left the project; the file still has the base text | `--prune` / by hand |
59
- | `local-added` | The file has text the project lacks | push, sync |
60
- | `local-changed` | The file changed since the base; the project did not | push, sync |
61
- | `local-deleted` | The file dropped a key the project still has unchanged | by hand (no deletes) |
66
+ | `platform-added` | Remote has text the file lacks | pull, sync |
67
+ | `platform-changed` | Remote changed since the base; the file did not | pull, sync |
68
+ | `platform-deleted` | The key left remote; the file still has the base text | `--prune` / by hand |
69
+ | `local-added` | The file has text remote lacks | push, sync |
70
+ | `local-changed` | The file changed since the base; remote did not | push, sync |
71
+ | `local-deleted` | The file dropped a key remote still has unchanged | by hand (no deletes) |
62
72
  | `different` | Text differs and there is no base yet | pull, or `--keys` |
63
73
  | `conflict` | Both changed, or the push would overwrite someone else's draft | `--keys` |
64
- | `pending-publish` | The file matches the project's unpublished draft | publish on platform |
65
-
66
- The base (`.localness/base.json`, next to the config) is the last text the file and the project agreed on; `pull`, `apply` and `sync` update it. Without it, every change is `different`: run `pull` or `sync` once. `.localness/` gets its own `.gitignore`; never commit it.
67
-
68
- | Option | Commands | Description |
69
- | ---------------------- | ------------------------------------- | -------------------------------------------------------------------------------------------- |
70
- | `--config <path>` | all | Config file. Default: nearest `localness.config.json`. |
71
- | `--keys <a,b>` | diff, pull, push, sync | Only these keys. For `pull` and `push`, take that side even when both changed. |
72
- | `--locales <en,ja>` | diff, pull, push, sync | Only these platform locales. |
73
- | `--prune` | pull | Also remove keys the project does not have. |
74
- | `--dry-run` | init, pull, push, sync, skill install | Show what would happen. |
75
- | `--json` | all | Machine-readable output on stdout. |
76
- | `--base-url <url>` | init | Localness instance URL. Required. |
77
- | `--project <name\|id>` | init | Project. Default: the token's only project. |
78
- | `--dir <path>` | init | Locale directory, skipping detection. |
79
- | `--pattern <pattern>` | init | File pattern under `--dir`, for example `{locale}.json`. |
80
- | `--format <format>` | init | `flat-json` or `nested-json`. |
81
- | `--force` | init, skill install | Overwrite an existing config, or a hand-edited Skill. |
82
- | `--agent <a,b>` | skill install | `copilot`, `claude`, `cursor`, `codex` or `all`. Default: the first three. |
83
- | `--agents-md` | skill install | Also add a block pointing to the Skill in the root `AGENTS.md`. |
84
- | `--root <path>` | skill install | Install here instead of the git root, for a folder opened on its own. |
85
- | `--release <name>` | init | Release new keys are labelled with. |
86
- | `--none` | releases use | No release for new keys. |
87
- | `--use` | releases create | Also make the new release the config's. |
88
- | `--match <glob>` | releases add, releases remove | Keys to relabel, e.g. `checkout.*`. |
89
- | `--timeout <seconds>` | review wait | How long to wait for the decisions. Default 90. |
90
- | `--open <where>` | review start | `auto` (default: the editor when the extension has the project open), `browser` or `editor`. |
91
- | `--yes`, `-y` | releases add, releases remove | Skip the confirmation for `--match`. |
74
+ | `pending-publish` | The file matches the unpublished remote draft | publish in Localness |
75
+
76
+ The base (`.localness/base.json`, next to the config) is the last text the file and remote agreed on; `pull`, `apply` and `sync` update it. Without it, every change is `different`: run `pull` or `sync` once. `.localness/` gets its own `.gitignore`; never commit it.
77
+
78
+ | Option | Commands | Description |
79
+ | ---------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
80
+ | `--config <path>` | all | Config file. Default: nearest `localness.config.json`. |
81
+ | `--keys <a,b>` | diff, pull, push, sync | Only these keys. For `pull` and `push`, take that side even when both changed. |
82
+ | `--locales <en,ja>` | diff, pull, push, sync | Only these project locales. |
83
+ | `--prune` | pull | Also remove keys remote does not have. |
84
+ | `--dry-run` | init, pull, push, sync, skill install | Show what would happen. |
85
+ | `--json` | all | Machine-readable output on stdout. For `diff`, `pull`, `push`, `sync` and `apply <id>` it names the `config` file used. |
86
+ | `--base-url <url>` | init | Localness instance URL. Required. |
87
+ | `--project <name\|id>` | init | Project. Default: the token's only project. |
88
+ | `--dir <path>` | init | Locale directory, skipping detection. |
89
+ | `--pattern <pattern>` | init | File pattern under `--dir`, for example `{locale}.json`. |
90
+ | `--into <dir>` | pull, sync | Configured directory for keys that have no place yet (`unrouted`, or a locale added to a `duplicate`). A person chooses it. |
91
+ | `--format <format>` | init | `flat-json` or `nested-json`. |
92
+ | `--force` | init, skill install | Overwrite an existing config, or a hand-edited Skill. |
93
+ | `--agent <a,b>` | skill install | `copilot`, `claude`, `cursor`, `codex` or `all`. Default: the first three. |
94
+ | `--agents-md` | skill install | Also add a block pointing to the Skill in the root `AGENTS.md`. |
95
+ | `--root <path>` | skill install | Install here instead of the git root, for a folder opened on its own. |
96
+ | `--global` | skill install | Install in your home folder, for every repository. Not with `--root` or `--agents-md`. |
97
+ | `--release <name>` | init | Release new keys are labelled with. |
98
+ | `--none` | releases use | No release for new keys. |
99
+ | `--use` | releases create | Also make the new release the config's. |
100
+ | `--match <glob>` | releases add, releases remove | Keys to relabel, e.g. `checkout.*`. |
101
+ | `--timeout <seconds>` | review wait | How long to wait for the decisions. Default 90. |
102
+ | `--open <where>` | review start | `auto` (default: the editor when the extension has the project open), `browser` or `editor`. |
103
+ | `--yes`, `-y` | releases add, releases remove | Skip the confirmation for `--match`. |
92
104
 
93
105
  Exit codes: `0` success (for `diff`: no differences), `1` `diff` found differences, `2` error (including a stale, expired or failed `apply`).
94
106
 
95
- Plans are local files in `.localness/plans/`; the platform knows nothing of them. `push`, `sync` and `apply` without an id delete expired plans; deleting a plan by hand is safe too.
107
+ Plans are local files in `.localness/plans/`; remote knows nothing of them. `push`, `sync` and `apply` without an id delete expired plans; deleting a plan by hand is safe too.
96
108
 
97
- Writes (`apply`) are labeled in the platform's key history as `cli/<version>`, or `cli/<version>; agent` when the CLI runs under an AI agent. Detection is best-effort from the agent's environment (`AI_AGENT`, `CLAUDECODE`, `CURSOR_AGENT`, `COPILOT_CLI`, `CODEX_SANDBOX`, `GEMINI_CLI`). Set `LOCALNESS_AGENT=1` to force the agent label or `LOCALNESS_AGENT=0` to drop it. The label is informational; permissions come from the token.
109
+ Writes (`apply`) are labeled in the key history on remote as `cli/<version>`, or `cli/<version>; agent` when the CLI runs under an AI agent. Detection is best-effort from the agent's environment (`AI_AGENT`, `CLAUDECODE`, `CURSOR_AGENT`, `COPILOT_CLI`, `CODEX_SANDBOX`, `GEMINI_CLI`). Set `LOCALNESS_AGENT=1` to force the agent label or `LOCALNESS_AGENT=0` to drop it. The label is informational; permissions come from the token.
98
110
 
99
111
  ## Coding agents
100
112
 
@@ -109,7 +121,23 @@ Writes (`apply`) are labeled in the platform's key history as `cli/<version>`, o
109
121
 
110
122
  It writes as few copies as cover the chosen agents, since an agent reading two copies lists the skill twice: the default (Copilot, Claude Code, Cursor) is the single `.claude/skills/localness/SKILL.md`. Claude Code and Codex share no folder, so `--agent all` writes two. Copies already installed in any of these folders are updated too.
111
123
 
112
- `SKILL.md` records the CLI version and a hash over every file of the Skill. Reinstalling leaves a copy with any hand-edited file alone unless `--force`. `diff`, `pull`, `push`, `apply` and `sync` print a note on stderr when the installed Skill is from another CLI version. Project-specific conventions belong in the platform's Skills page, not in this file.
124
+ `SKILL.md` records the CLI version and a hash over every file of the Skill. Reinstalling leaves a copy with any hand-edited file alone unless `--force`. `diff`, `pull`, `push`, `apply` and `sync` print a note on stderr when the installed Skill is from another CLI version. Project-specific conventions belong in the Skills page in Localness, not in this file.
125
+
126
+ To give your agents the Skill in every repository without committing it, install it once in your home folder:
127
+
128
+ ```sh
129
+ localness skill install --global # Copilot, Claude Code, Cursor
130
+ localness skill install --global --agent codex
131
+ ```
132
+
133
+ | Agent | Reads skills from (home folder) |
134
+ | -------------- | ----------------------------------------------------------------------------- |
135
+ | GitHub Copilot | `~/.copilot/skills`, `~/.agents/skills` |
136
+ | Claude Code | `~/.claude/skills` |
137
+ | Cursor | `~/.cursor/skills`, `~/.agents/skills`, `~/.claude/skills`, `~/.codex/skills` |
138
+ | Codex | `~/.agents/skills` |
139
+
140
+ The same rule picks the fewest copies: the default writes `~/.claude/skills/localness` (Claude Code, Cursor) and `~/.copilot/skills/localness` (Copilot). `--global` leaves `AGENTS.md` alone and cannot be combined with `--root` or `--agents-md`; `--agent`, `--dry-run`, `--force` and `--json` work as usual. An agent that reads both a repository copy and a home-folder copy lists the skill twice, so pick one per machine or repository. Rerun `localness skill install --global` after upgrading the CLI; the stderr note names `--global` when the home-folder copy is the outdated one.
113
141
 
114
142
  ## `localness.config.json`
115
143
 
@@ -128,17 +156,35 @@ Shared with the VS Code extension. Commit it; tokens never go here.
128
156
  }
129
157
  ```
130
158
 
131
- | Field | Default | Description |
132
- | ---------------------------------------------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------- |
133
- | `baseUrl` | required | Localness instance URL. |
134
- | `project` | none | Project id or name. Missing: the token's only project. |
135
- | `files.dir` | required in files | Locale directory, relative to the config file. |
136
- | `files.pattern` | `{locale}.json` | File path under `dir`; `{locale}` is the file name of the locale. |
137
- | `files.format` | `nested-json` | `nested-json` (`{ "a": { "b": "…" } }`) or `flat-json` (`{ "a.b": "…" }`). |
138
- | `locales` | all | Platform locales to sync. |
139
- | `localeMap` | none | Platform locale → file name, when the file is not named after the locale. |
140
- | `release` | none | Release the keys `apply` creates are labelled with. Set it with `localness releases use`. Sync is never filtered by release. |
141
- | `content` | `published` | `published` compares what `/bundle` serves; `draft` previews unpublished edits. |
142
- | `keyPatterns`, `useDefaultKeyPatterns`, `extractTemplates` | | Used by the VS Code extension. |
159
+ | Field | Default | Description |
160
+ | ---------------------------------------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
161
+ | `baseUrl` | required | Localness instance URL. |
162
+ | `project` | none | Project id or name. Missing: the token's only project. |
163
+ | `files` | none | One directory object, or a list of them (below). |
164
+ | `files[].dir` | required | Locale directory, relative to the config file; unique in the list. |
165
+ | `files[].pattern` | `{locale}.json` | File path under `dir`; `{locale}` is the file name of the locale. |
166
+ | `files[].format` | `nested-json` | `nested-json` (`{ "a": { "b": "…" } }`) or `flat-json` (`{ "a.b": "…" }`), per directory. |
167
+ | `files[].match` | none | Which new keys go to this directory: `key` (regular expression on the whole key) and/or `namespace` (a project namespace); all given conditions must hold. |
168
+ | `locales` | all | Project locales to sync. |
169
+ | `localeMap` | none | Project locale → file name, when the file is not named after the locale. |
170
+ | `release` | none | Release the keys `apply` creates are labelled with. Set it with `localness releases use`. Sync is never filtered by release. |
171
+ | `content` | `published` | `published` compares what `/bundle` serves; `draft` previews unpublished edits. |
172
+ | `keyPatterns`, `useDefaultKeyPatterns`, `extractTemplates` | | Used by the VS Code extension. |
143
173
 
144
174
  Keys of unnamed drafts (`__unnamed_…`) are never written.
175
+
176
+ ### Several directories
177
+
178
+ `files` takes one object or a list. A single object works exactly as before.
179
+
180
+ ```json
181
+ "files": [
182
+ { "dir": "src/locales/default" },
183
+ { "dir": "src/locales/boostprime", "match": { "namespace": "boostprime" } }
184
+ ]
185
+ ```
186
+
187
+ - Where a key lives: the directory that already has it (in any locale), else the first entry whose `match` fits, else the first entry without a `match` (the fallback). With none of these the key is `unrouted`: `pull` and `sync` skip it, list it, and exit 1; a person picks the directory with `localness pull --keys <key> --into <dir>`, and the key stays there afterwards.
188
+ - A key present in more than one directory is a `duplicate` (judged per key, across locales). Equal texts everywhere: `pull` updates every copy and `push` works as usual. Different texts, or remote added a locale the key has no file for: `pull`, `push` and `sync` skip it and list it; `pull --keys <key>` writes the remote text to every copy (`--into <dir>` places a locale with no copy yet).
189
+ - `match.namespace` is checked against the project's namespaces; an unknown name is reported as a warning. `init` finds sibling directories such as `default/` and `boostprime/`, picks a fallback (`default`, `common`, … or the largest) and infers `match` from the keys: the project namespace most of a directory's keys belong to, else the leading word they share.
190
+ - Git-sync's `locale-files` setting in Localness is still a single directory; this list exists only in `localness.config.json`.
package/dist/cli.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { createInterface } from "node:readline/promises";
3
3
  import { parseArgs } from "node:util";
4
- import { LocalnessError, createClient, findRelease } from "@localness/sdk";
4
+ import { LocalnessError, createClient, findRelease, namespaceOf } from "@localness/sdk";
5
5
  import { CONFIG_FILE_NAME, DIFF_KINDS, FORCED_PULL_KINDS, FORCED_PUSH_KINDS, PULL_KINDS, PUSH_KINDS, SYNC_PULL_KINDS, applyPush, checkPlan, compareLocaleFiles, deletePlan, describeBlocked, describeViolations, findConfigFile, listPlans, loadConfig, loadPlan, matchLocalEntries, parseConfig, planPush, prunePlans, pullLocaleFiles, readBase, readLocalFiles, recordPush, resolveRelease, savePlan, writeBase, writeConfigFields } from "@localness/sdk/sync";
6
- import { dirname, join, relative, resolve } from "node:path";
6
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
7
7
  import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
8
8
  import { DEFAULT_LOCALE_FILE_PATTERN, LOCALE_PLACEHOLDER, LocaleFileFormat, localeFileName, localeFilesScopeError, readLocaleFile } from "@localness/contract/locale-file";
9
9
  import { spawn } from "node:child_process";
@@ -11,9 +11,10 @@ import { createHash, randomBytes } from "node:crypto";
11
11
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
12
12
  import { claimReview, createReviewSession, hasEditor, isAlive, parseReviewInput, prepareReviewDir, readJson, reviewPage, reviewPaths, takenNames, writeJson } from "@localness/sdk/review";
13
13
  import { createServer } from "node:http";
14
+ import { homedir } from "node:os";
14
15
  import { fileURLToPath } from "node:url";
15
16
  // package.json
16
- var version = "0.1.1";
17
+ var version = "0.2.0";
17
18
  // src/env.ts
18
19
  const TOKEN_ENV = "LOCALNESS_TOKEN";
19
20
  const ENV_FILE = ".env.local";
@@ -53,12 +54,14 @@ const OPTIONS = {
53
54
  "base-url": { type: "string" },
54
55
  project: { type: "string" },
55
56
  dir: { type: "string" },
57
+ into: { type: "string" },
56
58
  pattern: { type: "string" },
57
59
  format: { type: "string" },
58
60
  force: { type: "boolean" },
59
61
  agent: { type: "string" },
60
62
  "agents-md": { type: "boolean" },
61
63
  root: { type: "string" },
64
+ global: { type: "boolean" },
62
65
  release: { type: "string" },
63
66
  none: { type: "boolean" },
64
67
  use: { type: "boolean" },
@@ -86,6 +89,10 @@ function list(value) {
86
89
  function plural(count, noun) {
87
90
  return `${count} ${noun}${count === 1 ? "" : "s"}`;
88
91
  }
92
+ /** Config problems the comparison found; they never stop a command. */
93
+ function printWarnings(io, warnings) {
94
+ for (const warning of warnings) io.stderr(`localness: ${warning}\n`);
95
+ }
89
96
  async function readToken(io, dir) {
90
97
  const token = await findEnvToken(dir, io.env);
91
98
  if (!token) throw new Error(`Set ${TOKEN_ENV} to a Localness API token in ${join(dir, ENV_FILE)} or the environment.`);
@@ -124,6 +131,10 @@ async function loadProject(io, values) {
124
131
  })
125
132
  };
126
133
  }
134
+ /** The config file used, relative to the working directory, for JSON output. */
135
+ function configField(io, loaded) {
136
+ return relative(io.cwd, loaded.path).split(sep).join("/");
137
+ }
127
138
  // src/apply.ts
128
139
  async function runApply(io, values, id) {
129
140
  const { client, loaded } = await loadProject(io, values);
@@ -147,12 +158,13 @@ async function runApply(io, values, id) {
147
158
  const check = await checkPlan(client, plan);
148
159
  if (check.expired || check.stale.length > 0) {
149
160
  await deletePlan(loaded, id);
150
- throw new Error(check.expired ? `Plan ${id} expired; run "localness push" again.` : `The project changed since plan ${id} was made (${check.stale.join(", ")}); nothing was written. Run "localness push" again.`);
161
+ throw new Error(check.expired ? `Plan ${id} expired; run "localness push" again.` : `Remote changed since plan ${id} was made (${check.stale.join(", ")}); nothing was written. Run "localness push" again.`);
151
162
  }
152
163
  const result = await applyPush(client, plan, check);
153
164
  await deletePlan(loaded, id);
154
165
  await writeBase(loaded, recordPush(await readBase(loaded), plan, result));
155
166
  if (values.json) io.stdout(`${JSON.stringify({
167
+ config: configField(io, loaded),
156
168
  id,
157
169
  ...result
158
170
  }, null, 2)}\n`);
@@ -177,20 +189,21 @@ function quote(text) {
177
189
  function detail(entry) {
178
190
  const { local, platform, draft, base } = entry;
179
191
  switch (entry.kind) {
180
- case "platform-added": return quote(platform);
192
+ case "platform-added": return entry.target.by === "unrouted" ? `${quote(platform)} (no directory matches it)` : quote(platform);
181
193
  case "platform-changed": return `${quote(local)} → ${quote(platform)}`;
182
- case "platform-deleted": return `${quote(local)} (deleted in the project)`;
183
- case "local-added": return `${quote(local)} (${entry.onPlatform ? "no text" : "not"} in the project)`;
194
+ case "platform-deleted": return `${quote(local)} (deleted on remote)`;
195
+ case "local-added": return `${quote(local)} (${entry.onPlatform ? "no text" : "not"} on remote)`;
184
196
  case "local-changed": return `${quote(platform)} → ${quote(local)}`;
185
197
  case "local-deleted": return `${quote(platform)} (deleted locally)`;
186
- case "different": return `local ${quote(local)}, project ${quote(platform)}`;
198
+ case "different": return `local ${quote(local)}, remote ${quote(platform)}`;
187
199
  case "conflict": return [
188
200
  `local ${quote(local)}`,
189
- `project ${quote(platform)}`,
201
+ `remote ${quote(platform)}`,
190
202
  draft !== null && draft !== platform && `unpublished ${quote(draft)}`,
191
203
  `base ${quote(base)}`
192
204
  ].filter(Boolean).join(", ");
193
205
  case "pending-publish": return `${quote(local)} (draft waiting for a publish)`;
206
+ case "duplicate": return entry.locations.length > 0 ? `${entry.locations.map((place) => `${place.dir} ${quote(place.value)}`).join(", ")}; remote ${quote(platform)}` : `no ${entry.locale} text in ${entry.dirs.join(", ")}; remote ${quote(platform)}`;
194
207
  }
195
208
  }
196
209
  const KIND_WIDTH = Math.max(...DIFF_KINDS.map((kind) => kind.length));
@@ -203,15 +216,32 @@ function countKinds(entries) {
203
216
  return DIFF_KINDS.filter((kind) => counts.has(kind)).map((kind) => `${counts.get(kind)} ${kind}`).join(", ");
204
217
  }
205
218
  function filesByLocale(comparison) {
206
- return Object.fromEntries(comparison.files.map((file) => [file.locale, file.relativePath]));
219
+ const files = {};
220
+ for (const file of comparison.files) (files[file.locale] ??= []).push(file.relativePath);
221
+ return files;
222
+ }
223
+ /** A key `pull` left for a person, for JSON output. */
224
+ function attention(entry) {
225
+ return {
226
+ locale: entry.locale,
227
+ key: entry.key,
228
+ platform: entry.platform,
229
+ dirs: entry.dirs,
230
+ locations: entry.locations.map(({ dir, relativePath, value }) => ({
231
+ dir,
232
+ relativePath,
233
+ value
234
+ }))
235
+ };
207
236
  }
208
237
  const HINTS = [
209
238
  [[
210
239
  "platform-added",
211
240
  "platform-changed",
212
241
  "different"
213
- ], "\"localness pull\" takes the project's text for platform-added, platform-changed and different."],
242
+ ], "\"localness pull\" takes the remote text for platform-added, platform-changed and different."],
214
243
  [["local-added", "local-changed"], "\"localness push\" plans sending local-added and local-changed."],
244
+ [["duplicate"], "A duplicate key is in several directories: \"pull --keys <key>\" writes the remote text to every place that has it (\"--into <dir>\" places a locale it has none in); never pick a directory for it yourself."],
215
245
  [[
216
246
  "conflict",
217
247
  "local-deleted",
@@ -224,9 +254,11 @@ async function runDiff(io, values) {
224
254
  locales: list(values.locales),
225
255
  keys: list(values.keys)
226
256
  });
257
+ printWarnings(io, comparison.warnings);
227
258
  const files = filesByLocale(comparison);
228
259
  const { entries } = comparison;
229
260
  if (values.json) io.stdout(`${JSON.stringify({
261
+ config: configField(io, loaded),
230
262
  sourceLocale: comparison.sourceLocale,
231
263
  locales: comparison.locales,
232
264
  content: comparison.content,
@@ -234,17 +266,18 @@ async function runDiff(io, values) {
234
266
  files,
235
267
  differences: entries
236
268
  }, null, 2)}\n`);
237
- else if (entries.length === 0) io.stdout(`Up to date: ${comparison.locales.length} locale files match the project's ${comparison.content} text.\n`);
269
+ else if (entries.length === 0) io.stdout(`Up to date: ${comparison.locales.length} locale files match the remote ${comparison.content} text.\n`);
238
270
  else {
239
271
  for (const locale of comparison.locales) {
240
272
  const own = entries.filter((entry) => entry.locale === locale);
241
273
  if (own.length === 0) continue;
242
- io.stdout(`${files[locale]} (${locale})\n`);
274
+ io.stdout(`${files[locale]?.join(", ")} (${locale})\n`);
243
275
  for (const entry of own) io.stdout(`${describeEntry(entry)}\n`);
244
276
  }
245
- io.stdout(`\n${entries.length} differences against the project's ${comparison.content} text: ${countKinds(entries)}.\n`);
277
+ io.stdout(`\n${entries.length} differences against the remote ${comparison.content} text: ${countKinds(entries)}.\n`);
246
278
  if (comparison.base === null) io.stdout("No base yet, so changed text shows as \"different\"; pull or sync records one.\n");
247
279
  for (const [kinds, hint] of HINTS) if (entries.some((entry) => kinds.includes(entry.kind))) io.stdout(`${hint}\n`);
280
+ if (entries.some((entry) => entry.target.by === "unrouted")) io.stdout("Keys that match no directory stay unwritten until a person picks one: \"pull --keys <key> --into <dir>\".\n");
248
281
  }
249
282
  return entries.length > 0 ? 1 : 0;
250
283
  }
@@ -306,6 +339,61 @@ function groupLocaleFiles(paths) {
306
339
  }
307
340
  return [...groups.values()].sort((a, b) => b.files.size - a.files.size || a.dir.length - b.dir.length);
308
341
  }
342
+ const FALLBACK_NAMES = [
343
+ "default",
344
+ "common",
345
+ "base",
346
+ "main",
347
+ "shared",
348
+ "core"
349
+ ];
350
+ const OWN_SHARE = .8;
351
+ const OTHER_SHARE = .2;
352
+ /**
353
+ * The directory `groups` start from, plus its siblings: same pattern, same
354
+ * parent, and a locale in common (`locales/default/`, `locales/boostprime/`).
355
+ * The directory new keys fall back to comes first.
356
+ */
357
+ function pickGroups(groups) {
358
+ const [top] = groups;
359
+ if (!top) return [];
360
+ const parent = posix.dirname(top.dir);
361
+ const all = [top, ...groups.filter((group) => group !== top && group.pattern === top.pattern && posix.dirname(group.dir) === parent && [...group.files.keys()].some((name) => top.files.has(name)))];
362
+ const fallback = all.find((group) => FALLBACK_NAMES.includes(posix.basename(group.dir))) ?? top;
363
+ return [fallback, ...all.filter((group) => group !== fallback)];
364
+ }
365
+ async function keysOf(root, group) {
366
+ const keys = /* @__PURE__ */ new Set();
367
+ for (const path of group.files.values()) try {
368
+ const source = await readFile(join(root, path), "utf8");
369
+ for (const key of Object.keys(readLocaleFile(source).entries)) keys.add(key);
370
+ } catch {
371
+ continue;
372
+ }
373
+ return [...keys];
374
+ }
375
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
376
+ /**
377
+ * A `match` that sends `own`'s kind of key here: the platform namespace
378
+ * most of its keys belong to, else the leading word most share. It must be
379
+ * rare among `rest`, the other directories' keys.
380
+ */
381
+ function inferMatch(own, rest, namespaces, keyPrefix) {
382
+ if (own.length === 0) return void 0;
383
+ const labelers = [];
384
+ if (namespaces.length > 0) labelers.push([(key) => namespaceOf(key, namespaces, keyPrefix), (namespace) => ({ namespace })]);
385
+ if (keyPrefix === "") labelers.push([(key) => /^([^_.-]+)[_.-]/.exec(key)?.[1] ?? null, (word) => ({ key: `^${escapeRegExp(word)}[_.-]` })]);
386
+ for (const [labelOf, toMatch] of labelers) {
387
+ const counts = /* @__PURE__ */ new Map();
388
+ for (const key of own) {
389
+ const label = labelOf(key);
390
+ if (label !== null) counts.set(label, (counts.get(label) ?? 0) + 1);
391
+ }
392
+ const [label, count] = [...counts].sort((a, b) => b[1] - a[1])[0] ?? [];
393
+ if (label === void 0 || count / own.length < OWN_SHARE) continue;
394
+ if (rest.filter((key) => labelOf(key) === label).length <= rest.length * OTHER_SHARE) return toMatch(label);
395
+ }
396
+ }
309
397
  /** Nested when any file nests; flat when keys contain dots but never nest. */
310
398
  async function detectFormat(root, paths) {
311
399
  let dotted = false;
@@ -363,31 +451,36 @@ async function runInit(io, values) {
363
451
  if (!baseUrl) throw new Error("Pass --base-url <url> of the Localness instance.");
364
452
  const notes = [];
365
453
  const groups = groupLocaleFiles(await scan(root));
366
- let group;
454
+ let used;
367
455
  if (values.dir !== void 0) {
368
456
  const dir = values.dir.replace(/\\/g, "/").replace(/\/+$/, "");
369
457
  const pattern = values.pattern ?? DEFAULT_LOCALE_FILE_PATTERN;
370
- group = groups.find((candidate) => candidate.dir === dir && candidate.pattern === pattern) ?? {
458
+ const group = groups.find((candidate) => candidate.dir === dir && candidate.pattern === pattern) ?? {
371
459
  dir,
372
460
  pattern,
373
461
  files: /* @__PURE__ */ new Map()
374
462
  };
375
463
  if (group.files.size === 0) notes.push(`No files match ${dir}/${pattern} yet.`);
464
+ used = [group];
376
465
  } else {
377
- group = groups[0];
378
- if (!group) throw new Error("Found no locale JSON files like src/locales/en.json; pass --dir and --pattern.");
379
- const others = groups.slice(1, 4);
466
+ if (groups.length === 0) throw new Error("Found no locale JSON files like src/locales/en.json; pass --dir and --pattern.");
467
+ used = pickGroups(groups);
468
+ if (used.length > 1) notes.push(`Found ${used.length} sibling directories (${used.map((group) => group.dir).join(", ")}); all are synced, new keys go where "match" says, else to ${used[0].dir}.`);
469
+ const others = groups.filter((group) => !used.includes(group)).slice(0, 3);
380
470
  if (others.length > 0) notes.push(`Also found ${others.map((other) => `${other.dir}/${other.pattern}`).join(", ")}; pass --dir and --pattern to use another.`);
381
471
  }
382
- const format = values.format ? parseFormat(values.format) : await detectFormat(root, group.files.values());
383
- const names = [...group.files.keys()].sort();
472
+ const formats = await Promise.all(used.map((group) => values.format ? parseFormat(values.format) : detectFormat(root, group.files.values())));
473
+ const names = [...new Set(used.flatMap((group) => [...group.files.keys()]))].sort();
384
474
  const config = { baseUrl };
385
475
  if (values.project) config.project = values.project;
386
- config.files = {
476
+ const entries = used.map((group, index) => ({
387
477
  dir: group.dir,
388
478
  pattern: group.pattern,
389
- format
390
- };
479
+ format: formats[index]
480
+ }));
481
+ config.files = entries.length === 1 ? entries[0] : entries;
482
+ let namespaces = [];
483
+ let keyPrefix = "";
391
484
  const token = await findEnvToken(root, io.env);
392
485
  if (token) {
393
486
  const meta = await createClient({
@@ -397,6 +490,8 @@ async function runInit(io, values) {
397
490
  fetch: io.fetch
398
491
  }).meta();
399
492
  config.project ??= meta.project.name;
493
+ namespaces = (meta.namespaces ?? []).map((namespace) => namespace.name);
494
+ keyPrefix = meta.keyConvention?.prefix ?? "";
400
495
  if (values.release) {
401
496
  const release = findRelease(meta.releases, values.release);
402
497
  if (!release) throw new Error(`The project has no release "${values.release}"; it has ${meta.releases.map((item) => item.name).join(", ") || "none"}.`);
@@ -410,6 +505,15 @@ async function runInit(io, values) {
410
505
  if (values.release) config.release = values.release;
411
506
  notes.push(`${TOKEN_ENV} is not set in ${ENV_FILE} or the environment, so file names were not checked against the project's locales.`);
412
507
  }
508
+ if (entries.length > 1) {
509
+ const keys = await Promise.all(used.map((group) => keysOf(root, group)));
510
+ for (const [index, entry] of entries.entries()) {
511
+ if (index === 0) continue;
512
+ const match = inferMatch(keys[index], keys.filter((_, other) => other !== index).flat(), namespaces, keyPrefix);
513
+ if (match) Object.assign(entry, { match });
514
+ else notes.push(`No match inferred for ${entry.dir}; add a "match" (key or namespace) so new keys can be routed there.`);
515
+ }
516
+ }
413
517
  parseConfig(JSON.stringify(config), shown);
414
518
  const text = `${JSON.stringify(config, null, 2)}\n`;
415
519
  const dryRun = values["dry-run"] ?? false;
@@ -444,8 +548,8 @@ async function lookupTexts(io, values, wanted) {
444
548
  platform.push(...page.matches);
445
549
  }
446
550
  const meta = await client.meta();
447
- const [local] = loaded.config.files && meta.sourceLocale ? await readLocalFiles(loaded, [meta.sourceLocale]) : [];
448
- const entries = local?.content.entries ?? {};
551
+ const [local] = loaded.config.files && meta.sourceLocale ? (await readLocalFiles(loaded, [meta.sourceLocale])).locales : [];
552
+ const entries = local?.entries ?? {};
449
553
  const localKeys = matchLocalEntries(entries, platform.map((match) => match.text));
450
554
  return {
451
555
  client,
@@ -497,11 +601,25 @@ async function runMatch(io, values, texts) {
497
601
  // src/pull.ts
498
602
  /** Writes the files and records the base, unless `dryRun`. */
499
603
  async function pullInto(loaded, comparison, options) {
604
+ const plan = await pullLocaleFiles(loaded, comparison, options);
605
+ const kept = options.prune ? 0 : comparison.entries.filter((entry) => !entry.onPlatform && entry.local !== null).length;
606
+ const dirs = [...new Set(comparison.files.map((file) => file.dir))];
500
607
  return {
501
- files: await pullLocaleFiles(loaded, comparison, options),
502
- kept: options.prune ? 0 : comparison.entries.filter((entry) => !entry.onPlatform && entry.local !== null).length
608
+ ...plan,
609
+ kept,
610
+ dirs
503
611
  };
504
612
  }
613
+ /** Whether keys wait for a person: the exit code of `pull` and `sync`. */
614
+ function needsPerson(run) {
615
+ return run.unrouted.length > 0 || run.duplicates.length > 0;
616
+ }
617
+ function describeKeys(io, entries) {
618
+ for (const entry of entries) {
619
+ const where = entry.locations.length > 0 ? entry.locations.map((place) => `${place.relativePath} ${quote(place.value)}`).join(", ") : `no ${entry.locale} text in ${entry.dirs.join(", ")}`;
620
+ io.stdout(` ${entry.key} (${entry.locale}): ${where}; remote ${quote(entry.platform)}\n`);
621
+ }
622
+ }
505
623
  function describePull(io, run, dryRun) {
506
624
  for (const file of run.files) {
507
625
  const parts = [
@@ -514,13 +632,26 @@ function describePull(io, run, dryRun) {
514
632
  }
515
633
  const written = run.files.filter((file) => file.output !== null).length;
516
634
  io.stdout(written === 0 ? "Nothing to write.\n" : `${dryRun ? "Dry run: would write" : "Wrote"} ${plural(written, "file")}.\n`);
517
- if (run.kept > 0) io.stdout(`Kept ${plural(run.kept, "local key")} the project does not have; --prune removes them.\n`);
635
+ if (run.unrouted.length > 0) {
636
+ io.stdout(`Not written, no directory matches ${plural(run.unrouted.length, "key")}:\n`);
637
+ for (const entry of run.unrouted) io.stdout(` ${entry.key} (${entry.locale}): remote ${quote(entry.platform)}\n`);
638
+ io.stdout(`A person picks the directory (${run.dirs.join(", ")}): "localness pull --keys <key> --into <dir>".\n`);
639
+ }
640
+ if (run.duplicates.length > 0) {
641
+ io.stdout(`Not written, ${plural(run.duplicates.length, "duplicate key")} in several directories:\n`);
642
+ describeKeys(io, run.duplicates);
643
+ io.stdout("A person decides: \"localness pull --keys <key>\" writes the remote text to every place; add \"--into <dir>\" for a locale with no place yet; or delete the extra copies by hand.\n");
644
+ }
645
+ if (run.kept > 0) io.stdout(`Kept ${plural(run.kept, "local key")} remote does not have; --prune removes them.\n`);
518
646
  }
519
647
  function pullJson(run, dryRun) {
520
648
  return {
521
649
  dryRun,
522
650
  files: run.files.map(({ output: _, path: __, ...file }) => file),
523
- kept: run.kept
651
+ kept: run.kept,
652
+ unrouted: run.unrouted.map(attention),
653
+ duplicates: run.duplicates.map(attention),
654
+ dirs: run.dirs
524
655
  };
525
656
  }
526
657
  async function runPull(io, values) {
@@ -530,16 +661,20 @@ async function runPull(io, values) {
530
661
  locales: list(values.locales),
531
662
  keys
532
663
  });
664
+ printWarnings(io, comparison.warnings);
533
665
  const kinds = keys ? FORCED_PULL_KINDS : PULL_KINDS;
534
666
  const dryRun = values["dry-run"] ?? false;
535
667
  const run = await pullInto(loaded, comparison, {
536
668
  kinds,
537
669
  prune: values.prune ?? false,
538
- dryRun
670
+ dryRun,
671
+ into: values.into
539
672
  });
540
- const left = comparison.entries.filter((entry) => !kinds.includes(entry.kind) && entry.kind !== "pending-publish" && entry.onPlatform);
673
+ const left = comparison.entries.filter((entry) => !kinds.includes(entry.kind) && entry.kind !== "pending-publish" && entry.kind !== "duplicate" && entry.onPlatform);
674
+ const code = needsPerson(run) ? 1 : 0;
541
675
  if (values.json) {
542
676
  io.stdout(`${JSON.stringify({
677
+ config: configField(io, loaded),
543
678
  ...pullJson(run, dryRun),
544
679
  left: left.map(({ locale, key, kind }) => ({
545
680
  locale,
@@ -547,11 +682,11 @@ async function runPull(io, values) {
547
682
  kind
548
683
  }))
549
684
  }, null, 2)}\n`);
550
- return 0;
685
+ return code;
551
686
  }
552
687
  describePull(io, run, dryRun);
553
- if (left.length > 0) io.stdout(`Left ${countKinds(left)}; "localness diff" shows them, "pull --keys <key>" takes the project's text.\n`);
554
- return 0;
688
+ if (left.length > 0) io.stdout(`Left ${countKinds(left)}; "localness diff" shows them, "pull --keys <key>" takes the remote text.\n`);
689
+ return code;
555
690
  }
556
691
  // src/push.ts
557
692
  /** Never pushed without naming the key: either side may be the newer one. */
@@ -616,12 +751,16 @@ async function runPush(io, values) {
616
751
  locales: list(values.locales),
617
752
  keys
618
753
  });
754
+ printWarnings(io, comparison.warnings);
619
755
  const dryRun = values["dry-run"] ?? false;
620
756
  const planned = await planPushFrom(io, loaded, client, comparison, {
621
757
  kinds: keys ? FORCED_PUSH_KINDS : PUSH_KINDS,
622
758
  dryRun
623
759
  });
624
- if (values.json) io.stdout(`${JSON.stringify(pushJson(planned), null, 2)}\n`);
760
+ if (values.json) io.stdout(`${JSON.stringify({
761
+ config: configField(io, loaded),
762
+ ...pushJson(planned)
763
+ }, null, 2)}\n`);
625
764
  else describePush(io, planned, dryRun);
626
765
  return 0;
627
766
  }
@@ -674,7 +813,7 @@ async function label(io, values, client, mode, [name, ...keys]) {
674
813
  });
675
814
  const found = new Map(result.keys.map((state) => [state.key, state]));
676
815
  const missing = keys.filter((key) => !found.has(key));
677
- if (missing.length > 0) throw new Error(`The project has no key ${missing.join(", ")}.`);
816
+ if (missing.length > 0) throw new Error(`Remote has no key ${missing.join(", ")}.`);
678
817
  const pattern = values.match === void 0 ? null : globToRegExp(values.match);
679
818
  const id = Number(release.id);
680
819
  const targets = (pattern ? result.keys.filter((state) => pattern.test(state.key)) : keys.map((key) => found.get(key))).filter((state) => state.releaseIds.includes(id) === (mode === "remove"));
@@ -1024,32 +1163,56 @@ const AGENT_READS = {
1024
1163
  ],
1025
1164
  codex: [".agents/skills"]
1026
1165
  };
1166
+ /** Folders each agent reads skills from in the home folder, its own first. */
1167
+ const AGENT_READS_GLOBAL = {
1168
+ copilot: [".copilot/skills", ".agents/skills"],
1169
+ claude: [".claude/skills"],
1170
+ cursor: [
1171
+ ".cursor/skills",
1172
+ ".agents/skills",
1173
+ ".claude/skills",
1174
+ ".codex/skills"
1175
+ ],
1176
+ codex: [".agents/skills"]
1177
+ };
1178
+ const PROJECT_SKILLS = {
1179
+ reads: AGENT_READS,
1180
+ dirs: [
1181
+ ".agents/skills",
1182
+ ".claude/skills",
1183
+ ".github/skills",
1184
+ ".cursor/skills"
1185
+ ]
1186
+ };
1187
+ const GLOBAL_SKILLS = {
1188
+ reads: AGENT_READS_GLOBAL,
1189
+ dirs: [
1190
+ ".agents/skills",
1191
+ ".claude/skills",
1192
+ ".copilot/skills",
1193
+ ".cursor/skills",
1194
+ ".codex/skills"
1195
+ ]
1196
+ };
1027
1197
  const AGENTS = Object.keys(AGENT_READS);
1028
1198
  const DEFAULT_AGENTS = [
1029
1199
  "copilot",
1030
1200
  "claude",
1031
1201
  "cursor"
1032
1202
  ];
1033
- /** Tie-break order: the vendor-neutral folder first. */
1034
- const SKILL_DIRS = [
1035
- ".agents/skills",
1036
- ".claude/skills",
1037
- ".github/skills",
1038
- ".cursor/skills"
1039
- ];
1040
1203
  /**
1041
1204
  * The fewest folders every agent reads from: one copy per agent would show the
1042
1205
  * skill twice to agents that read several folders.
1043
1206
  */
1044
- function skillDirsFor(agents) {
1207
+ function skillDirsFor(agents, { reads, dirs: candidates } = PROJECT_SKILLS) {
1045
1208
  const left = new Set(agents);
1046
1209
  const dirs = [];
1047
1210
  while (left.size > 0) {
1048
1211
  let best = "";
1049
1212
  let bestScore = 0;
1050
- for (const dir of SKILL_DIRS) {
1051
- const readers = [...left].filter((agent) => AGENT_READS[agent].includes(dir));
1052
- const own = readers.some((agent) => AGENT_READS[agent][0] === dir);
1213
+ for (const dir of candidates) {
1214
+ const readers = [...left].filter((agent) => reads[agent].includes(dir));
1215
+ const own = readers.some((agent) => reads[agent][0] === dir);
1053
1216
  const score = readers.length + (own ? .5 : 0);
1054
1217
  if (score > bestScore) {
1055
1218
  best = dir;
@@ -1057,7 +1220,7 @@ function skillDirsFor(agents) {
1057
1220
  }
1058
1221
  }
1059
1222
  dirs.push(best);
1060
- for (const agent of left) if (AGENT_READS[agent].includes(best)) left.delete(agent);
1223
+ for (const agent of left) if (reads[agent].includes(best)) left.delete(agent);
1061
1224
  }
1062
1225
  return dirs;
1063
1226
  }
@@ -1147,9 +1310,9 @@ function skillFolder(root, dir) {
1147
1310
  return join(root, ...dir.split("/"), SKILL_NAME);
1148
1311
  }
1149
1312
  /** Installed copies under `root`, in any folder an agent reads. */
1150
- async function findInstalledSkills(root) {
1313
+ async function findInstalledSkills(root, scope = PROJECT_SKILLS) {
1151
1314
  const found = [];
1152
- for (const dir of SKILL_DIRS) {
1315
+ for (const dir of scope.dirs) {
1153
1316
  const folder = skillFolder(root, dir);
1154
1317
  const files = await readSkillFolder(folder);
1155
1318
  if (files !== null) {
@@ -1163,19 +1326,29 @@ async function findInstalledSkills(root) {
1163
1326
  }
1164
1327
  return found;
1165
1328
  }
1329
+ const isOutdated = ({ skill }) => skill.version !== null && skill.version !== version;
1330
+ /** `~/...` under the home folder, else the absolute path. */
1331
+ function homePath(home, path) {
1332
+ const inside = relative(home, path);
1333
+ return inside && !inside.startsWith("..") && !isAbsolute(inside) ? join("~", inside) : path;
1334
+ }
1166
1335
  /** One line on stderr when an installed copy came from another CLI version. */
1167
1336
  async function warnOutdatedSkill(io, values) {
1337
+ const outdatedNote = (where, from, flag) => io.stderr(`localness: the Agent Skill in ${where} is for CLI ${from}, this is ${version}; run "localness skill install${flag}" to update it.\n`);
1168
1338
  const start = await startDir(io, values);
1169
1339
  const root = await repoRoot(start);
1170
1340
  for (let dir = start;; dir = dirname(dir)) {
1171
- const outdated = (await findInstalledSkills(dir)).find(({ skill }) => skill.version !== null && skill.version !== version);
1341
+ const outdated = (await findInstalledSkills(dir)).find(isOutdated);
1172
1342
  if (outdated) {
1173
1343
  const flag = dir === root ? "" : ` --root ${relative(io.cwd, dir) || "."}`;
1174
- io.stderr(`localness: the Agent Skill in ${relative(io.cwd, dirname(outdated.path)) || "."} is for CLI ${outdated.skill.version}, this is ${version}; run "localness skill install${flag}" to update it.\n`);
1344
+ outdatedNote(relative(io.cwd, dirname(outdated.path)) || ".", outdated.skill.version, flag);
1175
1345
  return;
1176
1346
  }
1177
- if (dir === root || dirname(dir) === dir) return;
1347
+ if (dir === root || dirname(dir) === dir) break;
1178
1348
  }
1349
+ const home = io.home ?? homedir();
1350
+ const global = (await findInstalledSkills(home, GLOBAL_SKILLS)).find(isOutdated);
1351
+ if (global) outdatedNote(homePath(home, dirname(global.path)), global.skill.version, " --global");
1179
1352
  }
1180
1353
  const AGENTS_MD = "AGENTS.md";
1181
1354
  const BLOCK_START = "<!-- localness:start -->";
@@ -1184,7 +1357,7 @@ function agentsBlock(skillFile) {
1184
1357
  return `${BLOCK_START}
1185
1358
  ## Localness
1186
1359
 
1187
- The locale JSON files are synced with a Localness project. Before changing them, read \`${skillFile}\` and follow it: move text only with the \`localness\` CLI, show a person the plan before \`localness apply\`, and never settle a conflict on your own.
1360
+ The locale JSON files are synced with a Localness project. Before changing them, read \`${skillFile}\` and follow it: use the \`localness.config.json\` nearest the files you change, move text only with the \`localness\` CLI, show a person the plan before \`localness apply\`, and never settle a conflict on your own.
1188
1361
  ${BLOCK_END}`;
1189
1362
  }
1190
1363
  /** Replaces the marked block, or appends one. */
@@ -1198,12 +1371,16 @@ function withAgentsBlock(text, block) {
1198
1371
  async function runSkill(io, values, subcommand) {
1199
1372
  if (subcommand !== "install") throw new Error(`Unknown skill command: ${subcommand ?? "(none)"}. Run "localness skill install".`);
1200
1373
  const agents = parseAgents(values.agent);
1201
- const root = await rootFor(io, values);
1374
+ const global = values.global ?? false;
1375
+ if (global && (values.root || values["agents-md"])) throw new Error(`--global cannot be combined with ${values.root ? "--root" : "--agents-md"}: it installs in your home folder, outside any repository.`);
1376
+ const home = io.home ?? homedir();
1377
+ const scope = global ? GLOBAL_SKILLS : PROJECT_SKILLS;
1378
+ const root = global ? home : await rootFor(io, values);
1202
1379
  const content = await renderSkill();
1203
1380
  const dryRun = values["dry-run"] ?? false;
1204
1381
  const force = values.force ?? false;
1205
- const installed = await findInstalledSkills(root);
1206
- const dirs = [.../* @__PURE__ */ new Set([...skillDirsFor(agents), ...installed.map(({ dir }) => dir)])];
1382
+ const installed = await findInstalledSkills(root, scope);
1383
+ const dirs = [.../* @__PURE__ */ new Set([...skillDirsFor(agents, scope), ...installed.map(({ dir }) => dir)])];
1207
1384
  const results = [];
1208
1385
  for (const dir of dirs) {
1209
1386
  const folder = skillFolder(root, dir);
@@ -1221,8 +1398,9 @@ async function runSkill(io, values, subcommand) {
1221
1398
  await writeFile(target, text, "utf8");
1222
1399
  }
1223
1400
  }
1401
+ const path = join(folder, SKILL_FILE);
1224
1402
  results.push({
1225
- path: relative(io.cwd, join(folder, SKILL_FILE)),
1403
+ path: global ? path : relative(io.cwd, path),
1226
1404
  action
1227
1405
  });
1228
1406
  }
@@ -1244,9 +1422,13 @@ async function runSkill(io, values, subcommand) {
1244
1422
  agentsMd
1245
1423
  }, null, 2)}\n`);
1246
1424
  else {
1247
- for (const { path, action } of results) io.stdout(action === "modified" ? ` kept ${path}: edited by hand; --force overwrites it\n` : ` ${dryRun && action !== "unchanged" ? `would be ${action}` : action} ${path}\n`);
1425
+ for (const result of results) {
1426
+ const { action } = result;
1427
+ const path = global ? homePath(home, result.path) : result.path;
1428
+ io.stdout(action === "modified" ? ` kept ${path}: edited by hand; --force overwrites it\n` : ` ${dryRun && action !== "unchanged" ? `would be ${action}` : action} ${path}\n`);
1429
+ }
1248
1430
  if (agentsMd) io.stdout(` ${dryRun ? "would update" : "updated"} ${agentsMd}\n`);
1249
- io.stdout(dryRun ? `Dry run: Agent Skill ${version} for ${agents.join(", ")}.\n` : `Agent Skill ${version} for ${agents.join(", ")}. Commit it so every checkout's agents get it.\n`);
1431
+ io.stdout(dryRun ? `Dry run: Agent Skill ${version} for ${agents.join(", ")}.\n` : global ? `Agent Skill ${version} for ${agents.join(", ")}, in every repository. Rerun after upgrading the CLI.\n` : `Agent Skill ${version} for ${agents.join(", ")}. Commit it so every checkout's agents get it.\n`);
1250
1432
  }
1251
1433
  return refused.length > 0 ? 2 : 0;
1252
1434
  }
@@ -1268,7 +1450,7 @@ async function runSuggestName(io, values, text) {
1268
1450
  io.stdout(`${suggestion.key}${confidence}\n`);
1269
1451
  if (suggestion.alternatives?.length) io.stdout(`Alternatives: ${suggestion.alternatives.map((item) => item.key).join(", ")}\n`);
1270
1452
  if (suggestion.violations.length > 0) io.stdout(`Breaks the project's key convention: ${suggestion.violations.join(", ")}\n`);
1271
- for (const duplicate of suggestion.duplicates) io.stdout(`Already in the project: ${duplicate.key} ${JSON.stringify(duplicate.sourceText)}${duplicate.sameSourceText ? ", same text; reuse it" : ""}\n`);
1453
+ for (const duplicate of suggestion.duplicates) io.stdout(`Already on remote: ${duplicate.key} ${JSON.stringify(duplicate.sourceText)}${duplicate.sameSourceText ? ", same text; reuse it" : ""}\n`);
1272
1454
  if (suggestion.reason) io.stdout(`${suggestion.reason}\n`);
1273
1455
  return 0;
1274
1456
  }
@@ -1280,17 +1462,20 @@ async function runSync(io, values) {
1280
1462
  locales: list(values.locales),
1281
1463
  keys: list(values.keys)
1282
1464
  });
1465
+ printWarnings(io, comparison.warnings);
1283
1466
  const dryRun = values["dry-run"] ?? false;
1284
1467
  const pulled = await pullInto(loaded, comparison, {
1285
1468
  kinds: SYNC_PULL_KINDS,
1286
1469
  prune: false,
1287
- dryRun
1470
+ dryRun,
1471
+ into: values.into
1288
1472
  });
1289
1473
  const pushed = await planPushFrom(io, loaded, client, comparison, {
1290
1474
  kinds: PUSH_KINDS,
1291
1475
  dryRun
1292
1476
  });
1293
1477
  if (values.json) io.stdout(`${JSON.stringify({
1478
+ config: configField(io, loaded),
1294
1479
  pull: pullJson(pulled, dryRun),
1295
1480
  push: pushJson(pushed)
1296
1481
  }, null, 2)}\n`);
@@ -1298,7 +1483,7 @@ async function runSync(io, values) {
1298
1483
  describePull(io, pulled, dryRun);
1299
1484
  describePush(io, pushed, dryRun);
1300
1485
  }
1301
- return 0;
1486
+ return needsPerson(pulled) ? 1 : 0;
1302
1487
  }
1303
1488
  // src/run.ts
1304
1489
  const SYNC_COMMANDS = /* @__PURE__ */ new Set([
@@ -1314,13 +1499,13 @@ Usage: localness <command> [options]
1314
1499
 
1315
1500
  Commands:
1316
1501
  init Find the repository's locale files and write localness.config.json
1317
- diff Compare the locale files with the project (exit 1 when they differ)
1318
- pull Write the project's changes into the locale files
1319
- push Plan sending local changes to the project; writes nothing
1320
- apply <id> Write a plan to the project (no id: list plans)
1321
- sync pull the project's changes, then plan a push of local ones
1502
+ diff Compare the locale files with remote (exit 1 when they differ)
1503
+ pull Write remote changes into the locale files
1504
+ push Plan sending local changes to remote; writes nothing
1505
+ apply <id> Write a plan to remote (no id: list plans)
1506
+ sync pull remote changes, then plan a push of local ones
1322
1507
  match <text...> Existing keys whose source text equals each text
1323
- suggest-name <text> Ask the project's AI for a key name; writes nothing
1508
+ suggest-name <text> Ask Localness AI for a key name; writes nothing
1324
1509
  review start <file> Open a page to decide, per extracted text, which key it
1325
1510
  gets (reuse, new or skip): in the editor when the
1326
1511
  Localness extension has the project open, else the browser
@@ -1330,14 +1515,16 @@ Commands:
1330
1515
  List releases, pick the one new keys get, create one,
1331
1516
  or label existing keys
1332
1517
  skill install Install the Agent Skill that teaches coding agents
1333
- this workflow, at the repository root
1518
+ this workflow, at the repository root (or with
1519
+ --global, in your home folder)
1334
1520
 
1335
1521
  Options:
1336
1522
  --config <path> Config file (default: nearest localness.config.json)
1337
1523
  --keys <a,b> Only these keys; for pull and push, take that side even
1338
1524
  when both changed
1339
- --locales <en,ja> Only these platform locales
1340
- --prune Also remove keys the project does not have (pull)
1525
+ --locales <en,ja> Only these project locales
1526
+ --prune Also remove keys remote does not have (pull)
1527
+ --into <dir> Configured directory for keys with no place yet (pull, sync)
1341
1528
  --dry-run Show what would happen (init, pull, push, sync, skill)
1342
1529
  --json Machine-readable output
1343
1530
  --base-url <url> Localness instance URL (init)
@@ -1349,9 +1536,12 @@ Options:
1349
1536
  Skill (skill install)
1350
1537
  --agent <a,b> Agents the Skill is for: copilot, claude, cursor, codex
1351
1538
  or all (default: copilot,claude,cursor)
1352
- --agents-md Also point AGENTS.md at the Skill (skill install)
1539
+ --agents-md Also point AGENTS.md at the Skill (skill install; not
1540
+ with --global)
1353
1541
  --root <path> Folder the agents open, when it is not the git root
1354
- (skill install)
1542
+ (skill install; not with --global)
1543
+ --global Install the Skill in your home folder for every
1544
+ repository (skill install)
1355
1545
  --release <name> Release new keys are labelled with (init)
1356
1546
  --none No release for new keys (releases use)
1357
1547
  --use Also use the release created (releases create)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@localness/cli",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Sync a repository's locale JSON files with a Localness project.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -24,7 +24,7 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@localness/contract": "^0.5.1",
27
- "@localness/sdk": "0.1.1"
27
+ "@localness/sdk": "0.2.0"
28
28
  },
29
29
  "scripts": {
30
30
  "build": "tsdown",
package/skill/SKILL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: localness
3
- description: Sync this repository's locale JSON files with its Localness translation project through the `localness` CLI. Use when adding, changing, renaming or removing translatable strings or locale keys, when extracting hardcoded text into locale keys, when touching files under the locale directory named in localness.config.json, or when locale files and the Localness project disagree.
3
+ description: Sync this repository's locale JSON files with its Localness translation project through the `localness` CLI. Use when adding, changing, renaming or removing translatable strings or locale keys, when extracting hardcoded text into locale keys, when touching files under the locale directory named in localness.config.json, or when the locale files and remote disagree.
4
4
  metadata:
5
5
  localness-cli: '{{version}}'
6
6
  localness-hash: ''
@@ -8,15 +8,20 @@ metadata:
8
8
 
9
9
  # Localness
10
10
 
11
- The locale JSON files in this repository are synced with a Localness project. The `localness` CLI is the only way to move text between them; if it is not on PATH, run `npx @localness/cli` instead. Each command uses the nearest `localness.config.json` above the working directory, so run it from the package that owns the config. That file names the locale directory, its layout and the project.
11
+ The locale JSON files in this repository are synced with a Localness project. The `localness` CLI is the only way to move text between them; if it is not on PATH, run `npx @localness/cli` instead. Each command uses the nearest `localness.config.json` above the working directory, so run it from the package that owns the config. That file names the locale directories (`files` is one directory or a list), their layout and the project. "Remote" means that project's texts on the Localness instance, "local" the locale files; in JSON output `platform` (as in `platform-added` or `onPlatform`) means remote.
12
+
13
+ ## Several configs
14
+
15
+ A repository may have several `localness.config.json` files (one per package or app). Use the one nearest the files you change: run the CLI from its folder, or pass `--config <path>`. If unsure, list the config files first. Each config has its own token (`.env.local`), `.localness/` (base, plans, review input) and project. For a task across packages, run `diff`, `pull` and `push` per config and show each plan separately; `apply <id>` must use the config that made the plan. Every `--json` output names its `config`: check it.
12
16
 
13
17
  ## Rules
14
18
 
15
- - Write to the project only with `localness apply <id>`, and only after a person approved that plan in this conversation. Never write through the HTTP API, an MCP server or the web app.
16
- - Never copy text between the locale files and the project by hand: `pull` brings the project's text in, `push` plans sending yours.
17
- - Never decide a `conflict` or `different` key yourself. Show each side's text and let a person choose.
19
+ - Write to remote only with `localness apply <id>`, and only after a person approved that plan in this conversation. Never write through the HTTP API, an MCP server or the web app.
20
+ - Never copy text between the locale files and remote by hand: `pull` brings the remote text in, `push` plans sending yours.
21
+ - Never decide a `conflict`, `different` or `duplicate` key yourself. Show each side's text and let a person choose.
22
+ - Never choose the folder of a key yourself: the CLI routes new keys by the config's `match` rules, and a key it cannot route (`unrouted`) waits for a person to name the directory.
18
23
  - Never pass `--prune` unless a person asked to delete those keys from the files.
19
- - Edit locale files only for what the task asks for. New or changed product text goes in the source-locale file; other locales are translated in the project unless the task supplies the translations.
24
+ - Edit locale files only for what the task asks for. New or changed product text goes in the source-locale file; other locales are translated in Localness unless the task supplies the translations.
20
25
  - Never read, print, ask for or write `LOCALNESS_TOKEN`. Never edit or commit `.localness/`.
21
26
  - `apply` writes drafts. Publishing happens in the Localness web app, so never say the text is live.
22
27
 
@@ -24,12 +29,12 @@ The locale JSON files in this repository are synced with a Localness project. Th
24
29
 
25
30
  Read the reference for the task before running anything:
26
31
 
27
- | Task | Read |
28
- | ----------------------------------------------------------------------------- | ------------------------------------------------------ |
29
- | Locale files and the project disagree; adding or changing keys and their text | [references/sync.md](references/sync.md) |
30
- | Moving hardcoded user-facing text in code into locale keys | [references/extract.md](references/extract.md) |
31
- | Release labels on keys, or the release new keys get | [references/releases.md](references/releases.md) |
32
- | Reading a command's `--json` output | [references/json-shapes.md](references/json-shapes.md) |
32
+ | Task | Read |
33
+ | ------------------------------------------------------------------------ | ------------------------------------------------------ |
34
+ | Locale files and remote disagree; adding or changing keys and their text | [references/sync.md](references/sync.md) |
35
+ | Moving hardcoded user-facing text in code into locale keys | [references/extract.md](references/extract.md) |
36
+ | Release labels on keys, or the release new keys get | [references/releases.md](references/releases.md) |
37
+ | Reading a command's `--json` output | [references/json-shapes.md](references/json-shapes.md) |
33
38
 
34
39
  ## Problems
35
40
 
@@ -3,14 +3,14 @@
3
3
  When a person asks to move hardcoded user-facing text into locale keys:
4
4
 
5
5
  1. Only look in the files or folders the person named. Skip text that is not shown to users: log messages, ids, CSS classes, URLs, test data, and text already passed to the i18n function.
6
- 2. Run `localness match --json "<text>" "<text>" ...` with every string at once. Keys come from the project (`source: "platform"`) and from the source-locale file when not pushed yet (`source: "local"`). A text with exactly one key reuses it. A text with several keys lists them all for the person to pick; never pick one yourself. Mark local keys in the table, and flag one whose name breaks a strict rule of `convention` (prefix, characters other than letters, digits, `.`, `_`, `-`, or an empty segment): push will block it.
6
+ 2. Run `localness match --json "<text>" "<text>" ...` with every string at once. Keys come from remote (`source: "platform"`) and from the source-locale file when not pushed yet (`source: "local"`). A text with exactly one key reuses it. A text with several keys lists them all for the person to pick; never pick one yourself. Mark local keys in the table, and flag one whose name breaks a strict rule of `convention` (prefix, characters other than letters, digits, `.`, `_`, `-`, or an empty segment): push will block it.
7
7
  3. Name a key for each text without one, using `convention` and `namespaces` from the same output:
8
8
  - With a `prefix`, start the name with it and `separator`. This is required.
9
9
  - Prefer `separator`, write each segment in `style` (`snake_case` or `camelCase`; `none` means match the neighbouring keys), and use at most `maxDepth` segments after the prefix. These are suggestions: push still creates a key that misses them and lists it in `warnings`.
10
10
  - Put the key under the namespace of the page or feature it belongs to when one fits; namespace names follow the prefix.
11
11
  - Follow `guidance` when it is set, and stay close to the neighbouring keys in the locale file.
12
12
  - Never reuse a name another key already has.
13
- 4. Let the person review on a page. Write `{ "items": [{ "text", "file", "line", "key" }] }` to `.localness/review-input.json` next to the config, one item per text in the order of your list: `file` relative to the current folder, `key` the name you proposed (leave it out for texts with an existing key). Run `localness review start .localness/review-input.json --json`; it opens a page where the person picks reuse, new key or skip per text, edits names checked live against the convention, and approves. With `openedIn: "editor"` the page opened as a tab in their editor (the Localness extension has the project open); with `openedIn: "browser"` give them the `url` it prints. Then run `localness review wait <id>` until `status` is no longer `pending`. `approved` returns `items: [{ index, text, file, line, action, key, source }]`: `reuse` means use `key` (`source: "local"` is a key not pushed yet), `create` means add `key` with `text`, `skip` means leave the text. `cancelled` means change nothing and stop.
13
+ 4. Let the person review on a page. Write `{ "items": [{ "text", "file", "line", "key" }] }` to `.localness/review-input.json` next to the config you use (the one nearest the files you change), one item per text in the order of your list: `file` relative to the current folder, `key` the name you proposed (leave it out for texts with an existing key). Run `localness review start .localness/review-input.json --json`; it opens a page where the person picks reuse, new key or skip per text, edits names checked live against the convention, and approves. With `openedIn: "editor"` the page opened as a tab in their editor (the Localness extension has the project open); with `openedIn: "browser"` give them the `url` it prints. Then run `localness review wait <id>` until `status` is no longer `pending`. `approved` returns `items: [{ index, text, file, line, action, key, source }]`: `reuse` means use `key` (`source: "local"` is a key not pushed yet), `create` means add `key` with `text`, `skip` means leave the text. `cancelled` means change nothing and stop.
14
14
  Fall back to a table in the chat when `review start` fails (no browser, remote machine) or the person asks for it. Columns: `#` (1, 2, 3, ...), text, file and line, then either the key to reuse (with its alternatives) or the new name. Below the table, tell the person they can approve everything, or reply with row numbers and what to do, for example `2 use auth_sign_in_title`, `5 rename to cart_coupon_label`, `7 skip`. Apply their instructions, show the updated table with the same numbers, and wait again.
15
15
  Either way, change no files before they approve.
16
16
  5. After approval, add the new keys with their text to the source-locale file only, and replace each string in the code with the i18n call the file already uses (same function, import and argument style). Reused keys need no locale file change; skipped texts stay as they are.
@@ -1,10 +1,15 @@
1
1
  # JSON shapes
2
2
 
3
- - `diff --json`: `{ sourceLocale, locales, content, hasBase, files, differences: [{ locale, key, kind, local, platform, draft, base, onPlatform }] }`
4
- - `push --json`: `{ id, path, expiresAt, sourceLocale, release, keys: [{ key, create, locales: { <locale>: { text, platform, draft } } }], blocked, warnings, leftOut }`; `id` is null when there is nothing to push; `release` is the name new keys get, or null.
5
- - `apply <id> --json`: `{ id, written: [{ key, created, locales }], failed }`
3
+ `platform` in field names, kinds and `source` values means remote, `local` the locale files. In `diff --json`, `platform` is the published remote text, `draft` the remote working text and `onPlatform` whether remote has the key.
4
+
5
+ `diff`, `pull`, `push`, `sync` and `apply <id>` also have `config`: the config file used, relative to the working directory with `/` separators (for example `apps/web/localness.config.json`).
6
+
7
+ - `diff --json`: `{ config, sourceLocale, locales, content, hasBase, files, differences: [{ locale, key, kind, local, platform, draft, base, onPlatform, target, locations, dirs }] }`; `files` maps each locale to its file paths, one per configured directory; `target` is `{ dir, by }` (`by`: `existing`, `namespace`, `key`, `fallback` or `unrouted`, then `dir` is null); `locations` are where this locale has the key (`{ dir, relativePath, value, path }`), `dirs` every directory holding it in any locale.
8
+ - `pull --json`: `{ config, dryRun, files: [{ locale, dir, relativePath, created, set, removed, skipped }], kept, unrouted, duplicates, dirs, left }`; `sync --json` is `{ config, pull, push }` with the same `pull` part (no `config`, no `left`) and the `push --json` shape (no `config`). `unrouted` and `duplicates` are `[{ locale, key, platform, dirs, locations: [{ dir, relativePath, value }] }]`, `dirs` the directories `--into` accepts. Exit code 1 when either is not empty.
9
+ - `push --json`: `{ config, id, path, expiresAt, sourceLocale, release, keys: [{ key, create, locales: { <locale>: { text, platform, draft } } }], blocked, warnings, leftOut }`; `id` is null when there is nothing to push; `release` is the name new keys get, or null.
10
+ - `apply <id> --json`: `{ config, id, written: [{ key, created, locales }], failed }`; `apply --json` without an id lists the saved plans of that config: `[{ id, createdAt, expiresAt, keys }]`.
6
11
  - `match --json`: `{ matches: [{ text, keys: [{ source, key, sourceText, ... }] }], convention, namespaces }`. `matches` has one entry per text in order; a match is the same source text after whitespace normalisation. `source: "platform"` keys also have `id`, `draft` and `releaseIds`; `source: "local"` keys exist only in the source-locale file and are not pushed yet. `convention` is `{ prefix, separator, style, maxDepth, guidance }` (`style` is `snake_case`, `camelCase` or `none`) (`prefix` has no trailing separator, `''` means none; `guidance` is the project's naming advice or null), or null when the server predates it. `namespaces` lists the project's namespace names, relative to the prefix.
7
12
  - `review start --json`: `{ id, url, rows }`. Input file: `{ items: [{ text, file?, line?, key? }] }`.
8
13
  - `review wait <id>`: `{ id, status, items }`; `status` is `pending` (also has `url`; run it again), `approved` or `cancelled` (`items` empty). Items: `{ index, text, file, line, action, key, source }`, `action` is `reuse`, `create` or `skip`; `skip` has no `key`, only `reuse` has `source` (`platform` or `local`).
9
- - `blocked` in `push --json`: `[{ locale, key, reason, violations? }]`; `reason` is `no-source-text`, `reserved-name` or `key-name`, and `violations` lists what a `key-name` key breaks: `prefix`, `charset` or `segment`.
14
+ - `blocked` in `push --json`: `[{ locale, key, reason, violations? }]`; `reason` is `no-source-text`, `reserved-name`, `key-name` or `duplicate` (the key is in several directories with different texts), and `violations` lists what a `key-name` key breaks: `prefix`, `charset` or `segment`.
10
15
  - `warnings` in `push --json`: `[{ key, violations }]`, new keys that are still created but miss a suggestion: `separator`, `case` or `depth`.
@@ -3,30 +3,42 @@
3
3
  1. Run `localness diff --json`. Exit code 0: nothing differs. 1: differences. 2: error.
4
4
  2. Sort each difference by `kind` (table below) and list everything that needs a person.
5
5
  3. Ask the person about those keys and wait for the answer.
6
- 4. Bring the project's text in: `localness pull`, or `localness pull --keys <a,b>` for keys the person gave to the project.
7
- 5. Plan local changes: `localness push --json`, or `localness push --keys <a,b> --json` for keys the person gave to the local side. It writes nothing to the project.
6
+ 4. Bring the remote text in: `localness pull`, or `localness pull --keys <a,b>` for keys the person gave to remote.
7
+ 5. Plan local changes: `localness push --json`, or `localness push --keys <a,b> --json` for keys the person gave to the local side. It writes nothing to remote.
8
8
  6. Show the plan to the person: its id, and for each key whether it is created or updated and every locale's old → new text. Also show `blocked`, `warnings` and `leftOut`.
9
9
  7. Only after the person approves, run `localness apply <id>`. If it reports the plan stale or expired, nothing was written: run `diff` again and start over; never retry the same id.
10
10
  8. Report what was written, and that drafts wait for a publish in the web app.
11
11
 
12
+ With several `localness.config.json` files, do these steps once per config the task touches, from that config's folder or with `--config <path>`. Plans live in that config's `.localness/plans/`, so run `apply <id>` with the same config; the `config` field of `push --json` and `apply --json` must match.
13
+
12
14
  `localness sync` does steps 4 and 5 together for the unambiguous kinds. `--dry-run` previews `pull`, `push` and `sync`.
13
15
 
14
- | `kind` | Meaning | Action |
15
- | ------------------ | ------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
16
- | `platform-added` | The project has text the file lacks | `pull` |
17
- | `platform-changed` | The project changed it; the file did not | `pull` |
18
- | `local-added` | The file has text the project lacks | `push` |
19
- | `local-changed` | The file changed it; the project did not | `push` |
20
- | `pending-publish` | The file matches an unpublished draft | Nothing; it gets published in the web app |
21
- | `conflict` | Both sides changed, or a push would overwrite someone's draft | Ask; then `pull --keys` or `push --keys` |
22
- | `different` | The texts differ and there is no base yet | Ask; then `pull --keys` or `push --keys` |
23
- | `platform-deleted` | The key left the project; the file still has it | Ask; remove it from the file, or `pull --prune` when the person wants all of them gone |
24
- | `local-deleted` | The file dropped a key the project still has | Ask; the CLI never deletes project keys, a person does that in the web app |
16
+ | `kind` | Meaning | Action |
17
+ | ------------------ | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
18
+ | `platform-added` | Remote has text the file lacks | `pull` |
19
+ | `platform-changed` | Remote changed it; the file did not | `pull` |
20
+ | `local-added` | The file has text remote lacks | `push` |
21
+ | `local-changed` | The file changed it; remote did not | `push` |
22
+ | `pending-publish` | The file matches an unpublished draft | Nothing; it gets published in the web app |
23
+ | `conflict` | Both sides changed, or a push would overwrite someone's draft | Ask; then `pull --keys` or `push --keys` |
24
+ | `different` | The texts differ and there is no base yet | Ask; then `pull --keys` or `push --keys` |
25
+ | `platform-deleted` | The key left remote; the file still has it | Ask; remove it from the file, or `pull --prune` when the person wants all of them gone |
26
+ | `local-deleted` | The file dropped a key remote still has | Ask; the CLI never deletes keys on remote, a person does that in the web app |
27
+ | `duplicate` | The key is in several directories with different texts, or remote added a locale to it | Ask; show every location and the remote text (see "Several directories") |
25
28
 
26
- When `hasBase` is false (the first sync), every changed text is `different`. Say so before pulling: a plain `pull` takes the project's text for all of them.
29
+ When `hasBase` is false (the first sync), every changed text is `different`. Say so before pulling: a plain `pull` takes the remote text for all of them.
27
30
 
28
31
  ## New keys
29
32
 
30
- - Name a new key after the project's key convention (`localness match --json` prints it as `convention`) and the neighbouring keys in the same file. `push` blocks a new key whose name breaks a strict rule (prefix, characters, empty segment), with reason `key-name`: rename it in the locale file and the code, then plan again. New keys off the suggested separator, casing or depth are created and listed in `warnings`; mention them, but they need no rename. `localness suggest-name "<source text>"` asks the project's AI for one name, but it is slow, uses the project's AI quota and needs a read & write token: only use it for a few strings a person asked about. Names starting with `__unnamed_` are reserved.
33
+ - Name a new key after the project's key convention (`localness match --json` prints it as `convention`) and the neighbouring keys in the same file. `push` blocks a new key whose name breaks a strict rule (prefix, characters, empty segment), with reason `key-name`: rename it in the locale file and the code, then plan again. New keys off the suggested separator, casing or depth are created and listed in `warnings`; mention them, but they need no rename. `localness suggest-name "<source text>"` asks Localness AI for one name, but it is slow, uses the project's AI quota and needs a read & write token: only use it for a few strings a person asked about. Names starting with `__unnamed_` are reserved.
31
34
  - A new key needs its text in the source-locale file. `apply` creates the key and publishes that source text; text in other locales becomes drafts.
32
35
  - A plan holds at most 200 keys and expires after an hour.
36
+
37
+ ## Several directories
38
+
39
+ `files` may list several directories (for example `src/locales/default` and `src/locales/boostprime`). A key lives in the directory that already has it; a new key goes to the first directory whose `match` fits (`key` regex, project `namespace`), else to the one without a `match`. `diff --json` shows each difference's `target` (`{ dir, by }`), `locations` and `dirs`.
40
+
41
+ - `pull` and `sync` exit 1 when keys wait for a person. Their JSON lists them in `unrouted` and `duplicates`, and `dirs` holds the configured directories.
42
+ - `unrouted`: a new key that no `match` fits, with no fallback directory. Never choose the folder yourself: list the keys and the `dirs` and ask. Then `localness pull --keys <a,b> --into <dir>`; the key stays in that directory afterwards.
43
+ - `duplicate`: a key in more than one directory. If its texts are equal everywhere, `pull` updates every copy and `push` works as usual. If they differ, or remote added a locale the key has no file for, `pull`, `push` and `sync` skip it. Show each location's text and the remote text, and let a person pick: `pull --keys <key>` writes the remote text to every copy (add `--into <dir>` for a locale with no copy yet), or the person deletes the extra copies by hand.
44
+ - The git-sync `locale-files` setting in Localness is still a single directory; the multi-directory layout exists only in `localness.config.json`.