@wirecat/wirecat 0.0.0-stage → 1.0.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 (230) hide show
  1. package/LICENSE +204 -0
  2. package/README.md +400 -2
  3. package/THIRD_PARTY_NOTICES +2 -0
  4. package/contracts/wirecat.json +4612 -0
  5. package/dist/actions/actions.js +269 -0
  6. package/dist/actions/command.js +102 -0
  7. package/dist/agents/command.js +17 -0
  8. package/dist/agents/log.js +23 -0
  9. package/dist/answer.js +100 -0
  10. package/dist/answers/command.js +128 -0
  11. package/dist/app.js +15 -0
  12. package/dist/author.js +109 -0
  13. package/dist/bin/wcat-wirecat.js +40 -0
  14. package/dist/bots/command.js +175 -0
  15. package/dist/bundle/auto-YETGUQ2J.js +43 -0
  16. package/dist/bundle/chunk-3ME37WWB.js +31 -0
  17. package/dist/bundle/chunk-4WI3FO7T.js +395 -0
  18. package/dist/bundle/chunk-7O7XM37N.js +2 -0
  19. package/dist/bundle/chunk-DWQQRBQV.js +51 -0
  20. package/dist/bundle/chunk-FOWR5KJS.js +72 -0
  21. package/dist/bundle/chunk-GGRL6DTE.js +120 -0
  22. package/dist/bundle/chunk-KNFSW562.js +312 -0
  23. package/dist/bundle/chunk-KPJVVFQF.js +416 -0
  24. package/dist/bundle/chunk-WMPDRWVF.js +222 -0
  25. package/dist/bundle/chunk-X5OK73GU.js +807 -0
  26. package/dist/bundle/chunk-ZC4PRE6C.js +38 -0
  27. package/dist/bundle/entry-S4DSYEAY.js +64 -0
  28. package/dist/bundle/failure-FALOD7QW.js +19 -0
  29. package/dist/bundle/from-memo-XVOLSUOM.js +314 -0
  30. package/dist/bundle/program-XSZSINBU.js +14994 -0
  31. package/dist/bundle/server-GQ4NZUDL.js +303 -0
  32. package/dist/bundle/update-2EH5KHTV.js +22 -0
  33. package/dist/bundle/wcat-wirecat.js +83 -0
  34. package/dist/config-command.js +39 -0
  35. package/dist/config-issues.js +15 -0
  36. package/dist/config.js +187 -0
  37. package/dist/context/command.js +162 -0
  38. package/dist/context/context.js +197 -0
  39. package/dist/contract-overrides/commands.js +81 -0
  40. package/dist/contract-overrides/mcp.js +241 -0
  41. package/dist/contract-overrides/meetings.js +344 -0
  42. package/dist/contract-overrides/search.js +508 -0
  43. package/dist/contract-overrides/skill.js +85 -0
  44. package/dist/contract-overrides.js +7 -0
  45. package/dist/digest/backfill.js +175 -0
  46. package/dist/digest/brief.js +189 -0
  47. package/dist/digest/catch-up-record.js +30 -0
  48. package/dist/digest/catch-up.js +86 -0
  49. package/dist/digest/command.js +110 -0
  50. package/dist/digest/digest-commands.js +327 -0
  51. package/dist/digest/digest.js +560 -0
  52. package/dist/digest/digests.js +213 -0
  53. package/dist/digest/history.js +202 -0
  54. package/dist/digest/input.js +30 -0
  55. package/dist/digest/known.js +28 -0
  56. package/dist/digest/sources.js +155 -0
  57. package/dist/digest/sync-health.js +158 -0
  58. package/dist/digest/task-proposals.js +67 -0
  59. package/dist/digest/tasks.js +145 -0
  60. package/dist/digest/text.js +49 -0
  61. package/dist/discovery/command.js +107 -0
  62. package/dist/doctor/command.js +167 -0
  63. package/dist/documents/command.js +107 -0
  64. package/dist/domain-lists/command.js +13 -0
  65. package/dist/events/command.js +35 -0
  66. package/dist/events/events.js +196 -0
  67. package/dist/examples.js +609 -0
  68. package/dist/facts/command.js +100 -0
  69. package/dist/facts/fact.js +54 -0
  70. package/dist/facts/facts.js +15 -0
  71. package/dist/failure.js +58 -0
  72. package/dist/finance/command.js +121 -0
  73. package/dist/finance/contracts-command.js +109 -0
  74. package/dist/finance/deal-text.js +34 -0
  75. package/dist/finance/deals-command.js +346 -0
  76. package/dist/finance/finance.js +129 -0
  77. package/dist/finance/lines-command.js +70 -0
  78. package/dist/finance/orders-command.js +94 -0
  79. package/dist/finance/products-command.js +98 -0
  80. package/dist/finance/subscriptions-command.js +152 -0
  81. package/dist/finance/transactions-command.js +136 -0
  82. package/dist/finance/wallets-command.js +105 -0
  83. package/dist/finance/written.js +36 -0
  84. package/dist/findings/command.js +102 -0
  85. package/dist/findings-input.js +23 -0
  86. package/dist/identity.js +20 -0
  87. package/dist/install/postinstall.js +47 -0
  88. package/dist/json-fields.js +48 -0
  89. package/dist/knowledge/business-text.js +19 -0
  90. package/dist/knowledge/command.js +435 -0
  91. package/dist/knowledge/document-context.js +33 -0
  92. package/dist/knowledge/key-documents.js +120 -0
  93. package/dist/knowledge/list-queries.js +20 -0
  94. package/dist/knowledge/meeting-projects-command.js +61 -0
  95. package/dist/knowledge/messenger-sync.js +253 -0
  96. package/dist/knowledge/money-text.js +16 -0
  97. package/dist/knowledge/notes-about.js +81 -0
  98. package/dist/knowledge/organization-delete-command.js +44 -0
  99. package/dist/knowledge/organization-text.js +27 -0
  100. package/dist/knowledge/project-actions-command.js +130 -0
  101. package/dist/knowledge/project-actions.js +104 -0
  102. package/dist/knowledge/project-activity-command.js +70 -0
  103. package/dist/knowledge/project-context.js +101 -0
  104. package/dist/knowledge/project-findings.js +41 -0
  105. package/dist/knowledge/project-gather-command.js +100 -0
  106. package/dist/knowledge/project-status-command.js +129 -0
  107. package/dist/knowledge/project-transfer-command.js +58 -0
  108. package/dist/knowledge/project-transfer.js +107 -0
  109. package/dist/knowledge/relationships-scan.js +116 -0
  110. package/dist/knowledge/relationships.js +115 -0
  111. package/dist/knowledge/roles-command.js +67 -0
  112. package/dist/mail/command.js +20 -0
  113. package/dist/mail/findings-command.js +143 -0
  114. package/dist/mail/findings-duplicates.js +159 -0
  115. package/dist/mail/messages-command.js +77 -0
  116. package/dist/mail/review-command.js +59 -0
  117. package/dist/mail/subscriptions-command.js +84 -0
  118. package/dist/mcp/catalogue.js +159 -0
  119. package/dist/mcp/command.js +125 -0
  120. package/dist/mcp/granted.js +18 -0
  121. package/dist/mcp/permissions.js +61 -0
  122. package/dist/mcp/server.js +128 -0
  123. package/dist/meetings/command.js +31 -0
  124. package/dist/meetings/list-command.js +59 -0
  125. package/dist/meetings/preparation-command.js +42 -0
  126. package/dist/meetings/preparation-text.js +44 -0
  127. package/dist/meetings/preparation.js +50 -0
  128. package/dist/meetings/read.js +32 -0
  129. package/dist/memories/command.js +105 -0
  130. package/dist/memories/memories.js +17 -0
  131. package/dist/memories/memory.js +89 -0
  132. package/dist/memories/sources.js +111 -0
  133. package/dist/mentions/command.js +91 -0
  134. package/dist/migrate/check.js +48 -0
  135. package/dist/migrate/from-memo.js +345 -0
  136. package/dist/migrate/skill.js +35 -0
  137. package/dist/models/command.js +19 -0
  138. package/dist/options.js +35 -0
  139. package/dist/output.js +17 -0
  140. package/dist/page.js +14 -0
  141. package/dist/people/command.js +144 -0
  142. package/dist/people/delete-command.js +53 -0
  143. package/dist/people/doubts-command.js +81 -0
  144. package/dist/people/identities-command.js +188 -0
  145. package/dist/people/identity.js +42 -0
  146. package/dist/people/owner.js +14 -0
  147. package/dist/people/proposal-rows.js +70 -0
  148. package/dist/people/proposals-command.js +248 -0
  149. package/dist/people/review-context.js +108 -0
  150. package/dist/people/subject.js +19 -0
  151. package/dist/program.js +875 -0
  152. package/dist/read-only.js +51 -0
  153. package/dist/reasons.js +368 -0
  154. package/dist/records/import.js +135 -0
  155. package/dist/records/input.js +210 -0
  156. package/dist/records/mapping.js +80 -0
  157. package/dist/records/record-commands.js +125 -0
  158. package/dist/records/sources.js +73 -0
  159. package/dist/refs.js +28 -0
  160. package/dist/review/command.js +171 -0
  161. package/dist/review/kinds.js +44 -0
  162. package/dist/review/review.js +299 -0
  163. package/dist/review/status.js +93 -0
  164. package/dist/rows.js +219 -0
  165. package/dist/run/auto.js +237 -0
  166. package/dist/run/entry.js +62 -0
  167. package/dist/run/files.js +51 -0
  168. package/dist/run/import.js +253 -0
  169. package/dist/run/lock.js +20 -0
  170. package/dist/save-help.js +3 -0
  171. package/dist/schedule/command.js +58 -0
  172. package/dist/schedule/mail-triage-input.js +152 -0
  173. package/dist/schedule/task-triage-input.js +152 -0
  174. package/dist/search/answers.js +176 -0
  175. package/dist/search/command.js +257 -0
  176. package/dist/search/denied.js +9 -0
  177. package/dist/search/embed.js +126 -0
  178. package/dist/search/hits.js +4 -0
  179. package/dist/search/lane-gates.js +76 -0
  180. package/dist/search/notes-text.js +18 -0
  181. package/dist/search/people.js +88 -0
  182. package/dist/search/search.js +306 -0
  183. package/dist/show/command.js +179 -0
  184. package/dist/store/crm-viewer.js +102 -0
  185. package/dist/store/group.js +112 -0
  186. package/dist/store/groups-command.js +136 -0
  187. package/dist/store/guard.js +94 -0
  188. package/dist/store/held.js +21 -0
  189. package/dist/store/info-command.js +37 -0
  190. package/dist/store/scope.js +53 -0
  191. package/dist/store/source-list.js +222 -0
  192. package/dist/store/source-target.js +28 -0
  193. package/dist/tags/command.js +176 -0
  194. package/dist/tasks/command.js +174 -0
  195. package/dist/tasks/context.js +74 -0
  196. package/dist/tasks/list.js +199 -0
  197. package/dist/tasks/proposal-duplicates.js +70 -0
  198. package/dist/tasks/relations-command.js +28 -0
  199. package/dist/tasks/shared.js +105 -0
  200. package/dist/tasks/tasks.js +197 -0
  201. package/dist/templates/command.js +18 -0
  202. package/dist/terminal.js +23 -0
  203. package/dist/update.js +35 -0
  204. package/dist/version.js +2 -0
  205. package/dist/vocabulary/command.js +103 -0
  206. package/dist/vocabulary/inspect.js +23 -0
  207. package/dist/vocabulary/inspection.js +18 -0
  208. package/dist/vocabulary/list.js +18 -0
  209. package/dist/vocabulary/project.js +19 -0
  210. package/dist/wcat.js +3 -0
  211. package/install/postinstall.mjs +9 -0
  212. package/package.json +89 -4
  213. package/scenarios/decision-trail.md +21 -0
  214. package/scenarios/person-brief.md +35 -0
  215. package/scenarios/prepare-meeting.md +17 -0
  216. package/scenarios/project-state.md +26 -0
  217. package/scenarios/set-up.md +18 -0
  218. package/scenarios/start-the-day.md +19 -0
  219. package/skills/mail-triage/SKILL.md +208 -0
  220. package/skills/morning-digest/SKILL.md +147 -0
  221. package/skills/task-triage/SKILL.md +79 -0
  222. package/skills/wcat/SKILL.md +65 -0
  223. package/skills/wcat/topics/mail.md +32 -0
  224. package/skills/wcat/topics/mcp.md +22 -0
  225. package/skills/wcat/topics/meetings.md +37 -0
  226. package/skills/wcat/topics/money.md +52 -0
  227. package/skills/wcat/topics/projects.md +54 -0
  228. package/skills/wcat/topics/proposals.md +113 -0
  229. package/skills/wcat/topics/search.md +85 -0
  230. package/skills/wcat/topics/vocabulary.md +8 -0
