@wirecat/cli-core 0.714.0 → 0.716.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/dist/background/lock.d.ts +7 -0
  3. package/dist/background/lock.js +15 -0
  4. package/dist/cli/account-remove.d.ts +14 -0
  5. package/dist/cli/account-remove.js +2 -2
  6. package/dist/cli/account-rename.d.ts +15 -0
  7. package/dist/cli/account-rename.js +240 -0
  8. package/dist/cli/bot/api.js +2 -1
  9. package/dist/cli/documents/words.d.ts +1 -1
  10. package/dist/cli/index.d.ts +1 -0
  11. package/dist/cli/index.js +1 -0
  12. package/dist/cli/messenger/account-command.js +6 -0
  13. package/dist/cli/messenger/serve-command.js +16 -1
  14. package/dist/cli/messenger/server-command.js +4 -2
  15. package/dist/cli/profile-files.js +1 -0
  16. package/dist/cli/profile-store.d.ts +31 -0
  17. package/dist/cli/profile-store.js +64 -0
  18. package/dist/cli/service-api.js +31 -3
  19. package/dist/content/cli/store.d.ts +4 -0
  20. package/dist/content/cli/store.js +3 -0
  21. package/dist/content/index.d.ts +1 -0
  22. package/dist/content/index.js +1 -0
  23. package/dist/content/manifest/manifest.d.ts +34 -10
  24. package/dist/content/manifest/manifest.js +32 -15
  25. package/dist/content/manifest/source.js +44 -6
  26. package/dist/content/manifest/writer.js +64 -34
  27. package/dist/content/source.d.ts +5 -0
  28. package/dist/content/sync.js +31 -8
  29. package/dist/content/testing/manifest-fake.d.ts +6 -1
  30. package/dist/content/testing/manifest-fake.js +51 -23
  31. package/dist/content/writes.js +2 -1
  32. package/dist/crm/cli/store.d.ts +4 -30
  33. package/dist/crm/cli/store.js +3 -63
  34. package/dist/documents/html-markdown.js +2 -1
  35. package/dist/errors/reasons.js +8 -0
  36. package/dist/search/lucene/types.d.ts +2 -0
  37. package/dist/search/lucene/types.js +8 -0
  38. package/dist/store/sqlite/account-groups.js +18 -2
  39. package/dist/store/sqlite/admin-statistics.js +3 -2
  40. package/dist/store/sqlite/lucene.js +2 -2
  41. package/dist/store/sqlite/migrations.generated.js +2 -2
  42. package/dist/tracker/cli/index.js +9 -3
  43. package/dist/tracker/index.d.ts +1 -1
  44. package/dist/tracker/index.js +1 -1
  45. package/dist/tracker/sync.d.ts +8 -0
  46. package/dist/tracker/sync.js +29 -0
  47. package/dist/tracker/tasks.d.ts +24 -4
  48. package/dist/tracker/tasks.js +164 -18
  49. package/dist/tracker/testing/manifest-fake.js +13 -1
  50. package/dist/tracker/testing/source-contract.js +14 -0
  51. package/dist/tracker/testing/source.d.ts +2 -0
  52. package/dist/tracker/testing/source.js +2 -0
  53. package/package.json +1 -1
  54. package/parity.json +11 -0