@@ -0,0 +1,23 @@
1
+ import { createReadStream, statSync } from "node:fs";
2
+ import { CliError, readBatchInput } from "@wirecat/cli-base";
3
+ export const FINDINGS_INPUT_HELP = "the findings JSON itself (starts with {), a JSON file, or - for stdin; at most 65536 UTF-8 bytes";
4
+ /**
5
+ * A scheduled agent under Claude Code's dontAsk mode is refused a heredoc or a pipe it builds around real mail
6
+ * text, and must never write mail to a file, so the JSON may come as the argument itself (BUG-534).
7
+ */
8
+ export const readFindingsInput = (input, stdin) => {
9
+ if (input.trimStart().startsWith("{"))
10
+ return Promise.resolve(input);
11
+ if (input === "-")
12
+ return readBatchInput(stdin);
13
+ const file = statSync(input, { throwIfNoEntry: false });
14
+ if (!file)
15
+ throw new CliError("not_found", `no findings file ${input}: give the JSON itself, a file that exists, or -`, {
16
+ reason: "findings.file-missing",
17
+ path: input,
18
+ });
19
+ if (!file.isFile())
20
+ throw new CliError("validation_error", `${input} is not a file`, { path: input });
21
+ return readBatchInput(createReadStream(input));
22
+ };
23
+ //# sourceMappingURL=findings-input.js.map
@@ -0,0 +1,20 @@
1
+ import { APP } from "./app.js";
2
+ // The bin hands this to wcatStart before the program loads, so it must not import the command tree; src/wcat.ts adds
3
+ // the permission keys for the manifest.
4
+ // The name in `wcat <name>` is `wirecat`: the launcher and the manifest both look for the program wcat-<name>, and
5
+ // this package ships wcat-wirecat, while help, hints and MCP tool names use the command people type, `wcat`.
6
+ export const DESKTOP = {
7
+ command: "wirecat",
8
+ version: APP.version,
9
+ description: APP.description,
10
+ appName: APP.appName,
11
+ envPrefix: APP.envPrefix,
12
+ docs: "https://wirecat.dev/en/docs/wcat",
13
+ tagline: "People, memories and context in one place for agents",
14
+ syncs: "mail and people",
15
+ mcpPort: 8767,
16
+ // The default endpoints of the AI models; the owner may point one at another address.
17
+ hosts: ["api.openai.com", "api.anthropic.com", "localhost", "127.0.0.1"],
18
+ userHosts: "the address you set for an AI model",
19
+ };
20
+ //# sourceMappingURL=identity.js.map
@@ -0,0 +1,47 @@
1
+ import { dirname, join, resolve } from "node:path";
2
+ import { fileURLToPath, pathToFileURL } from "node:url";
3
+ import { installSkill } from "@wirecat/cli-base/skill";
4
+ import { binFolder, ensureLauncher } from "@wirecat/cli-base/wcat";
5
+ import { APP } from "../app.js";
6
+ import { DESKTOP } from "../identity.js";
7
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
8
+ const TARGETS = {
9
+ all: ["claude", "agents"],
10
+ claude: ["claude"],
11
+ codex: ["agents"],
12
+ cursor: ["agents"],
13
+ gemini: ["agents"],
14
+ };
15
+ /**
16
+ * The package cannot declare a `wcat` bin: npm refuses one over the launcher another WireCat tool wrote. So the
17
+ * install writes the launcher, as every start of wcat-wirecat does again.
18
+ */
19
+ export const writeLauncher = ({ env = process.env, packageRoot = root, platform = process.platform, } = {}) => {
20
+ const folder = binFolder({
21
+ name: DESKTOP.command,
22
+ script: join(packageRoot, "dist", "bin", "wcat-wirecat.js"),
23
+ env,
24
+ platform,
25
+ });
26
+ return folder ? ensureLauncher({ ...folder, platform }) : undefined;
27
+ };
28
+ /**
29
+ * A global npm install puts the skill where agents look only when WCAT_INSTALL_AGENT names one: npm hides a
30
+ * lifecycle script's output, so writing into the owner's agent folders must be asked for.
31
+ */
32
+ export const completeGlobalInstall = ({ env = process.env, packageRoot = root, note = (message) => process.stderr.write(`${message}\n`), } = {}) => {
33
+ if (env.npm_config_global !== "true")
34
+ return;
35
+ writeLauncher({ env, packageRoot });
36
+ const agent = env.WCAT_INSTALL_AGENT;
37
+ if (agent === undefined || agent === "none") {
38
+ note("wcat: agent skill not installed; run wcat skill install --for all.");
39
+ return;
40
+ }
41
+ const targets = TARGETS[agent];
42
+ if (targets === undefined)
43
+ throw new Error("WCAT_INSTALL_AGENT must be all, codex, cursor, claude, gemini or none");
44
+ installSkill({ command: APP.command, appName: APP.appName, version: APP.version }, pathToFileURL(join(packageRoot, "skills/wcat/SKILL.md")), { env, targets });
45
+ note("wcat: agent skill installed. Agent: read wcat skill show before using wcat.");
46
+ };
47
+ //# sourceMappingURL=postinstall.js.map
@@ -0,0 +1,48 @@
1
+ import { fieldsOf, projectFields } from "@wirecat/cli-base";
2
+ import { checkJson, liftJson } from "@wirecat/cli-core";
3
+ const commandIn = (root, words) => {
4
+ let at = root;
5
+ for (const word of words) {
6
+ if (word.startsWith("-"))
7
+ continue;
8
+ const child = at.commands.find((command) => command.name() === word || command.aliases().includes(word));
9
+ if (child)
10
+ at = child;
11
+ }
12
+ return at === root ? undefined : at;
13
+ };
14
+ const keep = (text, paths) => {
15
+ let value;
16
+ try {
17
+ value = JSON.parse(text);
18
+ }
19
+ catch {
20
+ return text;
21
+ }
22
+ if (!value || typeof value !== "object")
23
+ return text;
24
+ return JSON.stringify(projectFields(value, paths));
25
+ };
26
+ /**
27
+ * `--json=a,b` keeps those fields of an answer's item or items, read the way tg and max read it. wcat's commands
28
+ * print through many renderers, so the fields are applied where every answer passes: the data stream.
29
+ */
30
+ export const jsonFields = (streams, resolve) => {
31
+ let fields;
32
+ return {
33
+ streams: { ...streams, data: (text) => streams.data(fields ? keep(text, fieldsOf(fields)) : text) },
34
+ install(program, terminal = process.stdout.isTTY === true) {
35
+ const parse = program.parseAsync.bind(program);
36
+ program.parseAsync = async (argv = process.argv, settings) => {
37
+ const user = settings?.from === "user";
38
+ const requested = liftJson(user ? argv : argv.slice(2), (words) => commandIn(program, words), resolve);
39
+ fields = requested.fields;
40
+ return parse(user ? requested.argv : [...argv.slice(0, 2), ...requested.argv], settings);
41
+ };
42
+ program.hook("preAction", (_root, action) => {
43
+ checkJson(action, { json: action.opts().json === true, ...(fields ? { fields } : {}) }, terminal, resolve);
44
+ });
45
+ },
46
+ };
47
+ };
48
+ //# sourceMappingURL=json-fields.js.map
@@ -0,0 +1,19 @@
1
+ /** One related entity with every role it holds and how sure each is: `reported` is a CRM's word only. */
2
+ export const relatedLine = ({ ref, name, roles }) => ` ${name ?? ref} ${ref} ${roles
3
+ .map((role) => [role.kind, role.role, role.position && `(${role.position})`, role.standing, role.account && `by ${role.account}`]
4
+ .filter(Boolean)
5
+ .join(" "))
6
+ .join("; ")}`;
7
+ /** A section's first items, and the command that lists the rest when it was cut. */
8
+ export const sectionLines = (title, section, line = relatedLine) => section.items.length === 0
9
+ ? []
10
+ : [
11
+ title,
12
+ ...section.items.map(line),
13
+ ...(section.hasMore ? [` ${section.total} in all${section.next ? ` — wcat ${section.next}` : ""}`] : []),
14
+ ];
15
+ export const coverageLines = (coverage) => [
16
+ `Read: ${coverage.accounts.join(", ") || "no account"}`,
17
+ ...coverage.notRead.map(({ source, reason }) => `Not read: ${source} — ${reason}`),
18
+ ];
19
+ //# sourceMappingURL=business-text.js.map
@@ -0,0 +1,435 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { timezoneOf } from "@wirecat/cli-base/query";
4
+ import { answerEntity, CATEGORIES, DEAL_ROLES, ENGAGEMENT_LEVELS, LOCAL_READ, LOCAL_WRITE, listQuery, ORGANIZATION_KINDS, ORGANIZATION_ROLES, ORGANIZATIONS_QUERY, organizationContext, PROJECT_ROLES, PROJECT_TYPES, PROJECTS_QUERY, proposalRegistry, purposesOf, queryTerms, RELATION_KINDS, REMINDERS_QUERY, SCOPES, termField, typedQuery, withQuery, } from "@wirecat/cli-core";
5
+ import { InvalidArgumentError } from "commander";
6
+ import { answers, itemAnswer, listAnswer, shortenedBy, wholeList, withStore } from "../answer.js";
7
+ import { byOption, deciderOf, reasonOption, whoRuns } from "../author.js";
8
+ import { oneOf, positive, readScope, writeScope } from "../options.js";
9
+ import { withOwner } from "../people/owner.js";
10
+ import { decideOne, decisionOf } from "../review/review.js";
11
+ import { deniedCrmKinds } from "../search/denied.js";
12
+ import { crmNotes, crmViewingAll } from "../store/crm-viewer.js";
13
+ import { groupScopeOf, keepInGroup } from "../store/group.js";
14
+ import { lockedCoverage, stripped } from "../store/guard.js";
15
+ import { ACCOUNTS_HELP, accountName, theAccounts, writeAccount, } from "../store/source-list.js";
16
+ import { keyDocuments, markKey, projectOf, unmarkKey } from "./key-documents.js";
17
+ import { KEY_DOCUMENTS_QUERY, keyDocument } from "./list-queries.js";
18
+ import { meetingProjectsCommand } from "./meeting-projects-command.js";
19
+ import { notesAbout } from "./notes-about.js";
20
+ import { organizationDeleteCommand } from "./organization-delete-command.js";
21
+ import { organizationText } from "./organization-text.js";
22
+ import { projectActionsCommand } from "./project-actions-command.js";
23
+ import { projectActivityCommand } from "./project-activity-command.js";
24
+ import { projectContext, projectContextText } from "./project-context.js";
25
+ import { projectGatherCommand } from "./project-gather-command.js";
26
+ import { projectStatusCommand } from "./project-status-command.js";
27
+ import { projectTransferCommand } from "./project-transfer-command.js";
28
+ import { listRelationships, RELATIONSHIP_QUERY, relationshipsText } from "./relationships.js";
29
+ import { relationshipsScanCommand, scanStep } from "./relationships-scan.js";
30
+ import { relationshipRolesCommand } from "./roles-command.js";
31
+ const ROLE_HELP = `its role: in an organization ${ORGANIZATION_ROLES.join(", ")}; in a project ${PROJECT_ROLES.join(", ")}; ` +
32
+ `on a deal or lead ${DEAL_ROLES.join(", ")}. A job title is not a role`;
33
+ const ORGANIZATIONS_LIST_QUERY = {
34
+ ...ORGANIZATIONS_QUERY,
35
+ fields: [
36
+ ...ORGANIZATIONS_QUERY.fields,
37
+ termField("category", "enum", "category:client", {
38
+ values: CATEGORIES,
39
+ relation: "what its relationships with your own organizations, or yours with it, make it",
40
+ }),
41
+ ],
42
+ };
43
+ /** `category:` is read from relationships in the store's own query, so it is taken out of the list's words first. */
44
+ const categoryOf = (words) => {
45
+ const named = words.map((word) => /^category:(.+)$/.exec(word)?.[1]);
46
+ const category = named.find((one) => one !== undefined);
47
+ return { ...(category === undefined ? {} : { category }), rest: words.filter((_, at) => named[at] === undefined) };
48
+ };
49
+ /** A day as `--start-date 2026-01-01` gives it: its start, UTC ms. */
50
+ const dayOption = (value) => {
51
+ const at = Date.parse(`${value}T00:00:00Z`);
52
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || Number.isNaN(at))
53
+ throw new InvalidArgumentError("a day, such as 2026-01-01");
54
+ return at;
55
+ };
56
+ /** `--end-date` is the last day it held; cli-core's end is the moment after it. */
57
+ const lastDayOption = (value) => dayOption(value) + 86_400_000;
58
+ /** A suggested link the review lists as `link:<id>`; deciding it goes through the same registry as review. */
59
+ const pendingLink = async (store, id) => {
60
+ try {
61
+ return await proposalRegistry(store).get(`link:${id}`);
62
+ }
63
+ catch (error) {
64
+ if (error instanceof CliError && error.code === "not_found")
65
+ return undefined;
66
+ throw error;
67
+ }
68
+ };
69
+ const ENGAGEMENT_HELP = "a person on a project: how much you deal with them yourself, not how active they are: none, low, medium or high";
70
+ export const knowledgeCommands = (program, streams, env) => {
71
+ const { run, print } = answers(program, streams, env);
72
+ const warn = (text) => streams.diagnostic(text);
73
+ const act = (options, work) => run(options.json, async (store) => work(store, await writeAccount(store, env, options, warn)));
74
+ /** Organisations and relations are the owner's, not an account's. */
75
+ const owned = (options, work) => run(options.json, async (store) => itemAnswer(await work(store)));
76
+ const ownedList = (command, options, work) => run(options.json, async (store) => wholeList(command, await work(store)));
77
+ const organizations = program
78
+ .command("organizations")
79
+ .description("companies, teams, families and communities of yours");
80
+ annotate(organizations.command("add"), { effects: LOCAL_WRITE, literal_after_dashes: true })
81
+ .description("add an organization of yours: a company, team, family or community; it is written at once, whoever runs it")
82
+ .summary("add an organization")
83
+ .argument("<name>", "the organization's name")
84
+ .requiredOption("--kind <kind>", ORGANIZATION_KINDS.join(", "), oneOf(ORGANIZATION_KINDS))
85
+ .option("--scope <scope>", SCOPES.join(", "), oneOf(SCOPES))
86
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
87
+ .action((name, options) => owned(options, (store) => store.knowledge.addOrganization({
88
+ kind: options.kind,
89
+ name,
90
+ ...(options.scope === undefined ? {} : { scope: options.scope }),
91
+ })));
92
+ annotate(organizations.command("rename"), { effects: LOCAL_WRITE, literal_after_dashes: true })
93
+ .description("rename an organization of yours; it is written at once, whoever runs it")
94
+ .summary("rename an organization")
95
+ .argument("<organization>", "its id or organization:<id>")
96
+ .argument("<name>", "the new name")
97
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
98
+ .action((reference, name, options) => owned(options, (store) => store.knowledge.updateOrganization(`organization:${reference.replace(/^organization:/, "")}`, { name })));
99
+ organizationDeleteCommand(organizations, program, streams, env);
100
+ annotate(organizations.command("show"), { effects: LOCAL_READ })
101
+ .description("one organization by its id or organization:<id>, without its relationships, notes and tags")
102
+ .summary("one organization")
103
+ .argument("<organization>", "its id or organization:<id>")
104
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
105
+ .action((reference, options) => owned(options, async (store) => {
106
+ const wanted = reference.replace(/^organization:/, "");
107
+ const found = (await store.knowledge.organizations()).find((organization) => organization.id === wanted);
108
+ if (found === undefined)
109
+ throw new CliError("not_found", `no organization ${reference}; wcat organizations list shows them`);
110
+ return found;
111
+ }));
112
+ withQuery(annotate(organizations.command("list"), { effects: LOCAL_READ }), ORGANIZATIONS_LIST_QUERY)
113
+ .description("your organizations; category:client, supplier, partner or employer keeps those its relationships make so")
114
+ .summary("your organizations")
115
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
116
+ .action((words, options) => {
117
+ const { category, rest } = categoryOf(words);
118
+ const query = listQuery(typedQuery(rest), ORGANIZATIONS_QUERY, "organizations list");
119
+ return ownedList("organizations list", options, async (store) => {
120
+ const scope = await groupScopeOf(store, env);
121
+ const found = await store.knowledge.organizations(query, {
122
+ ...(category === undefined ? {} : { category }),
123
+ ...(scope === undefined ? {} : { accounts: scope.accounts }),
124
+ });
125
+ return keepInGroup(store, env, found, ({ ref }) => ref);
126
+ });
127
+ });
128
+ annotate(organizations.command("context"), {
129
+ effects: LOCAL_READ,
130
+ output: { entity: "organization_context_memo" },
131
+ })
132
+ .description("one organization by its id or organization:<id>: its people by role, customers, suppliers and partners, " +
133
+ "projects, open deals and leads, invoices, payments and orders, what its people wrote, newest first, open " +
134
+ "tasks and categories, each relationship with its standing; then the notes about it and its tags. `coverage` names " +
135
+ "what was not read")
136
+ .summary("one organization: people, customers, deals, money, tasks, notes")
137
+ .argument("<organization>", "its id or organization:<id>")
138
+ .option("--limit <n>", "most items in each section", positive, 20)
139
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
140
+ .action(async (reference, options, command) => {
141
+ const { answer, notes } = await withStore(env, async (store) => {
142
+ const scope = await groupScopeOf(store, env);
143
+ const found = await organizationContext(store, reference, {
144
+ limit: options.limit,
145
+ ...(scope === undefined ? {} : { accounts: scope.accounts }),
146
+ deniedKinds: deniedCrmKinds(command, env),
147
+ viewing: await crmViewingAll(store),
148
+ });
149
+ const ref = found.organization.ref;
150
+ const answer = await lockedCoverage(store, env, {
151
+ ...found,
152
+ notes: await notesAbout(store, { ref }, 20, scope?.accounts),
153
+ tags: await store.knowledge.tags(null, { type: "organization", id: ref.slice("organization:".length) }),
154
+ untrusted: ["history.items.title", "history.items.text"],
155
+ });
156
+ return { answer, notes: crmNotes(store) };
157
+ });
158
+ print(options.json, shortenedBy(notes, itemAnswer(answer)), organizationText(answer));
159
+ });
160
+ const projects = program.command("projects").description("projects of yours, each with a short key");
161
+ meetingProjectsCommand(projects, streams, env);
162
+ annotate(projects.command("add"), { effects: LOCAL_WRITE, literal_after_dashes: true })
163
+ .description("add a project of yours, with a short key its tasks use")
164
+ .argument("<name>", "the project's name")
165
+ .option("--key <key>", "3–4 letters and digits; made from the name when left out")
166
+ .option("--type <type>", PROJECT_TYPES.join(", "), oneOf(PROJECT_TYPES))
167
+ .option("--organization <organization>", "the organization it belongs to: its id or organization:<id>")
168
+ .option("--scope <scope>", SCOPES.join(", "), oneOf(SCOPES))
169
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
170
+ .action((name, options) => owned(options, (store) => store.knowledge.addProject({
171
+ name,
172
+ ...(options.key === undefined ? {} : { key: options.key }),
173
+ ...(options.type === undefined ? {} : { type: options.type }),
174
+ ...(options.organization === undefined
175
+ ? {}
176
+ : { organization: `organization:${options.organization.replace(/^organization:/, "")}` }),
177
+ ...(options.scope === undefined ? {} : { scope: options.scope }),
178
+ })));
179
+ withQuery(annotate(projects.command("list"), { effects: LOCAL_READ }), PROJECTS_QUERY)
180
+ .description("your projects")
181
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
182
+ .action((words, options) => {
183
+ const query = listQuery(typedQuery(words), PROJECTS_QUERY, "projects list");
184
+ return ownedList("projects list", options, (store) => store.knowledge.projects(query));
185
+ });
186
+ annotate(projects.command("context"), { effects: LOCAL_READ })
187
+ .description("one project by its id, project:<id>, key, exact name or alias: its key documents first, then its " +
188
+ "relationships, notes, tags, pending findings and open tasks. Review proposals together; nothing is confirmed. `review.waiting` counts what waits for you, by kind, " +
189
+ "and `next` names the command that lists them")
190
+ .summary("one project: key documents, pending findings and open tasks; start work here")
191
+ .argument("<project>", "its id, project:<id>, key, exact name or alias")
192
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
193
+ .action(async (reference, options) => {
194
+ const { context, next } = await withStore(env, async (store) => {
195
+ const context = await stripped(store, env, await projectContext(store, env, reference));
196
+ return { context, next: await scanStep(store, context.project, "all") };
197
+ });
198
+ print(options.json, itemAnswer(context, next.length ? { next } : {}), projectContextText(context));
199
+ });
200
+ projectGatherCommand(projects, print, env, warn);
201
+ projectStatusCommand(projects, print, env);
202
+ projectActivityCommand(program, streams, env);
203
+ projectActionsCommand(projects, streams, env);
204
+ projectTransferCommand(projects, streams, env);
205
+ const keys = projects
206
+ .command("key-documents")
207
+ .description("the notes, files and messages to read first about a project, each with why");
208
+ byOption(annotate(keys.command("add"), { effects: LOCAL_WRITE })
209
+ .description("mark a note:, document: or msg: reference as a key document of the project")
210
+ .argument("<project>", "id, project:<id>, key, exact name or alias")
211
+ .argument("<reference>", "note:, document: or msg: reference")
212
+ .requiredOption("--reason <text>", "why it is key, in a few words")
213
+ .option("--json", "print JSON; --json=id,title keeps only those fields")).action(async (project, reference, options, command) => {
214
+ const by = await whoRuns(command, env, { asOwner: options.asOwner, question: "mark it key as you?" });
215
+ await owned(options, async (store) => markKey(store, await projectOf(store, project), reference, options.reason, by));
216
+ });
217
+ byOption(annotate(keys.command("remove"), { effects: LOCAL_WRITE })
218
+ .description("unmark a key document; the note, file or message stays. Only you remove one")
219
+ .argument("<project>", "id, project:<id>, key, exact name or alias")
220
+ .argument("<reference>", "the key document's note:, document: or msg: reference")
221
+ .option("--json", "print JSON; --json=id,title keeps only those fields")).action(async (project, reference, options, command) => {
222
+ const by = await deciderOf(command, env, { ...options, question: `unmark ${reference} as you, the owner?` });
223
+ await owned(options, async (store) => unmarkKey(store, await projectOf(store, project), reference, by));
224
+ });
225
+ answerEntity(withQuery(annotate(keys.command("list"), { effects: LOCAL_READ })
226
+ .description("a project's key documents: why, who marked each and whether it is still there")
227
+ .argument("<project>", "id, project:<id>, key, exact name or alias"), KEY_DOCUMENTS_QUERY), "memo_key_document", keyDocument)
228
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
229
+ .action((project, words, options) => {
230
+ const id = queryTerms(words, KEY_DOCUMENTS_QUERY, "projects key-documents list").get("id");
231
+ return ownedList("projects key-documents list", options, async (store) => keyDocuments(store, await projectOf(store, project), id === undefined ? {} : { id }));
232
+ });
233
+ const relations = program
234
+ .command("relationships")
235
+ .description("relations between people, organizations and projects; never between identities");
236
+ byOption(annotate(relations.command("add"), { effects: LOCAL_WRITE })
237
+ .description("state that a person, organization or project belongs to, reports to, is a customer or partner of, or relates " +
238
+ "to another, or that a chat is a project's (member-of only); an agent's waits for you to confirm it")
239
+ .summary("state that a person, organization, project or chat belongs or relates to another"))
240
+ .argument("<from>", "the person:, organization: or project: that belongs or relates, or chat:<provider>/<account>/<chat> of a project")
241
+ .argument("<to>", "the person:, organization: or project: it belongs or relates to")
242
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
243
+ .option("--kind <kind>", RELATION_KINDS.join(", "), oneOf(RELATION_KINDS), "member-of")
244
+ .option("--role <role>", ROLE_HELP)
245
+ .option("--role-note <text>", "what the role means here, in your words, beside a role from its list")
246
+ .option("--engagement <level>", ENGAGEMENT_HELP, oneOf(ENGAGEMENT_LEVELS))
247
+ .option("--position <title>", "the job title, such as 'Procurement manager'; kept apart from the role")
248
+ .option("--start-date <date>", "the first day it held, such as 2026-01-01", dayOption)
249
+ .option("--end-date <date>", "the last day it held, included; it ends at the start of the day after", lastDayOption)
250
+ .option("--reason <text>", "why you think so, in a sentence")
251
+ .action(async (from, to, options, command) => {
252
+ const by = await whoRuns(command, env, { asOwner: options.asOwner, question: "state it as yours?" });
253
+ return owned(options, async (store) => {
254
+ const input = {
255
+ from: await withOwner(store, from),
256
+ to: await withOwner(store, to),
257
+ kind: options.kind,
258
+ ...(options.role === undefined ? {} : { role: options.role }),
259
+ ...(options.roleNote === undefined ? {} : { roleNote: options.roleNote }),
260
+ ...(options.engagement === undefined ? {} : { engagement: options.engagement }),
261
+ ...(options.position === undefined ? {} : { position: options.position }),
262
+ ...(options.startDate === undefined ? {} : { startsAt: options.startDate }),
263
+ ...(options.endDate === undefined ? {} : { endsAt: options.endDate }),
264
+ ...(options.reason === undefined ? {} : { evidence: options.reason }),
265
+ };
266
+ return by === "owner"
267
+ ? store.knowledge.relate(null, { ...input, by })
268
+ : store.knowledge.relate(null, { ...input, by });
269
+ });
270
+ });
271
+ withQuery(annotate(relations.command("list"), { effects: LOCAL_READ })
272
+ .description("relationships (who works where, who reports to whom, who is on a deal), all or those of one reference, with " +
273
+ "titles; confirmed:false lists the proposals waiting for you, as wcat review kind:relationship does")
274
+ .summary("relationships with titles; confirmed:false lists those waiting for you"), RELATIONSHIP_QUERY)
275
+ .option("--limit <n>", "most relationships, up to 500", (value) => Math.min(positive(value), 500), 100)
276
+ .option("--page <n>", "which page, from 1", positive, 1)
277
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
278
+ .action(async (words, options, command) => {
279
+ const found = await withStore(env, async (store) => {
280
+ const scope = await groupScopeOf(store, env);
281
+ const listed = await listRelationships(store, env, words, {
282
+ limit: options.limit,
283
+ page: options.page,
284
+ ...(scope === undefined ? {} : { accounts: scope.accounts }),
285
+ deniedKinds: deniedCrmKinds(command, env),
286
+ });
287
+ return { ...listed, notes: crmNotes(store) };
288
+ });
289
+ print(options.json, shortenedBy(found.notes, listAnswer("relationships list", {
290
+ items: found.items,
291
+ limit: found.limit,
292
+ has_more: found.hasMore,
293
+ page: found.page,
294
+ args: { query: words.join(" ") },
295
+ })), relationshipsText(found.items));
296
+ });
297
+ byOption(annotate(relations.command("update"), { effects: LOCAL_WRITE })
298
+ .description("set what a relationship is: its role and a note beside it, how much you deal with a person on a project, or " +
299
+ "what a chat is for in a project (work, sales, support, other); an agent's change waits for you in wcat review")
300
+ .summary("set a relationship's role, engagement or a chat's purpose in a project")
301
+ .argument("<id>", "the relationship's id, as relationships list gives it")
302
+ .option("--role <role>", `${ROLE_HELP}; an empty value clears it`)
303
+ .option("--role-note <text>", "what the role means here, in your words; an empty value clears it")
304
+ .option("--engagement <level>", `${ENGAGEMENT_HELP}; an empty value clears it`, (value) => value === "" ? "" : oneOf(ENGAGEMENT_LEVELS)(value))
305
+ .option("--position <title>", "the job title; an empty value clears it")
306
+ .option("--start-date <date>", "the first day it held, such as 2026-01-01", dayOption)
307
+ .option("--purpose <purpose>", "what the chat is for in the project: work, sales, support or other")
308
+ .option("--reason <text>", "why, in a sentence")
309
+ .option("--json", "print JSON; --json=id,title keeps only those fields")).action(async (id, options, command) => {
310
+ const cleared = (value) => (value === "" ? null : value);
311
+ const change = {
312
+ ...(options.role === undefined ? {} : { role: cleared(options.role) }),
313
+ ...(options.roleNote === undefined ? {} : { roleNote: cleared(options.roleNote) }),
314
+ ...(options.engagement === undefined ? {} : { engagement: cleared(options.engagement) }),
315
+ ...(options.position === undefined ? {} : { position: cleared(options.position) }),
316
+ ...(options.startDate === undefined ? {} : { startsAt: options.startDate }),
317
+ ...(options.purpose === undefined ? {} : { purpose: options.purpose }),
318
+ };
319
+ const by = await whoRuns(command, env, { asOwner: options.asOwner, question: `change relationship ${id}?` });
320
+ return owned(options, async (store) => {
321
+ if (Object.keys(change).length === 0)
322
+ throw new CliError("validation_error", "say what to change: --role, --role-note, --engagement, --position, --start-date or --purpose", {
323
+ reason: "input.invalid",
324
+ param: "--purpose",
325
+ });
326
+ if (options.purpose !== undefined)
327
+ purposesOf([options.purpose]);
328
+ return by === "owner"
329
+ ? store.knowledge.updateRelation(null, id, { ...change, by })
330
+ : store.knowledge.updateRelation(null, id, {
331
+ ...change,
332
+ by,
333
+ ...(options.reason === undefined ? {} : { reason: options.reason }),
334
+ });
335
+ });
336
+ });
337
+ for (const [name, description] of [
338
+ ["remove", "remove a relationship; removing a suggested one rejects it"],
339
+ ["confirm", "confirm a suggested relationship"],
340
+ ])
341
+ reasonOption(byOption(annotate(relations.command(name), { effects: LOCAL_WRITE })
342
+ .description(description)
343
+ .argument("<id>", "the relationship's id, as relationships list gives it")
344
+ .option("--json", "print JSON; --json=id,title keeps only those fields"))).action(async (id, options, command) => {
345
+ const by = await deciderOf(command, env, {
346
+ ...options,
347
+ question: `${name} relationship ${id} as you, the owner?`,
348
+ });
349
+ await owned(options, async (store) => {
350
+ const suggestion = await pendingLink(store, id);
351
+ if (suggestion === undefined)
352
+ return name === "remove"
353
+ ? store.knowledge.removeRelation(null, id, by)
354
+ : store.knowledge.confirmRelation(null, id, by);
355
+ await decideOne(store, env, suggestion.id, decisionOf(name === "confirm", by, options.reason));
356
+ if (name === "remove")
357
+ return { id, removed: true };
358
+ return (await store.knowledge.relations(null, suggestion.subject)).find((one) => one.id === id);
359
+ });
360
+ });
361
+ byOption(annotate(relations.command("end"), { effects: LOCAL_WRITE })
362
+ .description("say that a relationship no longer holds, from a day on; it stays, as ended, and relationships list " +
363
+ "include:ended shows it. An agent's waits for you in wcat review")
364
+ .summary("say that a relationship ended")
365
+ .argument("<id>", "the relationship's id, as relationships list gives it")
366
+ .option("--end-date <date>", "the last day it held, included; it ends at the start of the day after. Today when left out", lastDayOption)
367
+ .option("--json", "print JSON; --json=id,title keeps only those fields")).action(async (id, options, command) => {
368
+ const by = await whoRuns(command, env, { asOwner: options.asOwner, question: `end relationship ${id}?` });
369
+ const at = options.endDate ?? Date.now();
370
+ return owned(options, async (store) => {
371
+ return by === "owner"
372
+ ? store.knowledge.endRelation(null, id, at, by)
373
+ : store.knowledge.endRelation(null, id, at, by);
374
+ });
375
+ });
376
+ relationshipRolesCommand(relations, { print }, env);
377
+ relationshipsScanCommand(relations, print, env, warn);
378
+ const reminders = program
379
+ .command("reminders")
380
+ .description("durable local reminders; poll hands one out and ack confirms it was shown");
381
+ writeScope(annotate(reminders.command("add"), { effects: LOCAL_WRITE })
382
+ .description("add a reminder for an open task")
383
+ .argument("<task>", "the task's id"))
384
+ .requiredOption("--at-time <time>", "when to remind: an ISO 8601 time with its UTC offset")
385
+ .option("--timezone <zone>", "IANA timezone; the computer's when not given")
386
+ .action((task, options) => act(options, async (store, key) => {
387
+ if ((await store.tasks.get(task)) === undefined && (await store.tasks.projectTask(task)))
388
+ throw new CliError("validation_error", `${task} is a task in a project; a reminder belongs to an account, so it needs a task from a message, ` +
389
+ "a note or a file — wcat tasks add <source>");
390
+ return itemAnswer(await store.knowledge.schedule(key, task, options.atTime, timezoneOf(options.timezone)));
391
+ }));
392
+ readScope(withQuery(annotate(reminders.command("list"), { effects: LOCAL_READ }).description("pending reminders of the accounts --source names (default all), soonest first"), REMINDERS_QUERY), ACCOUNTS_HELP).action((words, options) => {
393
+ const query = listQuery(typedQuery(words), REMINDERS_QUERY, "reminders list");
394
+ return run(options.json, async (store) => {
395
+ const keys = await theAccounts(store, env, options, warn);
396
+ const items = (await Promise.all(keys.map(async (key) => (await store.knowledge.reminders(key, query)).map((reminder) => ({ ...reminder, account: accountName(key) })))))
397
+ .flat()
398
+ .sort((a, b) => a.dueAt.localeCompare(b.dueAt));
399
+ return listAnswer("reminders list", {
400
+ items,
401
+ limit: Math.max(1, items.length),
402
+ has_more: false,
403
+ meta: { accounts: keys.map(accountName) },
404
+ });
405
+ });
406
+ });
407
+ writeScope(annotate(reminders.command("claim"), { effects: LOCAL_WRITE }).description("hand out due reminders, each with a receipt to acknowledge"))
408
+ .option("--limit <n>", "most due reminders, at most 500", positive, 100)
409
+ .action((options) => act(options, async (store, key) => {
410
+ const claimed = await store.knowledge.claimReminders(key, { limit: options.limit });
411
+ return listAnswer("reminders claim", {
412
+ items: claimed.map((reminder) => ({
413
+ ...reminder,
414
+ deliveryId: `${reminder.id}:${reminder.revision}`,
415
+ delivery: "local",
416
+ })),
417
+ limit: options.limit,
418
+ has_more: claimed.length >= options.limit,
419
+ });
420
+ }));
421
+ writeScope(annotate(reminders.command("acknowledge"), { effects: LOCAL_WRITE })
422
+ .description("confirm that a handed-out reminder was shown")
423
+ .argument("<id>", "the reminder's id")
424
+ .argument("<receipt>", "the receipt reminders claim handed out with it")).action((id, receipt, options) => act(options, async (store, key) => itemAnswer(await store.knowledge.acknowledgeReminder(key, id, receipt))));
425
+ writeScope(annotate(reminders.command("cancel"), { effects: LOCAL_WRITE })
426
+ .description("cancel a reminder")
427
+ .argument("<id>", "the reminder's id")).action((id, options) => act(options, async (store, key) => itemAnswer(await store.knowledge.cancelReminder(key, id))));
428
+ writeScope(annotate(reminders.command("update"), { effects: LOCAL_WRITE })
429
+ .description("move a reminder to another time")
430
+ .argument("<id>", "the reminder's id"))
431
+ .requiredOption("--at-time <time>", "the new time: an ISO 8601 time with its UTC offset")
432
+ .requiredOption("--revision <n>", "the reminder's current revision, as reminders list gives it", positive)
433
+ .action((id, options) => act(options, async (store, key) => itemAnswer(await store.knowledge.snoozeReminder(key, id, options.atTime, options.revision))));
434
+ };
435
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1,33 @@
1
+ const MAX_DEPTH = 20;
2
+ /** What the owner needs to judge an item about a document without leaving the review: what it is and where. */
3
+ export const documentContext = async (store, ref) => {
4
+ const note = await store.notes.note(ref).catch(() => null);
5
+ if (!note || note.deletedAt)
6
+ return null;
7
+ const { folderId } = note;
8
+ const entryOf = async (externalId) => folderId === null ? undefined : await store.catalog.get(folderId, externalId).catch(() => undefined);
9
+ const entry = note.path === null ? undefined : await entryOf(note.path);
10
+ // Without its catalog entry a Drive document's stored path is Drive's file id, not a place the owner knows.
11
+ if (!entry)
12
+ return { ref: note.ref, title: note.title, path: null, url: null, modifiedAt: note.modifiedAt, mime: null };
13
+ const names = [entry.name];
14
+ const seen = new Set([note.path]);
15
+ let parent = entry.parents[0];
16
+ for (let depth = 0; parent !== undefined && !seen.has(parent) && depth < MAX_DEPTH; depth++) {
17
+ seen.add(parent);
18
+ const folder = await entryOf(parent);
19
+ if (!folder)
20
+ break;
21
+ names.unshift(folder.name);
22
+ parent = folder.parents[0];
23
+ }
24
+ return {
25
+ ref: note.ref,
26
+ title: entry.name,
27
+ path: names.join("/"),
28
+ url: entry.url ?? null,
29
+ modifiedAt: entry.modifiedAt ?? note.modifiedAt,
30
+ mime: entry.mime ?? null,
31
+ };
32
+ };
33
+ //# sourceMappingURL=document-context.js.map