package/CHANGELOG.md CHANGED
@@ -5,6 +5,93 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.716.0 — 21.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A content manifest writes pages: `writes.page`.** It names a page's own create, update, trash and delete calls,
13
+ and its `fields` when they differ from a post's. `posts create --type page` and every write to a page then go by
14
+ those calls, and the answer stays a page in the copy. Without it a page write is still refused as
15
+ `content.write-unsupported`, and so are tags on a type whose fields have none
16
+ ([CONTENT.md](docs/dev/CONTENT.md#content-from-a-manifest)).
17
+ - **`optional.fallback`: a refused call is sent again in a simpler form.** It names query values over the call's own
18
+ (WordPress: `context: "view"` for the users, which only an administrator lists with `context=edit`). An editor or
19
+ an author then gets the authors with published posts, by name and without e-mail, and the gap says the fallback's
20
+ message. `contentManifestFake` answers that form of a `denied` operation, and its new `hidden` names rows a
21
+ sign-in may not see.
22
+ - **`openContentStore`** (`@wirecat/cli-core/content`): the store helper of a content CLI's `open`, so content no
23
+ longer opens the store with the CRM's `openCrmStore`. Both come from `openProfileStore`; `openCrmStore` stays.
24
+
25
+ ### Fixed
26
+
27
+ - **An author or a contributor no longer lists every post on every sync, and sees a post deleted for good.** A gap
28
+ that is a right the role lacks (`optional.requires`, `needs`, `fallback`; `ContentGap.lasting`) now lets the cursor
29
+ move on, and the id pass reads each post it no longer lists once more by its id: only a 404 marks it deleted, a
30
+ refusal keeps it. The cursor keeps the rights the role lacked; once it has one more, the kind is listed in full
31
+ again. Only an entity with a `get` gives such a gap; without one it still holds the pass. A post's tags in a
32
+ manifest whose `writes.fields` has no `terms` are now refused instead of dropped without a word.
33
+ - **A post's text keeps its `-` list marker.** `htmlToMarkdown` wrote `* one` for `- one`, so a body read back
34
+ differed from the file it was written from. A stored post with a list gets one new revision the next time it is read.
35
+ - **`content.schedule-past` names `--at-time`,** the option `posts publish` takes, not `--at`.
36
+
37
+ ## 0.715.0 — 21.11.2026
38
+
39
+ ### Added
40
+
41
+ - **`<tool> <profile> account rename <new>` gives a profile another name and keeps it signed in.** It moves the
42
+ profile's keyring entries (cli-core's `token:<profile>` and the tool's own), its config sections, its files, the
43
+ store's record of which account it is, and its entries in account groups; the account's messages stay where they
44
+ are. It reuses the `account remove` hooks, asked for the old and the new name, plus one new optional hook,
45
+ `signIn`, that names where the sign-in lives. `--dry-run` lists the moves; it asks first, or `--yes`. It refuses a
46
+ taken name, a profile a serve, service, schedule or sync uses, a bot profile, and a run with moved folders.
47
+ A messenger gets it by setting `accountRemoval.signIn`; another CLI mounts `accountRenameCommand(app, removal)`
48
+ beside `account remove` ([guide](docs/dev/ACCOUNT-REMOVAL.md#renaming-a-profile)).
49
+ - **`server status` says when the store was last current (`current_at`).** `serve` writes the time beside its lock
50
+ when it connects, every minute while it runs and as it stops, and the file stays after it stops. A messenger with
51
+ no full sync, such as WhatsApp, now has a time to show once serve is off; the text answer says "The store was
52
+ current at …". `account remove` and `account rename` take the file with the profile.
53
+ - **Issues assigned to you become your tasks.** A tracker sync (Linear first) now makes each open issue assigned to the
54
+ signed-in user a task, so it shows in memo's and Desktop's task lists with no new screen. The task's title is the
55
+ issue's key and title (`ENG-12 Fix login`) and follows later renames. It closes, with a reason, when the issue is
56
+ completed, canceled, archived, deleted, unassigned or assigned to someone else, and opens again when the issue comes
57
+ back to you. A task you closed yourself stays closed, one you reopened is not closed again, and nothing is written
58
+ back to the tracker. `issues assign` tasks now carry the title too. The sync's answer says what it did in `tasks`
59
+ ([TRACKER.md](docs/dev/TRACKER.md#an-issue-as-the-owners-task)).
60
+ - **`trackerSourceContract` checks `self()`**: when a tracker has it, it names one of the tracker's users.
61
+ `fakeTrackerSource` takes `self`, and `trackerManifestFake` answers `self` with its first user.
62
+
63
+ ### Fixed
64
+
65
+ - **A `deny` on a service `api` call refuses it before its body is read.** A call whose key is `deny` (or
66
+ `readonly`, for a write) answered `validation_error` (exit 2) when a required body was left out or did not match
67
+ the schema, because every key was checked only when the call was sent. Now `api.<operation>` and each manifest key
68
+ that does not depend on the body refuse first, with `permission_error` (exit 5) and the key in
69
+ `details.permission`; an MCP call runs the same command, so it refuses alike. A key that depends on the body is
70
+ still checked once the body is read, and `ask` still asks there. A CLI's `before` hook on `generatedApiCommand` now
71
+ runs before the flag values are validated too.
72
+ - **The `api` group of a GraphQL service names its schema.** Its help said "one command per operation of its OpenAPI
73
+ document" for Linear too; a group whose every operation is GraphQL now says "of its GraphQL schema". An OpenAPI
74
+ CLI's help is unchanged.
75
+ - **max-cli is off the parity known-broken list.** max-cli#984 adopted cli-core 0.714.0, so a release fails again when
76
+ max-cli breaks. Only whatsapp-cli stays listed.
77
+ - **SQLite 3.54 (Node 24.22) no longer breaks store version 31, combined search or the admin byte counts.** SQLite
78
+ 3.54 stopped passing a subquery's JSON subtype up, so version 31 wrote each app's profiles and each account group as
79
+ a string inside the setting, and a profile or group search then lost them; version 31 now wraps both in `json()`. A
80
+ store that already ran version 31 on SQLite 3.54 is read as if it had not, and its next profile or group save writes
81
+ the setting whole again. The admin statistics' message byte count wraps its attachments the same way.
82
+ - **A search SQLite refuses as too large answers `query.too-large`.** On SQLite 3.54 a combined message search of
83
+ about 53 words or more stopped with SQLite's own "nested too deep" error; it now gets the same refusal as a query
84
+ over the node budget, so a caller tells the person to search for less.
85
+ - **A tracker task you reopened stays open past your next change.** After a sync closed the task of an issue assigned
86
+ to you, your reopen held only while it was the task's last status change: moving the task on to in progress let
87
+ the next sync close it again. Any status change of yours after the sync's close now counts. It holds for good
88
+ while the issue goes to someone else or to no one, and for any other close until the issue has been open work
89
+ again, so a later completion closes the task again ([TRACKER.md](docs/dev/TRACKER.md#an-issue-as-the-owners-task)).
90
+ - **A tracker task the sync opens again keeps the status it had**, such as in progress, instead of open.
91
+ - **`issues assign` on an issue the sync already made a task of makes that task your pick.** It opens the task again
92
+ when it was closed, where it answered the closed task, and the issue going to someone else no longer closes it.
93
+ - **Only the sync's own close is one your reopen overrules**; an agent that closed the task is not the sync.
94
+
8
95
  ## 0.714.0 — 19.11.2026
9
96
 
10
97
  ### Fixed
@@ -21,5 +21,12 @@ export declare const holdLock: (path: string, lock: Lock) => void;
21
21
  export declare const takeLock: (path: string, lock: Lock) => Lock | undefined;
22
22
  /** Only the process that holds the lock removes it: one refused as a second serve must not free it. */
23
23
  export declare const releaseLock: (path: string, pid?: number) => void;
24
+ /**
25
+ * When serve last had the store current, beside the lock and kept after it stops: a messenger with no full sync (wa)
26
+ * has no other time to show. Written on connect and every minute after, so a serve that was killed still leaves one.
27
+ */
28
+ export declare const currentPath: (lock: string) => string;
29
+ export declare const markCurrent: (lock: string, at?: Date) => void;
30
+ export declare const readCurrent: (lock: string) => string | undefined;
24
31
  /** The profiles a serve is running for now — what an update must restart for its new code to run. */
25
32
  export declare const servingProfiles: (app: AppIdentity, env: NodeJS.ProcessEnv) => string[];
@@ -48,6 +48,21 @@ export const releaseLock = (path, pid = process.pid) => {
48
48
  if (readLock(path)?.pid === pid)
49
49
  rmSync(path, { force: true });
50
50
  };
51
+ /**
52
+ * When serve last had the store current, beside the lock and kept after it stops: a messenger with no full sync (wa)
53
+ * has no other time to show. Written on connect and every minute after, so a serve that was killed still leaves one.
54
+ */
55
+ export const currentPath = (lock) => lock.replace(/\.lock$/, ".current");
56
+ export const markCurrent = (lock, at = new Date()) => writeSecurely(currentPath(lock), `${JSON.stringify({ at: at.toISOString() })}\n`, 0o600);
57
+ export const readCurrent = (lock) => {
58
+ try {
59
+ const { at } = JSON.parse(readFileSync(currentPath(lock), "utf8"));
60
+ return typeof at === "string" ? at : undefined;
61
+ }
62
+ catch {
63
+ return undefined;
64
+ }
65
+ };
51
66
  /** The profiles a serve is running for now — what an update must restart for its new code to run. */
52
67
  export const servingProfiles = (app, env) => {
53
68
  const dir = dirname(lockPath(app, "default", env));
@@ -1,5 +1,7 @@
1
1
  import { type CredentialsOptions, type KeyringStore } from "@wirecat/cli-base";
2
2
  import { Command } from "commander";
3
+ import { type ServerSystem } from "../background/system.js";
4
+ import { type Unit } from "../background/units.js";
3
5
  import type { Provider } from "../domain/models.js";
4
6
  import type { AppIdentity } from "../ports/app.js";
5
7
  import type { AccountKey } from "../store/types.js";
@@ -44,6 +46,14 @@ export interface AccountRemoval {
44
46
  account?(profile: string, context: AccountRemovalContext): AccountKey | undefined;
45
47
  /** Keyring entries of this profile the sign-out leaves: app keys, a bot token. Removing a missing one is fine. */
46
48
  secrets?(profile: string, context: AccountRemovalContext): AccountSecrets[];
49
+ /**
50
+ * Where the sign-in itself lives, for `account rename` to move it with the rest; `secrets` and the file hooks name
51
+ * everything else. A tool without it has no `account rename`: its sign-in would stay under the old name.
52
+ */
53
+ signIn?(profile: string, context: AccountRemovalContext): {
54
+ secrets?: AccountSecrets[];
55
+ files?: string[];
56
+ };
47
57
  /** The tool's own files and folders for this profile that hold no messages: cursors, a device id. Always removed. */
48
58
  stateFiles?(profile: string, context: AccountRemovalContext): string[];
49
59
  /** Files and folders holding this account's data outside the store: removed only with `--delete-data`. */
@@ -66,6 +76,10 @@ export interface AccountRemoveOptions {
66
76
  /** The owner's own home; unset, the account's from the user database. A test names its sandbox. */
67
77
  ownerHome?: string;
68
78
  }
79
+ /** Inside the tool's own folders and not one of them: a hook's mistake must not reach the home folder. */
80
+ export declare const insideOwnFolders: (app: AppIdentity, env: NodeJS.ProcessEnv, extra: readonly string[]) => (path: string) => string;
81
+ /** The profile's own serve unit, by its exact name, when one is installed; never a pattern over the unit folder. */
82
+ export declare const serveUnit: (app: AppIdentity, system: ServerSystem, profile: string, env: NodeJS.ProcessEnv) => Unit | undefined;
69
83
  /**
70
84
  * `<tool> <profile> account remove --keep-data|--delete-data`: signs the profile out the tool's way, forgets it on
71
85
  * this computer, and keeps or deletes what the store holds of its account. Asks first, or `--yes`; `--dry-run` lists
@@ -33,7 +33,7 @@ const choiceOf = ({ keepData, deleteData }) => {
33
33
  return keepData ? "kept" : "deleted";
34
34
  };
35
35
  /** Inside the tool's own folders and not one of them: a hook's mistake must not reach the home folder. */
36
- const insideOwnFolders = (app, env, extra) => {
36
+ export const insideOwnFolders = (app, env, extra) => {
37
37
  const home = absolute(env.HOME ?? env.USERPROFILE ?? homedir());
38
38
  for (const root of extra)
39
39
  if (!isAbsolute(root) || !absolute(root).startsWith(`${home}${sep}`))
@@ -62,7 +62,7 @@ const ownerFolders = (app, removal, hooks, home) => {
62
62
  ].map((root) => absolute(root));
63
63
  };
64
64
  /** The profile's own serve unit, by its exact name, when one is installed; never a pattern over the unit folder. */
65
- const serveUnit = (app, system, profile, env) => {
65
+ export const serveUnit = (app, system, profile, env) => {
66
66
  if (!env.HOME)
67
67
  return undefined;
68
68
  const unit = platformFor(app, system, env).unit({
@@ -0,0 +1,15 @@
1
+ import { Command } from "commander";
2
+ import type { AppIdentity } from "../ports/app.js";
3
+ import { type AccountRemoval } from "./account-remove.js";
4
+ import type { GlobalFlags, ResolveOptions, Settings } from "./settings.js";
5
+ export type AccountRenaming = AccountRemoval & Required<Pick<AccountRemoval, "signIn">>;
6
+ export interface AccountRenameOptions {
7
+ /** Unset: the one `run()` set. */
8
+ resolveSettings?: (flags: GlobalFlags, options?: ResolveOptions) => Settings;
9
+ }
10
+ /**
11
+ * `<tool> <profile> account rename <new>`: gives the profile another name and moves everything it owns on this
12
+ * computer — the sign-in, its other keyring entries, its settings, its files and what the store records of it. The
13
+ * account's data in the store is keyed by the account, not the name, and stays where it is. Asks first, or `--yes`.
14
+ */
15
+ export declare const accountRenameCommand: (app: AppIdentity, renaming: AccountRenaming, options?: AccountRenameOptions) => Command;
@@ -0,0 +1,240 @@
1
+ import { existsSync, mkdirSync, renameSync } from "node:fs";
2
+ import { dirname, join, sep } from "node:path";
3
+ import { CliError, Credentials, resolvePaths, saveConfigFile } from "@wirecat/cli-base";
4
+ import { annotate } from "@wirecat/cli-base/commands";
5
+ import { Command } from "commander";
6
+ import { lockPath, readLock, servingProfiles } from "../background/lock.js";
7
+ import { alive } from "../background/processes.js";
8
+ import { listSchedules } from "../background/schedules.js";
9
+ import { thisMachine } from "../background/system.js";
10
+ import { httpLockFile } from "../mcp/http/state.js";
11
+ import { sendsPathFor } from "../sends/journal.js";
12
+ import { storePath } from "../store/path.js";
13
+ import { openStore } from "../store/store.js";
14
+ import { insideOwnFolders, mayRevoke, serveUnit, } from "./account-remove.js";
15
+ import { readConfigFile, withoutPath } from "./config-issues.js";
16
+ import { baseContext, environmentOf } from "./context.js";
17
+ import { LOCAL_WRITE } from "./effects.js";
18
+ import { itemOf, renderAnswer } from "./envelope.js";
19
+ import { accountFileFor } from "./messenger/accounts.js";
20
+ import { answerOf } from "./messenger/ask.js";
21
+ import { usableProfileName } from "./profile.js";
22
+ import { profileFiles } from "./profile-files.js";
23
+ const refuse = (reason, message, details = {}) => new CliError("conflict", message, { reason: `account-rename.${reason}`, ...details });
24
+ /** Every hook is a function of the profile name, so the same hook asked for both names pairs old with new. */
25
+ const paired = (app, from, to) => {
26
+ if (from.length !== to.length)
27
+ throw new CliError("configuration_error", `${app.command} names a different number of paths or entries for the new name — nothing was renamed; report this as a bug`, { reason: "account-rename.unpaired" });
28
+ return from.map((one, at) => [one, to[at]]);
29
+ };
30
+ const at = (raw, path) => path.reduce((node, key) => node?.[key], raw);
31
+ const withValue = (raw, path, value) => {
32
+ const [key, ...rest] = path;
33
+ if (key === undefined)
34
+ return value;
35
+ const node = typeof raw === "object" && raw !== null ? raw : {};
36
+ return { ...node, [key]: withValue(node[key], rest, value) };
37
+ };
38
+ /**
39
+ * `<tool> <profile> account rename <new>`: gives the profile another name and moves everything it owns on this
40
+ * computer — the sign-in, its other keyring entries, its settings, its files and what the store records of it. The
41
+ * account's data in the store is keyed by the account, not the name, and stays where it is. Asks first, or `--yes`.
42
+ */
43
+ export const accountRenameCommand = (app, renaming, options = {}) => annotate(new Command("rename"), {
44
+ effects: LOCAL_WRITE,
45
+ mcp: false,
46
+ output: { entity: "account_rename" },
47
+ examples: [
48
+ `${app.command} personal account rename home --dry-run`,
49
+ `${app.command} personal account rename home --yes`,
50
+ ],
51
+ })
52
+ .summary("give this profile another name, keeping its sign-in, settings and data")
53
+ .description("give the profile another name: its sign-in, settings, files and what the store records of it move to the new " +
54
+ "name, and nothing is signed out; asks first, or --yes")
55
+ .argument("<new>", "the profile's new name")
56
+ .option("--dry-run", "list what it would move, and change nothing")
57
+ .action(async function (wanted) {
58
+ const given = this.opts();
59
+ const resolveSettings = options.resolveSettings ?? environmentOf(this).resolveSettings;
60
+ if (!resolveSettings)
61
+ throw new Error("account rename runs inside run(), or is given resolveSettings");
62
+ const context = baseContext(this, resolveSettings);
63
+ const { env, settings } = context;
64
+ const profile = settings.profile;
65
+ const next = usableProfileName(wanted);
66
+ const known = (name) => settings.profilesHere.includes(name) || existsSync(accountFileFor(app, name, env));
67
+ if (!known(profile))
68
+ throw new CliError("not_found", `no profile ${profile} on this computer — ${settings.profilesHere.join(", ") || "there is none"}`, { reason: "account-rename.unknown-profile", profiles: settings.profilesHere });
69
+ if (next === profile)
70
+ throw new CliError("validation_error", `${profile} already has that name`);
71
+ if (known(next) || (settings.botProfiles ?? []).includes(next))
72
+ throw refuse("taken", `a profile called ${next} already exists — pick another name`);
73
+ if (!mayRevoke(app, env, context.keyring))
74
+ throw new CliError("permission_error", "this run's folders are moved, and a profile is renamed only from a run with the owner's own folders", { reason: "account-rename.moved-run" });
75
+ if ((settings.botProfiles ?? []).includes(profile))
76
+ throw refuse("bot", `${profile} is also a bot profile, and a bot keeps its name — nothing was renamed`);
77
+ const hooks = {
78
+ env,
79
+ ...(context.keyring ? { keyring: context.keyring } : {}),
80
+ mayRevoke: true,
81
+ };
82
+ const state = resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state;
83
+ const httpLock = readLock(httpLockFile(join(state, "mcp-http", `${profile}.json`)));
84
+ const system = environmentOf(this).system ?? thisMachine();
85
+ const unit = serveUnit(app, system, profile, env);
86
+ const schedules = listSchedules(state).filter((schedule) => schedule.environment[`${app.envPrefix}_PROFILE`] === profile);
87
+ const holder = servingProfiles(app, env).includes(profile)
88
+ ? `\`${app.command} serve\` is running for ${profile} — stop it first (\`${app.command} ${profile} server stop\`)`
89
+ : httpLock && alive(httpLock.pid)
90
+ ? `\`${app.command} mcp serve --http\` is running for ${profile} — stop it first`
91
+ : unit
92
+ ? `${profile} has a background service — remove it first (\`${app.command} ${profile} server uninstall\`)`
93
+ : schedules.length > 0
94
+ ? `schedules run as ${profile}: ${schedules.map(({ name }) => name).join(", ")} — remove them first ` +
95
+ `(\`${app.command} schedule remove <name>\`)`
96
+ : renaming.busy?.(profile, hooks);
97
+ if (holder)
98
+ throw refuse("busy", `${holder}, then rename the profile`);
99
+ const own = insideOwnFolders(app, env, renaming.ownFolders?.(hooks) ?? []);
100
+ const filesOf = (name) => {
101
+ const serve = lockPath(app, name, env);
102
+ return [
103
+ accountFileFor(app, name, env),
104
+ sendsPathFor(app, name, env),
105
+ serve,
106
+ ...profileFiles(app, name, env, []),
107
+ ...(renaming.signIn(name, hooks).files ?? []),
108
+ ...(renaming.stateFiles?.(name, hooks) ?? []),
109
+ ...(renaming.dataFiles?.(name, hooks) ?? []),
110
+ ].map(own);
111
+ };
112
+ // A hook may repeat a path cli-core keeps, or name a folder holding another entry: that one moves with it.
113
+ const files = [
114
+ ...new Map(paired(app, filesOf(profile), filesOf(next))
115
+ .filter(([from]) => existsSync(from))
116
+ .map(([from, to]) => [from, to])),
117
+ ].filter(([from], _, all) => !all.some(([outer]) => outer !== from && from.startsWith(`${outer}${sep}`)));
118
+ const clash = files.find(([, to]) => existsSync(to));
119
+ if (clash)
120
+ throw refuse("taken", `${clash[1]} already exists — nothing was renamed`);
121
+ const config = resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config;
122
+ const secretsOf = (name) => [
123
+ { credentials: { configDir: config, service: app.appName, env }, accounts: [`token:${name}`] },
124
+ ...(renaming.signIn(name, hooks).secrets ?? []),
125
+ ...(renaming.secrets?.(name, hooks) ?? []),
126
+ ];
127
+ const seen = new Set();
128
+ const entries = paired(app, secretsOf(profile), secretsOf(next)).flatMap(([from, to]) => {
129
+ const store = new Credentials({
130
+ ...from.credentials,
131
+ ...(context.keyring && !from.credentials.keyring ? { keyring: context.keyring } : {}),
132
+ warn: (line) => context.renderer.warn(line),
133
+ });
134
+ return paired(app, from.accounts, to.accounts).flatMap(([old, now]) => {
135
+ const id = `${from.credentials.service}\0${from.credentials.configDir}\0${old}`;
136
+ if (seen.has(id))
137
+ return [];
138
+ seen.add(id);
139
+ const found = store.read(old);
140
+ return found && found.source !== "environment" ? [{ store, from: old, to: now }] : [];
141
+ });
142
+ });
143
+ const taken = entries.find(({ store, to }) => (store.read(to)?.source ?? "environment") !== "environment");
144
+ if (taken)
145
+ throw refuse("taken", `the keyring already holds ${taken.to} — nothing was renamed`);
146
+ const read = readConfigFile(settings.configPath);
147
+ if ("issue" in read)
148
+ throw new CliError("configuration_error", `${settings.configPath} cannot be read — fix it first`, {
149
+ reason: "account-rename.config",
150
+ });
151
+ const sections = [["profiles"], ["personal", "profiles"]].filter((path) => at(read.raw, [...path, profile]) !== undefined);
152
+ const storeHere = existsSync(storePath(env));
153
+ const recorded = storeHere ? await recordedOf(app, env, profile) : { key: undefined, groups: [] };
154
+ const moved = [
155
+ ...entries.map(({ from, to }) => ({ kind: "keyring", from, to })),
156
+ ...sections.map((path) => ({
157
+ kind: "config",
158
+ from: [...path, profile].join("."),
159
+ to: [...path, next].join("."),
160
+ })),
161
+ ...files.map(([from, to]) => ({ kind: "file", from, to })),
162
+ ...(recorded.key
163
+ ? [{ kind: "store", from: `${app.command}:${profile}`, to: `${app.command}:${next}` }]
164
+ : []),
165
+ ...recorded.groups.map((group) => ({
166
+ kind: "store",
167
+ from: `group ${group}: ${app.command}:${profile}`,
168
+ to: `group ${group}: ${app.command}:${next}`,
169
+ })),
170
+ ];
171
+ const answer = (dryRun) => renderAnswer(this, context, itemOf({ profile, renamed_to: next, dry_run: dryRun, config_file: settings.configPath, moved }));
172
+ if (given.dryRun) {
173
+ answer(true);
174
+ return;
175
+ }
176
+ if (this.optsWithGlobals().yes !== true) {
177
+ const what = `this renames ${profile} to ${next}`;
178
+ const lines = moved.map((one) => ` ${one.kind}: ${one.from} → ${one.to}`).join("\n");
179
+ const reply = await answerOf(this, `${what}:\n${lines}\nGo ahead? [y/N] `);
180
+ if (reply === null)
181
+ throw new CliError("confirmation_required", `${what} — add --yes to go ahead, or --dry-run to see the list`, {
182
+ reason: "account-rename.unconfirmed",
183
+ });
184
+ if (!/^\s*y(es)?\s*$/i.test(reply))
185
+ throw new CliError("cancelled", `cancelled — ${profile} is unchanged`);
186
+ }
187
+ await context.run(async () => {
188
+ // Every new entry is written before an old one goes, so a failure leaves the old name signed in.
189
+ for (const { store, from, to } of entries) {
190
+ const found = store.read(from);
191
+ if (found)
192
+ store.write(to, found.secret);
193
+ }
194
+ if (sections.length > 0)
195
+ saveConfigFile(settings.configPath, sections.reduce((raw, path) => withoutPath(withValue(raw, [...path, next], at(raw, [...path, profile])), [...path, profile]).config, read.raw));
196
+ for (const [from, to] of files) {
197
+ mkdirSync(dirname(to), { recursive: true });
198
+ renameSync(from, to);
199
+ }
200
+ if (recorded.key || recorded.groups.length > 0)
201
+ await moveRecords(app, env, profile, next);
202
+ for (const { store, from } of entries)
203
+ store.remove(from);
204
+ answer(false);
205
+ if (context.format === "pretty")
206
+ context.renderer.success(`renamed ${profile} to ${next}`);
207
+ });
208
+ });
209
+ const recordedOf = async (app, env, profile) => {
210
+ const store = await openStore({ env, command: app.command });
211
+ try {
212
+ const member = `${app.command}:${profile}`;
213
+ return {
214
+ key: (await store.accounts.profiles())[app.command]?.[profile],
215
+ groups: Object.entries(await store.accounts.accountGroups())
216
+ .filter(([, members]) => members.includes(member))
217
+ .map(([group]) => group),
218
+ };
219
+ }
220
+ finally {
221
+ await store.close();
222
+ }
223
+ };
224
+ const moveRecords = async (app, env, profile, next) => {
225
+ const store = await openStore({ env, command: app.command });
226
+ try {
227
+ const key = (await store.accounts.profiles())[app.command]?.[profile];
228
+ if (key) {
229
+ await store.accounts.saveProfile(app.command, next, key);
230
+ await store.accounts.forgetProfile(app.command, profile);
231
+ }
232
+ const member = `${app.command}:${profile}`;
233
+ for (const [group, members] of Object.entries(await store.accounts.accountGroups()))
234
+ if (members.includes(member))
235
+ await store.accounts.saveAccountGroup(group, members.map((one) => (one === member ? `${app.command}:${next}` : one)));
236
+ }
237
+ finally {
238
+ await store.close();
239
+ }
240
+ };
@@ -61,6 +61,8 @@ export const generatedApiCommand = (api) => {
61
61
  effects: { remote: operation.effect === "read" ? "read" : "write", local: "none" },
62
62
  });
63
63
  command.action(async function () {
64
+ // First: a refusal by the profile holds whatever the flags and the body say.
65
+ await api.before?.(this, operation);
64
66
  const options = this.opts();
65
67
  const input = { path: {}, query: {}, headers: {}, fields: {} };
66
68
  const tokenProfile = group.opts().storeToken;
@@ -86,7 +88,6 @@ export const generatedApiCommand = (api) => {
86
88
  const target = parameter.in === "body" ? input.fields : parameter.in === "header" ? input.headers : input[parameter.in];
87
89
  target[parameter.name] = raw;
88
90
  }
89
- await api.before?.(this, operation);
90
91
  if (sendsBytes(operation)) {
91
92
  const path = options.bodyFile;
92
93
  if (path === undefined && operation.request?.required)
@@ -58,8 +58,8 @@ export interface CopyAge {
58
58
  }
59
59
  export declare const ageOf: (lastSync: string | undefined, now?: number) => CopyAge;
60
60
  export declare const staleCopy: (provider: string, lastSync: string | undefined, now?: number) => {
61
- next?: undefined;
62
61
  missing?: undefined;
62
+ next?: undefined;
63
63
  meta?: undefined;
64
64
  } | {
65
65
  missing: {
@@ -50,6 +50,7 @@ export { defineSetup, type Setup, type SetupCheck, type SetupCheckInput, type Se
50
50
  export { type Asset as SetupAsset, BLOCK_ROLES, BLOCK_TYPES, type Block as SetupBlock, BUILT_IN_ACTIONS, type Condition as SetupCondition, DISPLAY_CLASSES, INPUT_KINDS, SETUP_FORMAT, SETUP_LIMITS, SETUP_PATTERNS, SETUP_VERSION, type SetupDocument, type Step as SetupStep, setupDocumentSchema, setupJsonSchema, } from "../setup/document.js";
51
51
  export { answerStdinOption, type Need, type SignInSteps, type SignInStepsOptions, signInSteps, } from "../terminal/sign-in-steps.js";
52
52
  export { type AccountRemoval, type AccountRemovalContext, type AccountRemoveOptions, type AccountSecrets, accountRemoveCommand, mayRevoke, type SignedOut, } from "./account-remove.js";
53
+ export { type AccountRenameOptions, type AccountRenaming, accountRenameCommand } from "./account-rename.js";
53
54
  export { liftOptionsAfterDashes } from "./after-dashes.js";
54
55
  export { type AgentPolicy, type AgentTask, type EvaluationResult, evaluateAgent, type Observation, } from "./agent-evaluation.js";
55
56
  export { answerEntity } from "./answer-entity.js";
package/dist/cli/index.js CHANGED
@@ -45,6 +45,7 @@ export { defineSetup, setupProblems, } from "../setup/define.js";
45
45
  export { BLOCK_ROLES, BLOCK_TYPES, BUILT_IN_ACTIONS, DISPLAY_CLASSES, INPUT_KINDS, SETUP_FORMAT, SETUP_LIMITS, SETUP_PATTERNS, SETUP_VERSION, setupDocumentSchema, setupJsonSchema, } from "../setup/document.js";
46
46
  export { answerStdinOption, signInSteps, } from "../terminal/sign-in-steps.js";
47
47
  export { accountRemoveCommand, mayRevoke, } from "./account-remove.js";
48
+ export { accountRenameCommand } from "./account-rename.js";
48
49
  export { liftOptionsAfterDashes } from "./after-dashes.js";
49
50
  export { evaluateAgent, } from "./agent-evaluation.js";
50
51
  export { answerEntity } from "./answer-entity.js";
@@ -5,6 +5,7 @@ import { withoutPhone } from "../../services/people.js";
5
5
  import { storePath } from "../../store/path.js";
6
6
  import { openStore } from "../../store/store.js";
7
7
  import { accountRemoveCommand } from "../account-remove.js";
8
+ import { accountRenameCommand } from "../account-rename.js";
8
9
  import { REMOTE_READ, REMOTE_WRITE } from "../effects.js";
9
10
  import { itemOf, renderAnswer } from "../envelope.js";
10
11
  import { queryTerms, withQuery } from "../list-query.js";
@@ -105,6 +106,11 @@ export const accountCommand = (messenger) => {
105
106
  provider: messenger.provider,
106
107
  resolveSettings: messenger.resolveSettings,
107
108
  }));
109
+ const renaming = messenger.accountRemoval;
110
+ if (renaming?.signIn)
111
+ account.addCommand(accountRenameCommand(messenger.app, { ...renaming, signIn: renaming.signIn }, {
112
+ resolveSettings: messenger.resolveSettings,
113
+ }));
108
114
  if (messenger.privacy === true)
109
115
  account.addCommand(privacyCommand(messenger));
110
116
  return hideNever(messenger, account);
@@ -1,7 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { annotate } from "@wirecat/cli-base/commands";
3
3
  import { Command } from "commander";
4
- import { holdLock, lockPath, releaseLock, takeLock } from "../../background/lock.js";
4
+ import { holdLock, lockPath, markCurrent, releaseLock, takeLock } from "../../background/lock.js";
5
5
  import { parseDuration } from "../../domain/duration.js";
6
6
  import { failureKey } from "../../errors/failures.js";
7
7
  import { capability } from "../../ports/messenger.js";
@@ -31,6 +31,7 @@ import { serveRelay } from "./serve-relay.js";
31
31
  import { stemFills } from "./serve-stems.js";
32
32
  import { listenUntilStopped } from "./watch-command.js";
33
33
  export { lockPath, readLock, servingProfiles } from "../../background/lock.js";
34
+ const CURRENT_EVERY_MS = 60_000;
34
35
  /**
35
36
  * Keeps the store current: every new message, edit, deletion and reaction, and on start what arrived
36
37
  * while nothing listened. **One per profile**, held by a lock file; a lock whose process is gone is
@@ -58,10 +59,20 @@ export const serveCommand = (messenger) => {
58
59
  throw new CliError("validation_error", `${messenger.app.command} serve is already running for profile ${context.profile} (PID ${held.pid}, since ${held.startedAt})`);
59
60
  }
60
61
  let relaying;
62
+ let current;
63
+ // A stamp that cannot be written must not end serve: the store is still kept.
64
+ const stamp = () => {
65
+ try {
66
+ markCurrent(path);
67
+ }
68
+ catch { }
69
+ };
61
70
  // `server start` answers on this, not on the lock alone: a lock is written before the connection opens.
62
71
  const onReady = () => {
63
72
  const listening = { pid: process.pid, startedAt, version, listeningAt: new Date().toISOString() };
64
73
  holdLock(path, listening);
74
+ stamp();
75
+ current ??= setInterval(stamp, CURRENT_EVERY_MS).unref();
65
76
  note({
66
77
  code: "listening",
67
78
  text: `listening for profile ${context.profile}, catching up on what arrived while it was down`,
@@ -186,6 +197,10 @@ export const serveCommand = (messenger) => {
186
197
  });
187
198
  }
188
199
  finally {
200
+ if (current) {
201
+ clearInterval(current);
202
+ stamp();
203
+ }
189
204
  watch.stop();
190
205
  await relaying;
191
206
  await relay?.close();
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { CliError, EXIT_CODES, exitCodeFor, resolvePaths, writeSecurely } from "@wirecat/cli-base";
4
4
  import { annotate } from "@wirecat/cli-base/commands";
5
5
  import { Command } from "commander";
6
- import { lockPath, readLock } from "../../background/lock.js";
6
+ import { lockPath, readCurrent, readLock } from "../../background/lock.js";
7
7
  import { alive, carries } from "../../background/processes.js";
8
8
  import { thisMachine } from "../../background/system.js";
9
9
  import { locationVariables, platformFor, readableLog, tail } from "../../background/units.js";
@@ -220,6 +220,7 @@ export const serverCommand = (messenger, options = {}) => {
220
220
  const held = await server.probe();
221
221
  const by = held ? await byOf(prepared, held) : null;
222
222
  const left = held ? undefined : readLock(lockPath(app, unit.profile, context.env));
223
+ const currentAt = readCurrent(lockPath(app, unit.profile, context.env));
223
224
  // An update leaves a running serve on the old code.
224
225
  const outdated = held?.version !== undefined && held.version !== app.version;
225
226
  const gaveUp = !held && !state.active && state.exitCode !== undefined && unit.noRestartOn?.includes(state.exitCode)
@@ -249,6 +250,7 @@ export const serverCommand = (messenger, options = {}) => {
249
250
  cliVersion: app.version,
250
251
  log: isInstalled && unit.path.endsWith(".service") ? `journalctl --user -u ${unit.name}` : unit.logPath,
251
252
  ...(left ? { stale: { pid: left.pid, startedAt: left.startedAt } } : {}),
253
+ ...(currentAt ? { currentAt } : {}),
252
254
  ...(gaveUp !== undefined
253
255
  ? { stopped: { exitCode: gaveUp, reason: gaveUpReason ?? null, restarts: false } }
254
256
  : {}),
@@ -260,7 +262,7 @@ export const serverCommand = (messenger, options = {}) => {
260
262
  ? held.connected
261
263
  ? `Serving profile ${unit.profile} since ${clock(held.startedAt)} (PID ${held.pid}), connected${held.connectedAt ? ` since ${clock(held.connectedAt)}` : ""}, ${how(by ?? "hand", unit)}.`
262
264
  : `Starting profile ${unit.profile} since ${clock(held.startedAt)} (PID ${held.pid}) — not connected yet, ${how(by ?? "hand", unit)}.`
263
- : `Not serving profile ${unit.profile}.${isInstalled && gaveUp === undefined && state.detail?.startsWith("failed") ? ` The unit failed — \`${app.command} ${unit.profile} server logs\`.` : ""}`,
265
+ : `Not serving profile ${unit.profile}.${currentAt ? ` The store was current at ${clock(currentAt)}.` : ""}${isInstalled && gaveUp === undefined && state.detail?.startsWith("failed") ? ` The unit failed — \`${app.command} ${unit.profile} server logs\`.` : ""}`,
264
266
  ...(gaveUp === exitCodeFor("authentication_error")
265
267
  ? [
266
268
  `It stopped because the login is no longer valid, and it will not restart by itself — \`${app.command} ${unit.profile} session start\`, then \`${app.command} ${unit.profile} server start\`.`,
@@ -37,6 +37,7 @@ export const profileFiles = (app, profile, env, schedules) => {
37
37
  replyConsentPathFor(app, profile, env),
38
38
  repliesStatePathFor(app, profile, env),
39
39
  join(state, "serve", `${profile}.log`),
40
+ join(state, "serve", `${profile}.current`),
40
41
  join(state, "checkpoints", profile),
41
42
  ...pointFolders(schedules).map((folder) => join(state, folder, `${profile}.json`)),
42
43
  ];
@@ -0,0 +1,31 @@
1
+ import { type AppIdentity } from "../ports/app.js";
2
+ import type { MessageStore } from "../store/store.js";
3
+ import type { AccountKey } from "../store/types.js";
4
+ export interface ProfileStoreOptions {
5
+ app: AppIdentity;
6
+ env: NodeJS.ProcessEnv;
7
+ profile: string;
8
+ /** The command only reads the store: the `readOnly` its category's `open` is given. */
9
+ readOnly: boolean;
10
+ /** The service's provider, as the store names it: the empty store's account under the read-only lock. */
11
+ provider: string;
12
+ /** Opens the shared store as the CLI does; a writable open also registers its provider. */
13
+ open: (env: NodeJS.ProcessEnv, options?: {
14
+ readOnly?: boolean;
15
+ }) => Promise<MessageStore>;
16
+ /** The profile's account from its sign-in; asked only when no earlier run saved it. */
17
+ account: () => AccountKey;
18
+ }
19
+ /**
20
+ * The store a command over one service account reads (a CRM's, a blog's), and the profile's account in it. A read takes
21
+ * the account an earlier run saved, so it never reads the sign-in; the first read of a profile, a store that is missing
22
+ * or needs a migration, and every sync and write open it for writing and save the account (scope work, which the owner
23
+ * may change) and the profile.
24
+ *
25
+ * Under `<PREFIX>_READ_ONLY` a read with no store or no saved profile reads an empty store in a temporary folder, so
26
+ * the lock creates no `wirecat.db`; the folder goes when the store closes. A sync still writes, as a fetch may.
27
+ */
28
+ export declare const openProfileStore: (options: ProfileStoreOptions) => Promise<{
29
+ store: MessageStore;
30
+ account: AccountKey;
31
+ }>;