tenjin-cli 0.1.0-alpha.12 → 0.1.0-alpha.13

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 (126) hide show
  1. package/README.md +1 -0
  2. package/dist/{buy-3DTBFZ4B.js → buy-X4VPHFUA.js} +20 -20
  3. package/dist/{chunk-V5UHKC46.js → chunk-3NZCU6SD.js} +7 -7
  4. package/dist/{chunk-Y7ERTA7D.js → chunk-3P3ES4XU.js} +4 -6
  5. package/dist/chunk-3P3ES4XU.js.map +1 -0
  6. package/dist/{chunk-OZHJ3FLR.js → chunk-47YKYDOF.js} +5 -5
  7. package/dist/{chunk-WWIKAJFO.js → chunk-6JKD46OJ.js} +12 -10
  8. package/dist/{chunk-WWIKAJFO.js.map → chunk-6JKD46OJ.js.map} +1 -1
  9. package/dist/chunk-736DW4V3.js +65 -0
  10. package/dist/chunk-736DW4V3.js.map +1 -0
  11. package/dist/{chunk-IB63U6BM.js → chunk-B676GPS2.js} +34 -11
  12. package/dist/chunk-B676GPS2.js.map +1 -0
  13. package/dist/{chunk-4NTZETIL.js → chunk-BRAVLUGI.js} +2 -2
  14. package/dist/{chunk-HWHYPCCH.js → chunk-CA3JV7FX.js} +2 -2
  15. package/dist/{chunk-HWHYPCCH.js.map → chunk-CA3JV7FX.js.map} +1 -1
  16. package/dist/{chunk-ALUNME53.js → chunk-ELVDOTU7.js} +50 -66
  17. package/dist/chunk-ELVDOTU7.js.map +1 -0
  18. package/dist/{chunk-ILDVGY7K.js → chunk-GCGMXA2O.js} +13 -11
  19. package/dist/{chunk-ILDVGY7K.js.map → chunk-GCGMXA2O.js.map} +1 -1
  20. package/dist/{chunk-L3I2MVKR.js → chunk-IAR25V2E.js} +6 -6
  21. package/dist/{chunk-6UY2UQMY.js → chunk-IFPKA32J.js} +4 -4
  22. package/dist/{chunk-JTYIX6OD.js → chunk-IGHSLJUF.js} +6 -4
  23. package/dist/{chunk-JTYIX6OD.js.map → chunk-IGHSLJUF.js.map} +1 -1
  24. package/dist/{chunk-7MJVNALU.js → chunk-IKAJSA7E.js} +12 -10
  25. package/dist/{chunk-7MJVNALU.js.map → chunk-IKAJSA7E.js.map} +1 -1
  26. package/dist/{chunk-NUF2PKJO.js → chunk-J6FUAIRR.js} +4 -6
  27. package/dist/{chunk-NUF2PKJO.js.map → chunk-J6FUAIRR.js.map} +1 -1
  28. package/dist/{chunk-CNUXRXI2.js → chunk-JVBMPU5G.js} +5 -7
  29. package/dist/{chunk-CNUXRXI2.js.map → chunk-JVBMPU5G.js.map} +1 -1
  30. package/dist/{chunk-6RMEX74N.js → chunk-L4XNT3UW.js} +21 -16
  31. package/dist/chunk-L4XNT3UW.js.map +1 -0
  32. package/dist/{chunk-X2WZPGCF.js → chunk-NKN4YC5C.js} +5 -5
  33. package/dist/{chunk-P74I3WH4.js → chunk-OC3EIDCP.js} +3 -5
  34. package/dist/{chunk-P74I3WH4.js.map → chunk-OC3EIDCP.js.map} +1 -1
  35. package/dist/{chunk-E6YOODH7.js → chunk-OE36HRWG.js} +31 -5
  36. package/dist/{chunk-E6YOODH7.js.map → chunk-OE36HRWG.js.map} +1 -1
  37. package/dist/chunk-OUJDDY5L.js +189 -0
  38. package/dist/chunk-OUJDDY5L.js.map +1 -0
  39. package/dist/{chunk-6BGYHARE.js → chunk-OWVVI4VQ.js} +15 -15
  40. package/dist/{chunk-4TCU3YRD.js → chunk-OXUJ3FXU.js} +5 -1
  41. package/dist/{chunk-4TCU3YRD.js.map → chunk-OXUJ3FXU.js.map} +1 -1
  42. package/dist/{chunk-PZRAAAY2.js → chunk-PAOVPSP6.js} +10 -3
  43. package/dist/chunk-PAOVPSP6.js.map +1 -0
  44. package/dist/{chunk-TUXKOIOU.js → chunk-SPUORKD7.js} +3 -3
  45. package/dist/{chunk-UFPJBS4C.js → chunk-T4UWMVKV.js} +9 -7
  46. package/dist/{chunk-UFPJBS4C.js.map → chunk-T4UWMVKV.js.map} +1 -1
  47. package/dist/{chunk-CLOEU7RA.js → chunk-TXVC46SA.js} +8 -8
  48. package/dist/{chunk-SFGXAZ3M.js → chunk-UUARTUY2.js} +42 -9
  49. package/dist/chunk-UUARTUY2.js.map +1 -0
  50. package/dist/{chunk-ROAK2DOX.js → chunk-WMFRCSNC.js} +8 -8
  51. package/dist/{chunk-TDDN5GXR.js → chunk-WU5CZPLD.js} +5 -5
  52. package/dist/{chunk-RSBN67PA.js → chunk-WVHPGQH5.js} +4 -6
  53. package/dist/{chunk-RSBN67PA.js.map → chunk-WVHPGQH5.js.map} +1 -1
  54. package/dist/{chunk-PZSUWDF2.js → chunk-XGZ5EVMB.js} +2 -2
  55. package/dist/{chunk-MBKFZBB2.js → chunk-XXY77EZJ.js} +24 -24
  56. package/dist/{chunk-CBNXUQGM.js → chunk-YMUJZWHB.js} +10 -8
  57. package/dist/{chunk-CBNXUQGM.js.map → chunk-YMUJZWHB.js.map} +1 -1
  58. package/dist/{cli-3WZGLZDP.js → cli-XK5JZWU6.js} +51 -146
  59. package/dist/cli-XK5JZWU6.js.map +1 -0
  60. package/dist/{config-WDGMZKHU.js → config-CNK7MYUR.js} +7 -7
  61. package/dist/doctor-R7N7FUX5.js +27 -0
  62. package/dist/{edit-4UZQVFCK.js → edit-QSUEG7CL.js} +19 -19
  63. package/dist/{fund-JAPOFTUG.js → fund-JF6A76YS.js} +16 -16
  64. package/dist/index.js +1 -1
  65. package/dist/{inspect-IEV75A42.js → inspect-NFNAA4LA.js} +17 -17
  66. package/dist/{install-WXTOHDWC.js → install-YQVM3SUW.js} +20 -21
  67. package/dist/{install-WXTOHDWC.js.map → install-YQVM3SUW.js.map} +1 -1
  68. package/dist/outcome-IUSYFJTN.js +22 -0
  69. package/dist/{publish-6QNARH7E.js → publish-O2I6IAEL.js} +20 -20
  70. package/dist/{read-UAZGZ4UL.js → read-UF7QVQOU.js} +21 -21
  71. package/dist/{run-AJNCOT5R.js → run-GDZWHNWZ.js} +30 -30
  72. package/dist/search-JVOHEF3E.js +23 -0
  73. package/dist/{send-F34ZDXDZ.js → send-SI254H3R.js} +11 -10
  74. package/dist/{send-F34ZDXDZ.js.map → send-SI254H3R.js.map} +1 -1
  75. package/dist/{session-4N4ZT3AH.js → session-GJZJEXLJ.js} +14 -14
  76. package/dist/{skill-heal-XBEK272G.js → skill-heal-BPFT22XS.js} +5 -6
  77. package/dist/{skill-heal-XBEK272G.js.map → skill-heal-BPFT22XS.js.map} +1 -1
  78. package/dist/{uninstall-BTKPHPDL.js → uninstall-7ZZG6WQ5.js} +6 -7
  79. package/dist/{uninstall-BTKPHPDL.js.map → uninstall-7ZZG6WQ5.js.map} +1 -1
  80. package/dist/update-FPSBITLB.js +315 -0
  81. package/dist/update-FPSBITLB.js.map +1 -0
  82. package/dist/{wallet-UL4P2JRO.js → wallet-NS7TYWNN.js} +5 -6
  83. package/dist/{wallet-WJ6UP5OU.js → wallet-TZVD2M4I.js} +9 -9
  84. package/docs/agent-permissions.md +11 -0
  85. package/docs/command-reference.md +47 -0
  86. package/package.json +1 -1
  87. package/skills/tenjin-publish/SKILL.md +15 -2
  88. package/dist/chunk-2I4QTOLB.js +0 -11
  89. package/dist/chunk-2I4QTOLB.js.map +0 -1
  90. package/dist/chunk-6RMEX74N.js.map +0 -1
  91. package/dist/chunk-ALUNME53.js.map +0 -1
  92. package/dist/chunk-IB63U6BM.js.map +0 -1
  93. package/dist/chunk-PZRAAAY2.js.map +0 -1
  94. package/dist/chunk-SFGXAZ3M.js.map +0 -1
  95. package/dist/chunk-Y7ERTA7D.js.map +0 -1
  96. package/dist/cli-3WZGLZDP.js.map +0 -1
  97. package/dist/doctor-EKVCP7JP.js +0 -27
  98. package/dist/outcome-FYOFDOUK.js +0 -22
  99. package/dist/search-EEKTW6VK.js +0 -23
  100. /package/dist/{buy-3DTBFZ4B.js.map → buy-X4VPHFUA.js.map} +0 -0
  101. /package/dist/{chunk-V5UHKC46.js.map → chunk-3NZCU6SD.js.map} +0 -0
  102. /package/dist/{chunk-OZHJ3FLR.js.map → chunk-47YKYDOF.js.map} +0 -0
  103. /package/dist/{chunk-4NTZETIL.js.map → chunk-BRAVLUGI.js.map} +0 -0
  104. /package/dist/{chunk-L3I2MVKR.js.map → chunk-IAR25V2E.js.map} +0 -0
  105. /package/dist/{chunk-6UY2UQMY.js.map → chunk-IFPKA32J.js.map} +0 -0
  106. /package/dist/{chunk-X2WZPGCF.js.map → chunk-NKN4YC5C.js.map} +0 -0
  107. /package/dist/{chunk-6BGYHARE.js.map → chunk-OWVVI4VQ.js.map} +0 -0
  108. /package/dist/{chunk-TUXKOIOU.js.map → chunk-SPUORKD7.js.map} +0 -0
  109. /package/dist/{chunk-CLOEU7RA.js.map → chunk-TXVC46SA.js.map} +0 -0
  110. /package/dist/{chunk-ROAK2DOX.js.map → chunk-WMFRCSNC.js.map} +0 -0
  111. /package/dist/{chunk-TDDN5GXR.js.map → chunk-WU5CZPLD.js.map} +0 -0
  112. /package/dist/{chunk-PZSUWDF2.js.map → chunk-XGZ5EVMB.js.map} +0 -0
  113. /package/dist/{chunk-MBKFZBB2.js.map → chunk-XXY77EZJ.js.map} +0 -0
  114. /package/dist/{config-WDGMZKHU.js.map → config-CNK7MYUR.js.map} +0 -0
  115. /package/dist/{doctor-EKVCP7JP.js.map → doctor-R7N7FUX5.js.map} +0 -0
  116. /package/dist/{edit-4UZQVFCK.js.map → edit-QSUEG7CL.js.map} +0 -0
  117. /package/dist/{fund-JAPOFTUG.js.map → fund-JF6A76YS.js.map} +0 -0
  118. /package/dist/{inspect-IEV75A42.js.map → inspect-NFNAA4LA.js.map} +0 -0
  119. /package/dist/{outcome-FYOFDOUK.js.map → outcome-IUSYFJTN.js.map} +0 -0
  120. /package/dist/{publish-6QNARH7E.js.map → publish-O2I6IAEL.js.map} +0 -0
  121. /package/dist/{read-UAZGZ4UL.js.map → read-UF7QVQOU.js.map} +0 -0
  122. /package/dist/{run-AJNCOT5R.js.map → run-GDZWHNWZ.js.map} +0 -0
  123. /package/dist/{search-EEKTW6VK.js.map → search-JVOHEF3E.js.map} +0 -0
  124. /package/dist/{session-4N4ZT3AH.js.map → session-GJZJEXLJ.js.map} +0 -0
  125. /package/dist/{wallet-UL4P2JRO.js.map → wallet-NS7TYWNN.js.map} +0 -0
  126. /package/dist/{wallet-WJ6UP5OU.js.map → wallet-TZVD2M4I.js.map} +0 -0
@@ -6,18 +6,10 @@ import {
6
6
  deliverExisting,
7
7
  deliverFresh,
8
8
  parseSectionsBudget
9
- } from "./chunk-OZHJ3FLR.js";
9
+ } from "./chunk-47YKYDOF.js";
10
10
  import {
11
11
  fetchRead
12
- } from "./chunk-ROAK2DOX.js";
13
- import {
14
- findDelivered,
15
- findDeliveredByUrl,
16
- resolveResourceRef
17
- } from "./chunk-6UY2UQMY.js";
18
- import {
19
- findSearchForResource
20
- } from "./chunk-4NTZETIL.js";
12
+ } from "./chunk-WMFRCSNC.js";
21
13
  import {
22
14
  buildSiwxHeader,
23
15
  createPublicClient,
@@ -26,15 +18,7 @@ import {
26
18
  http,
27
19
  x402HTTPClient,
28
20
  x402Version
29
- } from "./chunk-6BGYHARE.js";
30
- import {
31
- USDC_ADDRESS
32
- } from "./chunk-MJZZTKCC.js";
33
- import {
34
- describeWallet,
35
- resolveSpendAuthorizer,
36
- resolveWalletProvider
37
- } from "./chunk-CNUXRXI2.js";
21
+ } from "./chunk-OWVVI4VQ.js";
38
22
  import {
39
23
  encodeFunctionData,
40
24
  getAddress as getAddress2,
@@ -43,19 +27,35 @@ import {
43
27
  toBytes,
44
28
  toHex
45
29
  } from "./chunk-KZAAWQNP.js";
30
+ import {
31
+ findDelivered,
32
+ findDeliveredByUrl,
33
+ resolveResourceRef
34
+ } from "./chunk-IFPKA32J.js";
35
+ import {
36
+ findSearchForResource
37
+ } from "./chunk-BRAVLUGI.js";
38
+ import {
39
+ USDC_ADDRESS
40
+ } from "./chunk-MJZZTKCC.js";
41
+ import {
42
+ describeWallet,
43
+ resolveSpendAuthorizer,
44
+ resolveWalletProvider
45
+ } from "./chunk-JVBMPU5G.js";
46
46
  import {
47
47
  sanitizeForTerminal
48
- } from "./chunk-IB63U6BM.js";
48
+ } from "./chunk-B676GPS2.js";
49
49
  import {
50
50
  resolveContextSettings
51
- } from "./chunk-JTYIX6OD.js";
51
+ } from "./chunk-IGHSLJUF.js";
52
52
  import {
53
53
  parseUsdToAtomic,
54
54
  toMoney
55
- } from "./chunk-ALUNME53.js";
55
+ } from "./chunk-736DW4V3.js";
56
56
  import {
57
57
  CliError
58
- } from "./chunk-PZRAAAY2.js";
58
+ } from "./chunk-PAOVPSP6.js";
59
59
  import {
60
60
  getAddress
61
61
  } from "./chunk-47PP7TAG.js";
@@ -1354,4 +1354,4 @@ async function confirmSpend(ctx, deps, yes, amountAtomic, creator) {
1354
1354
  export {
1355
1355
  runBuy
1356
1356
  };
1357
- //# sourceMappingURL=chunk-MBKFZBB2.js.map
1357
+ //# sourceMappingURL=chunk-XXY77EZJ.js.map
@@ -15,27 +15,29 @@ import {
15
15
  scan,
16
16
  updatePost,
17
17
  writeModeNotices
18
- } from "./chunk-ILDVGY7K.js";
18
+ } from "./chunk-GCGMXA2O.js";
19
19
  import {
20
20
  describeWallet,
21
21
  resolveWalletProvider
22
- } from "./chunk-CNUXRXI2.js";
22
+ } from "./chunk-JVBMPU5G.js";
23
23
  import {
24
24
  sanitizeForTerminal
25
- } from "./chunk-IB63U6BM.js";
25
+ } from "./chunk-B676GPS2.js";
26
26
  import {
27
27
  resolveContextSettings,
28
28
  resolvePublishSettings
29
- } from "./chunk-JTYIX6OD.js";
29
+ } from "./chunk-IGHSLJUF.js";
30
30
  import {
31
31
  UUID_RE,
32
- parsePublishModeFlag,
33
32
  parseUsdToAtomic,
34
33
  toMoney
35
- } from "./chunk-ALUNME53.js";
34
+ } from "./chunk-736DW4V3.js";
35
+ import {
36
+ parsePublishModeFlag
37
+ } from "./chunk-ELVDOTU7.js";
36
38
  import {
37
39
  CliError
38
- } from "./chunk-PZRAAAY2.js";
40
+ } from "./chunk-PAOVPSP6.js";
39
41
 
40
42
  // src/commands/edit.ts
41
43
  import { readFile } from "fs/promises";
@@ -609,4 +611,4 @@ function hasText(value) {
609
611
  export {
610
612
  runEdit
611
613
  };
612
- //# sourceMappingURL=chunk-CBNXUQGM.js.map
614
+ //# sourceMappingURL=chunk-YMUJZWHB.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/edit.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { resolveContextSettings, resolvePublishSettings } from '../lib/settings';\nimport { parsePublishModeFlag, type PublishMode } from '../lib/config';\nimport { UUID_RE } from '../lib/ids';\nimport { scan, type ScanContext, type ScanFinding } from '../lib/scan';\nimport { deriveProjectMarkers } from '../lib/scan-context';\nimport { sanitizeForTerminal } from '../lib/output';\nimport {\n deriveCard,\n missingSentences,\n parseAppliesToFlags,\n parseFrontmatter,\n type CardFlags,\n type ResourceCardInput,\n} from '../lib/card';\nimport {\n buildPostUpdateBody,\n getOwnPost,\n updatePost,\n type OwnPost,\n type OwnPostCard,\n type PostUpdateInput,\n type ResourceCardUpdate,\n} from '../lib/posts-api';\nimport {\n dedupeFindings,\n describeFindings,\n needsConfirmation,\n publicFinding,\n resolveWriteAuth,\n writeModeNotices,\n} from '../lib/consent';\nimport { describeWallet, resolveWalletProvider, type WalletProvider } from '../lib/wallet';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin edit <postId>`: the agent-side twin of the web answer-card panel. With\n * no change flags it READS the owner-scoped post and prints it; with change flags\n * it merge-updates via `PUT /api/posts/<id>` — omitted key = keep, `--clear` sends\n * the explicit null (or the empty container) the server's merge clears on, and an\n * array flag REPLACES the stored array wholesale (`--add-question` is the append\n * convenience that reads first and sends the merged array).\n *\n * The gates are publish's, deliberately: the same deterministic scan over the new\n * body + card text (a live secret hard-blocks in every mode) and the same\n * publish.mode consent cascade, because an edit ships content to the same public\n * page a publish does.\n *\n * Unlike publish, the wallet is touched BEFORE consent, and that is a real\n * tradeoff, not a technicality: the before→after summary the user approves can\n * only be built from the stored post, and reading it is owner-scoped. The read\n * changes nothing on the server and burns no nonce, but on first use it\n * establishes a session key, so one wallet signature and a delegation persisted to\n * `~/.tenjin/session.json` precede any approval. What that delegation can DO is\n * scoped to the run: a no-flag show mints `read`, and only an invocation that\n * intends to write asks for `read+write`. We accept the remaining cost, because\n * the alternative is asking a human to approve a diff we cannot show them.\n *\n * Exit codes: 0 success (and the read-only show), 2 usage, 3 needs_confirmation /\n * non-bypassable publish_blocked, 4 a write failure after approval.\n */\n\nexport interface EditArgs {\n /** The post uuid to edit. */\n postId: string;\n /** Card array flags: REPLACE the stored array wholesale. */\n question?: string[];\n task?: string[];\n /** Append convenience: read the stored array, add, dedupe, send the merged array. */\n addQuestion?: string[];\n addTask?: string[];\n scope?: string;\n exclusions?: string;\n appliesTo?: string[];\n asOf?: string;\n validUntil?: string;\n artifactType?: string;\n temporalMode?: string;\n provenance?: string;\n methodology?: string;\n /** Post fields. */\n title?: string;\n /** Post price, decimal USD at the edge (O1). */\n price?: string;\n /** A Markdown file whose body (frontmatter stripped) replaces the stored body. */\n body?: string;\n excerpt?: string;\n /** Card fields to clear (repeatable); see CLEAR_FIELDS. */\n clear?: string[];\n yes?: boolean;\n /** Raw `--mode` (review|auto|full-auto); validated at the edge (USAGE on a bad value). */\n mode?: string;\n}\n\nexport interface EditDeps {\n fetchImpl?: typeof fetch;\n provider?: WalletProvider;\n /** Force the plain-SIWX write path (default: session key unless TENJIN_NO_SESSION=1). */\n useSession?: boolean;\n /** Environment seam (mode, base-url, TENJIN_NO_SESSION); defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** Working directory for the `.tenjin.json` walk; defaults to process.cwd(). */\n cwd?: string;\n}\n\nexport async function runEdit(\n args: EditArgs,\n ctx: CommandContext,\n deps: EditDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const cwd = deps.cwd ?? process.cwd();\n\n if (!UUID_RE.test(args.postId)) {\n throw new CliError('USAGE', `Invalid post id: ${JSON.stringify(args.postId)}`, {\n fix: 'Pass the post uuid from `tenjin publish`’s receipt or your desk.',\n });\n }\n // A mistyped --mode must never silently land on a looser mode and apply an edit\n // unconfirmed; validate it at the edge, exactly as publish does.\n if (args.mode !== undefined) parsePublishModeFlag(args.mode, '--mode');\n // Every edge check that can fail on the FLAGS alone runs before the wallet: a\n // typo must cost nothing, not a signature and a round trip.\n rejectEmptyValues(args);\n assertAppendExclusivity(args);\n const clears = parseClears(args);\n const cardFlags = cardFlagsFrom(args);\n const priceAtomic = args.price !== undefined ? parseUsdToAtomic(args.price) : undefined;\n const bodyFile = args.body !== undefined ? await readBodyFile(args.body) : undefined;\n const wantsChange = hasChangeFlags(args);\n\n const runtime = await resolveContextSettings(ctx);\n const provider = resolveWalletProvider(\n ctx,\n deps.provider !== undefined ? { provider: deps.provider } : {},\n );\n await describeWallet(provider); // surfaces WALLET_MISSING with its own fix\n const signer = await provider.getSigner();\n // Least privilege, decided before the wallet is asked for anything: a show is a\n // READ, so it mints a read-scoped delegation rather than leaving a write-capable\n // one on disk for a command that never writes. A cached read+write session still\n // serves it, so this costs no extra signature.\n const auth = resolveWriteAuth({\n signer,\n baseUrl: runtime.baseUrl,\n dataDir: ctx.dataDir,\n scope: wantsChange ? 'read+write' : 'read',\n ...(deps.useSession !== undefined ? { useSession: deps.useSession } : {}),\n env,\n });\n const client = {\n baseUrl: runtime.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n\n const stored = await getOwnPost(args.postId, auth, client);\n if (!wantsChange) return showReceipt(stored);\n\n // The append path merges onto the STORED array (exact-string dedupe) and sends\n // the result: the server replaces arrays wholesale, so there is no append there.\n if (args.addQuestion !== undefined && args.addQuestion.length > 0) {\n cardFlags.question = appendUnique(storedList(stored, 'questionsAnswered'), args.addQuestion);\n }\n if (args.addTask !== undefined && args.addTask.length > 0) {\n cardFlags.task = appendUnique(storedList(stored, 'tasksSupported'), args.addTask);\n }\n\n // deriveCard validates the set fields against the server's bounds and reports\n // them under the same dotted `resource.<field>` keys the server would.\n const intent: PostUpdateInput = {\n ...(args.title !== undefined ? { title: args.title } : {}),\n ...(bodyFile !== undefined ? { bodyMd: bodyFile.body } : {}),\n ...(args.excerpt !== undefined ? { excerpt: args.excerpt } : {}),\n ...(priceAtomic !== undefined ? { priceAtomic } : {}),\n ...withClears(deriveCard({}, cardFlags), clears, stored.resource),\n };\n\n // Diff before deciding anything: a no-op edit is not an edit. With nothing left\n // after pruning there is nothing to confirm, nothing new to scan, and no reason\n // to burn a nonce on a write that changes nothing. Exit 0 with the current post.\n const { input, lines: changes } = diffUpdate(stored, intent);\n if (changes.length === 0) return noChangeReceipt(stored);\n // Bounds-check the pruned body here so a miss is USAGE before the consent\n // prompt; updatePost rebuilds the same body for the wire (pure, so identical).\n buildPostUpdateBody(input);\n\n const settings = await resolvePublishSettings({\n dataDir: ctx.dataDir,\n cwd,\n ...(args.mode !== undefined ? { flag: args.mode } : {}),\n env,\n });\n writeModeNotices(\n ctx.io.stderr,\n settings,\n env,\n 'each edit asks you once. Set auto to apply clean edits automatically',\n );\n\n // Gate parity with publish (#38): the source project's own git remote slugs are\n // private-by-default, so text quoting them warns. Markers derive from the\n // CONTENT's project — the body file's own directory when there is one, else the\n // working directory — never from wherever the shell happens to be.\n const markerRoot = args.body !== undefined ? dirname(resolve(cwd, args.body)) : cwd;\n const scanContext: ScanContext = { projectMarkers: await deriveProjectMarkers(markerRoot) };\n // The scan covers exactly what this edit SHIPS: the typed text behind the keys\n // that survived pruning, plus the body file only when the body itself survived.\n // Scanning the raw flags instead would block on a value that prunes away — a\n // secret already public in the stored scope, restated verbatim, would refuse an\n // unrelated title change while the same flags alone exit 0. A secret in a\n // surviving value still blocks in every mode, never cleared by --yes.\n const findings = dedupeFindings([\n ...(input.bodyMd !== undefined ? scan(bodyFile?.raw ?? '', scanContext) : []),\n ...scan(shippedTypedText(args, input), scanContext),\n ]);\n const blocking = findings.filter((f) => f.severity === 'block');\n const warns = findings.filter((f) => f.severity === 'warn');\n if (blocking.length > 0) {\n throw new CliError('PUBLISH_BLOCKED', blockMessage(blocking), {\n fix: 'Remove the secret from the new content (it is never masked away by --yes), then re-run.',\n details: { mode: settings.mode, findings: blocking.map(publicFinding) },\n });\n }\n\n const notes = editNotes(args, stored, bodyFile, clears);\n for (const line of [...notes, ...changes]) ctx.io.stderr.write(`${line}\\n`);\n\n if (needsConfirmation(settings.mode, warns.length) && args.yes !== true) {\n throw new CliError('NEEDS_CONFIRMATION', confirmMessage(warns.length, changes.length), {\n fix: 'Review the changes, then re-run with --yes.',\n details: {\n mode: settings.mode,\n postId: stored.id,\n title: sanitizeForTerminal(stored.title),\n changes,\n ...(notes.length > 0 ? { notes } : {}),\n findings: warns.map(publicFinding),\n },\n });\n }\n\n const updated = await updatePost(args.postId, input, auth, client);\n return updateReceipt(updated, changes, notes, settings.mode);\n}\n\n// ---------------------------------------------------------------------------\n// Receipts.\n// ---------------------------------------------------------------------------\n\n/** The read half of the loop: the stored post + card, owner view. */\nfunction showReceipt(post: OwnPost): CommandResult {\n const price = toMoney(post.price);\n const card = post.resource;\n const lines = [\n `${sanitizeForTerminal(post.title)} (${sanitizeForTerminal(post.status)}), ${price.usd} USD (${price.atomic} atomic)`,\n `url: ${sanitizeForTerminal(post.url)}`,\n ...(hasText(post.excerpt) ? [`excerpt: ${preview(post.excerpt)}`] : []),\n ...cardLines(card),\n eligibilityLine(card),\n ];\n return { data: post, humanLines: lines };\n}\n\n/**\n * The applied-update receipt. `changes` (and `notes`) are mirrored INTO the data\n * as well as printed, the way publish mirrors its stderr warnings into the\n * receipt: an MCP client gets a discard sink for stderr, so a summary that lives\n * only there is a summary it can never show the user. `changes: []` is the\n * unambiguous machine signal that nothing was written.\n */\nfunction updateReceipt(\n post: OwnPost,\n changes: string[],\n notes: string[],\n mode: PublishMode,\n): CommandResult {\n const card = post.resource;\n const lines = [\n `Updated ${sanitizeForTerminal(post.title)} → ${sanitizeForTerminal(post.url)}`,\n eligibilityLine(card),\n ...(post.warnings ?? []).map((w) => `warning: ${sanitizeForTerminal(w)}`),\n ];\n return {\n // `mode` is echoed because a per-call --mode (or the MCP `mode` argument) is\n // otherwise invisible in a transcript: the receipt would look identical\n // whether the caller loosened the gate for this run or not.\n data: { ...post, mode, changes, ...(notes.length > 0 ? { notes } : {}) },\n humanLines: lines,\n };\n}\n\n/** Nothing to write: the post as it stands, and an empty change list to prove it. */\nfunction noChangeReceipt(post: OwnPost): CommandResult {\n return {\n data: { ...post, changes: [] },\n humanLines: [\n `No changes: every value given already matches ${sanitizeForTerminal(post.title)}. Nothing was written.`,\n ],\n };\n}\n\n/** The card fields that are set, one per line; nothing for a post with no card. */\nfunction cardLines(card: OwnPostCard | undefined): string[] {\n if (card === undefined) return [];\n const lines: string[] = [];\n const list = (label: string, values: string[] | null | undefined): void => {\n if (values !== undefined && values !== null && values.length > 0) {\n lines.push(\n `${label} (${values.length}): ${values.map((v) => sanitizeForTerminal(v)).join(' | ')}`,\n );\n }\n };\n list('questionsAnswered', card.questionsAnswered);\n list('tasksSupported', card.tasksSupported);\n for (const [label, value] of [\n ['scope', card.scope],\n ['exclusions', card.exclusions],\n ['artifactType', card.artifactType],\n ['temporalMode', card.temporalMode],\n ['asOf', card.asOf],\n ['validUntil', card.validUntil],\n ['provenance', card.provenanceSummary],\n ['methodology', card.methodologySummary],\n ['supersedesPostId', card.supersedesPostId],\n ] as const) {\n if (hasText(value)) lines.push(`${label}: ${preview(value)}`);\n }\n if (card.appliesTo !== undefined && card.appliesTo !== null) {\n for (const [key, values] of Object.entries(card.appliesTo)) {\n lines.push(\n `appliesTo ${sanitizeForTerminal(key)}: ${values.map((v) => sanitizeForTerminal(v)).join(', ')}`,\n );\n }\n }\n return lines;\n}\n\nfunction eligibilityLine(card: OwnPostCard | undefined): string {\n if (card === undefined) return 'No answer card (browse-only document).';\n const missing = missingSentences(card.cacheEligibleMissing).map(sanitizeForTerminal);\n if (card.cacheEligible) return 'Answer card is search-eligible.';\n return missing.length > 0\n ? `Answer card not search-eligible yet: ${missing.join(' ')}`\n : 'Answer card is not search-eligible.';\n}\n\n// ---------------------------------------------------------------------------\n// The before→after summary.\n// ---------------------------------------------------------------------------\n\n/**\n * Diff what the flags ASK for against what is stored, and return both the terse\n * summary and an input pruned to the fields that actually move.\n *\n * Pruning is not cosmetic. A card key that rides along unchanged still counts as a\n * card write server-side, which re-runs the embedding for a card nobody edited;\n * and on a post with NO card, a lone `scope: null` mints an all-default card row,\n * turning a browse-only document into a card-bearing one. Comparing first and\n * sending only the difference is what keeps `edit` idempotent.\n */\nfunction diffUpdate(\n stored: OwnPost,\n intent: PostUpdateInput,\n): { input: PostUpdateInput; lines: string[] } {\n const lines: string[] = [];\n const input: PostUpdateInput = {};\n\n // Both sides trimmed, because the server trims these before storing them: an\n // untrimmed compare would call \" x\" a change from \"x\" forever.\n const title = intent.title?.trim();\n if (title !== undefined && title !== stored.title) {\n input.title = title;\n lines.push(`title: ${preview(stored.title)} → ${preview(title)}`);\n }\n if (intent.priceAtomic !== undefined && intent.priceAtomic !== stored.price) {\n const before = toMoney(stored.price);\n const after = toMoney(intent.priceAtomic);\n input.priceAtomic = intent.priceAtomic;\n lines.push(\n `price: ${before.usd} USD (${before.atomic} atomic) → ${after.usd} USD (${after.atomic} atomic)`,\n );\n }\n if (intent.bodyMd !== undefined && intent.bodyMd !== stored.bodyMd) {\n input.bodyMd = intent.bodyMd;\n lines.push(`body: ${(stored.bodyMd ?? '').length} → ${intent.bodyMd.length} characters`);\n }\n const excerpt = intent.excerpt?.trim();\n if (excerpt !== undefined && excerpt !== (stored.excerpt ?? '')) {\n input.excerpt = excerpt;\n lines.push(`excerpt: ${preview(stored.excerpt)} → ${preview(excerpt)}`);\n }\n\n const card = diffCard(stored.resource, intent.resource);\n lines.push(...card.lines);\n if (card.card !== undefined) input.resource = card.card;\n\n // Empty means EMPTY: the caller reads no lines as \"this edit is a no-op\" and\n // skips the write, so a sentinel line here would report a change that isn't one.\n return { input, lines };\n}\n\n/**\n * How each card key is diffed. The Record over `keyof ResourceCardUpdate` is the\n * point: adding a field to the card type without saying how it diffs is a compile\n * error here, not a field that silently never reaches the wire. `none` marks a\n * field no flag and no clear can set today, so it can never appear in `next`;\n * giving one a flag means moving it to a real pass.\n */\ntype CardPass = 'list' | 'iso' | 'scalar' | 'map' | 'none';\nconst CARD_PASS = {\n questionsAnswered: 'list',\n tasksSupported: 'list',\n asOf: 'iso',\n validUntil: 'iso',\n scope: 'scalar',\n exclusions: 'scalar',\n artifactType: 'scalar',\n temporalMode: 'scalar',\n provenanceSummary: 'scalar',\n methodologySummary: 'scalar',\n supersedesPostId: 'scalar',\n appliesTo: 'map',\n mediaType: 'none',\n maintenanceCadence: 'none',\n reproductionMinutes: 'none',\n estimatedPaidInputCost: 'none',\n} as const satisfies Record<keyof ResourceCardUpdate, CardPass>;\n\n/** The card keys assigned to one pass, as a union of literal keys. */\ntype KeysIn<P extends CardPass> = {\n [K in keyof typeof CARD_PASS]: (typeof CARD_PASS)[K] extends P ? K : never;\n}[keyof typeof CARD_PASS];\n\nfunction keysIn<P extends CardPass>(pass: P): KeysIn<P>[] {\n return Object.entries(CARD_PASS)\n .filter(([, value]) => value === pass)\n .map(([key]) => key) as KeysIn<P>[];\n}\n\n/** The two card keys whose flag name differs from the field name. */\nconst CARD_LABEL: Partial<Record<keyof ResourceCardUpdate, string>> = {\n provenanceSummary: 'provenance',\n methodologySummary: 'methodology',\n};\nfunction cardLabel(key: keyof ResourceCardUpdate): string {\n return CARD_LABEL[key] ?? key;\n}\n\n/**\n * The card half of the diff. Every comparison treats an ABSENT stored value as\n * already-cleared, which is what makes clearing a field on a cardless post the\n * no-op it should be rather than a card-creating write.\n */\nfunction diffCard(\n stored: OwnPostCard | undefined,\n next: ResourceCardUpdate | undefined,\n): { card?: ResourceCardUpdate; lines: string[] } {\n const lines: string[] = [];\n const card: Record<string, unknown> = {};\n const keep = (key: keyof ResourceCardUpdate, value: unknown, line: string): void => {\n card[key] = value;\n lines.push(line);\n };\n if (next === undefined) return { lines };\n\n // Lists replace wholesale, so order counts; an absent stored list reads as empty.\n for (const key of keysIn('list')) {\n const after = next[key];\n if (after === undefined) continue;\n const old = stored?.[key] ?? [];\n if (sameList(old, after)) continue;\n const added = after.filter((v) => !old.includes(v));\n const detail =\n after.length === 0 ? ' (cleared)' : added.length > 0 ? ` (new: ${previewList(added)})` : '';\n keep(key, after, `${key}: ${old.length} → ${after.length}${detail}`);\n }\n\n // The timestamps compare as INSTANTS and are sent canonicalized. The server\n // echoes a timestamptz through toISOString(), while a flag carries whatever the\n // user typed, so \"2026-07-01T00:00:00Z\" and \"2026-07-01T00:00:00.000Z\" are the\n // same moment spelled two ways — comparing the spellings would re-write the\n // field on every single run.\n for (const key of keysIn('iso')) {\n const after = next[key];\n if (after === undefined) continue;\n const from = isoInstant(stored?.[key]);\n const to = isoInstant(after);\n if (from === to) continue;\n keep(key, to, `${key}: ${preview(from)} → ${to === null ? '(cleared)' : preview(to)}`);\n }\n\n for (const key of keysIn('scalar')) {\n const after = next[key];\n if (after === undefined) continue;\n const from = stored?.[key] ?? null;\n if (from === after) continue;\n keep(\n key,\n after,\n `${cardLabel(key)}: ${preview(from)} → ${after === null ? '(cleared)' : preview(after)}`,\n );\n }\n\n // appliesTo is one value, not a key count: a same-size swap (products=Base →\n // products=Vercel) has identical counts on both sides, so a count compare would\n // call a real change a no-op and a count RENDER would print it as one.\n for (const key of keysIn('map')) {\n const after = next[key];\n if (after === undefined) continue;\n const before = stored?.[key] ?? {};\n if (sameAppliesTo(before, after)) continue;\n keep(key, after, `${key}: ${appliesToPreview(before)} → ${appliesToPreview(after)}`);\n }\n\n return { ...(Object.keys(card).length > 0 ? { card: card as ResourceCardUpdate } : {}), lines };\n}\n\n/**\n * A timestamp as its canonical instant, so two spellings of one moment compare\n * equal. An unparseable value (never from a flag — validateIso ran — but possible\n * from a future server format) passes through rather than being silently dropped.\n */\nfunction isoInstant(value: string | null | undefined): string | null {\n if (value === undefined || value === null) return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? new Date(ms).toISOString() : value;\n}\n\n/** Map equality: keys order-insensitive, each key's values order-sensitive. */\nfunction sameAppliesTo(a: Record<string, string[]>, b: Record<string, string[]>): boolean {\n const aKeys = Object.keys(a).sort();\n const bKeys = Object.keys(b).sort();\n if (!sameList(aKeys, bKeys)) return false;\n return aKeys.every((key) => sameList(a[key] ?? [], b[key] ?? []));\n}\n\n/** The advisory notes a --body edit needs, in the order a human reads them. */\nfunction editNotes(\n args: EditArgs,\n stored: OwnPost,\n bodyFile: BodyFile | undefined,\n clears: ClearField[],\n): string[] {\n if (bodyFile === undefined) return [];\n const notes: string[] = [];\n if (bodyFile.hadFrontmatter) {\n notes.push(\n 'note: frontmatter in the body file was ignored; metadata changes only through flags.',\n );\n }\n if (args.excerpt === undefined) {\n notes.push(\n `note: the excerpt stays as-is (${preview(stored.excerpt)}) and remains lexically indexed; the server does not re-derive it. Pass --excerpt to change it.`,\n );\n }\n // Only when asOf really is staying put: a run that clears it is already saying\n // so in the summary, and both lines together would contradict each other.\n const asOfMoves = args.asOf !== undefined || clears.includes('asOf');\n if (stored.resource?.temporalMode === 'snapshot' && !asOfMoves) {\n notes.push(\n `note: asOf is unchanged (${preview(stored.resource.asOf)}) on this snapshot card, and search freshness gating uses it. Pass --as-of to move it.`,\n );\n }\n return notes;\n}\n\n// ---------------------------------------------------------------------------\n// Flag parsing + validation.\n// ---------------------------------------------------------------------------\n\n/** The card fields `--clear` accepts, named as the flag that sets each one. */\nconst CLEAR_FIELDS = [\n 'scope',\n 'exclusions',\n 'asOf',\n 'validUntil',\n 'provenance',\n 'methodology',\n 'supersedesPostId',\n 'questionsAnswered',\n 'tasksSupported',\n 'appliesTo',\n] as const;\ntype ClearField = (typeof CLEAR_FIELDS)[number];\n\n/** clear name → the card key it targets. */\nconst CLEAR_KEY = {\n scope: 'scope',\n exclusions: 'exclusions',\n asOf: 'asOf',\n validUntil: 'validUntil',\n provenance: 'provenanceSummary',\n methodology: 'methodologySummary',\n supersedesPostId: 'supersedesPostId',\n questionsAnswered: 'questionsAnswered',\n tasksSupported: 'tasksSupported',\n appliesTo: 'appliesTo',\n} as const satisfies Record<ClearField, keyof ResourceCardUpdate>;\n\n/**\n * clear name → the value that clears its key server-side. Each value is typed as\n * the card field it lands on, so sending the wrong shape (a null where the merge\n * clears with `[]`, or an `[]` where it wants null) is a compile error, not a\n * validation_failed discovered in production.\n */\nconst CLEAR_VALUE: { [F in ClearField]: ResourceCardUpdate[(typeof CLEAR_KEY)[F]] } = {\n scope: null,\n exclusions: null,\n asOf: null,\n validUntil: null,\n provenance: null,\n methodology: null,\n supersedesPostId: null,\n questionsAnswered: [],\n tasksSupported: [],\n appliesTo: {},\n};\n\n/** clear name → the set-flags that would contradict it in the same invocation. */\nconst CLEAR_CONFLICTS: Record<ClearField, Array<keyof EditArgs>> = {\n scope: ['scope'],\n exclusions: ['exclusions'],\n asOf: ['asOf'],\n validUntil: ['validUntil'],\n provenance: ['provenance'],\n methodology: ['methodology'],\n supersedesPostId: [],\n questionsAnswered: ['question', 'addQuestion'],\n tasksSupported: ['task', 'addTask'],\n appliesTo: ['appliesTo'],\n};\n\n/** The CLI spelling of each arg key, for error messages. */\nconst FLAG_NAME: Record<string, string> = {\n question: '--question',\n task: '--task',\n addQuestion: '--add-question',\n addTask: '--add-task',\n scope: '--scope',\n exclusions: '--exclusions',\n appliesTo: '--applies-to',\n asOf: '--as-of',\n validUntil: '--valid-until',\n artifactType: '--artifact-type',\n temporalMode: '--temporal-mode',\n provenance: '--provenance',\n methodology: '--methodology',\n title: '--title',\n price: '--price',\n body: '--body',\n excerpt: '--excerpt',\n};\n\nconst CHANGE_KEYS: Array<keyof EditArgs> = [\n 'question',\n 'task',\n 'addQuestion',\n 'addTask',\n 'scope',\n 'exclusions',\n 'appliesTo',\n 'asOf',\n 'validUntil',\n 'artifactType',\n 'temporalMode',\n 'provenance',\n 'methodology',\n 'title',\n 'price',\n 'body',\n 'excerpt',\n 'clear',\n];\n\nfunction hasChangeFlags(args: EditArgs): boolean {\n return CHANGE_KEYS.some((key) => {\n const value = args[key];\n return Array.isArray(value) ? value.length > 0 : value !== undefined;\n });\n}\n\n/**\n * An explicit empty value is refused for every set-flag: `--scope \"\"` reads as\n * \"clear the scope\", but only `--clear scope` sends the null that clears it, and a\n * silently-sent empty string would set a blank field instead. One spelling per\n * intent, no ambiguity.\n */\nfunction rejectEmptyValues(args: EditArgs): void {\n for (const [key, flag] of Object.entries(FLAG_NAME)) {\n const value = args[key as keyof EditArgs];\n const empties =\n typeof value === 'string'\n ? [value]\n : Array.isArray(value)\n ? value.filter((v) => typeof v === 'string')\n : [];\n for (const v of empties) {\n if (v.trim().length === 0) {\n const clearable = (CLEAR_FIELDS as readonly string[]).includes(clearNameFor(key));\n throw new CliError('USAGE', `${flag} cannot be empty.`, {\n fix: clearable\n ? `Pass a value, or clear the field with \\`--clear ${clearNameFor(key)}\\`.`\n : 'Pass a value, or omit the flag to keep the stored one.',\n });\n }\n }\n }\n}\n\n/** The `--clear` name a set-flag arg key corresponds to (identity where they match). */\nfunction clearNameFor(key: string): string {\n if (key === 'question' || key === 'addQuestion') return 'questionsAnswered';\n if (key === 'task' || key === 'addTask') return 'tasksSupported';\n return key;\n}\n\nfunction assertAppendExclusivity(args: EditArgs): void {\n const both = (a: string[] | undefined, b: string[] | undefined): boolean =>\n a !== undefined && a.length > 0 && b !== undefined && b.length > 0;\n if (both(args.question, args.addQuestion)) {\n throw new CliError('USAGE', 'Pass either --question or --add-question, not both.', {\n fix: '--question replaces the stored questions; --add-question appends to them.',\n });\n }\n if (both(args.task, args.addTask)) {\n throw new CliError('USAGE', 'Pass either --task or --add-task, not both.', {\n fix: '--task replaces the stored tasks; --add-task appends to them.',\n });\n }\n}\n\nfunction parseClears(args: EditArgs): ClearField[] {\n const raw = args.clear ?? [];\n const out: ClearField[] = [];\n for (const name of raw) {\n if (!(CLEAR_FIELDS as readonly string[]).includes(name)) {\n throw new CliError('USAGE', `Cannot clear ${JSON.stringify(name)}.`, {\n fix: `Clearable fields: ${CLEAR_FIELDS.join(', ')}.`,\n });\n }\n const field = name as ClearField;\n for (const key of CLEAR_CONFLICTS[field]) {\n const value = args[key];\n const given = Array.isArray(value) ? value.length > 0 : value !== undefined;\n if (given) {\n throw new CliError(\n 'USAGE',\n `--clear ${field} contradicts ${FLAG_NAME[key as string] ?? String(key)}.`,\n { fix: 'Set the field or clear it, not both in the same run.' },\n );\n }\n }\n if (!out.includes(field)) out.push(field);\n }\n return out;\n}\n\nfunction cardFlagsFrom(args: EditArgs): CardFlags {\n return {\n ...(args.question !== undefined && args.question.length > 0 ? { question: args.question } : {}),\n ...(args.task !== undefined && args.task.length > 0 ? { task: args.task } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n ...(args.exclusions !== undefined ? { exclusions: args.exclusions } : {}),\n ...(args.asOf !== undefined ? { asOf: args.asOf } : {}),\n ...(args.validUntil !== undefined ? { validUntil: args.validUntil } : {}),\n ...(args.artifactType !== undefined ? { artifactType: args.artifactType } : {}),\n ...(args.temporalMode !== undefined ? { temporalMode: args.temporalMode } : {}),\n ...(args.provenance !== undefined ? { provenance: args.provenance } : {}),\n ...(args.methodology !== undefined ? { methodology: args.methodology } : {}),\n ...(args.appliesTo !== undefined && args.appliesTo.length > 0\n ? { appliesTo: parseAppliesToFlags(args.appliesTo) }\n : {}),\n };\n}\n\n/**\n * The card this edit ASKS for: the validated set fields plus the clears. Built\n * from an allowlist (deriveCard's output keys and CLEAR_KEY) and never from a\n * spread of the GET, so a server-owned key (cacheEligible, cacheEligibleMissing,\n * schemaVersion) cannot reach a strictObject body that would reject it.\n *\n * What actually protects the server's D14 invariant (no card row on a browse-only\n * post) is diffCard: it defaults an absent stored value to already-cleared, so a\n * clear on a post with no card compares equal and prunes away. Dropping the clears\n * here as well is a deliberate redundant backstop, one step earlier and local to\n * the one condition that matters, because the cost of that invariant breaking is a\n * plain document silently becoming card-bearing.\n */\nfunction withClears(\n set: ResourceCardInput | undefined,\n clears: ClearField[],\n stored: OwnPostCard | undefined,\n): { resource?: ResourceCardUpdate } {\n const applicable = stored !== undefined ? clears : [];\n if (set === undefined && applicable.length === 0) return {};\n const card: Record<string, unknown> = { ...(set ?? {}) };\n for (const name of applicable) {\n card[CLEAR_KEY[name]] = CLEAR_VALUE[name];\n }\n return Object.keys(card).length > 0 ? { resource: card as ResourceCardUpdate } : {};\n}\n\ninterface BodyFile {\n /** The whole file, frontmatter included; what the scan reads. */\n raw: string;\n /** The Markdown below the frontmatter; what becomes bodyMd. */\n body: string;\n hadFrontmatter: boolean;\n}\n\nasync function readBodyFile(file: string): Promise<BodyFile> {\n let raw: string;\n try {\n raw = await readFile(file, 'utf8');\n } catch (err) {\n throw new CliError('USAGE', `Could not read ${JSON.stringify(file)}`, {\n fix: 'Pass a path to a readable Markdown file, e.g. `tenjin edit <id> --body post.md`.',\n cause: err,\n });\n }\n const { frontmatter, body } = parseFrontmatter(raw);\n return { raw, body, hadFrontmatter: Object.keys(frontmatter).length > 0 };\n}\n\nfunction storedList(post: OwnPost, key: 'questionsAnswered' | 'tasksSupported'): string[] {\n return post.resource?.[key] ?? [];\n}\n\n/** Append, preserving order, skipping exact-string duplicates already stored. */\nfunction appendUnique(stored: string[], additions: string[]): string[] {\n const out = [...stored];\n for (const item of additions) {\n if (!out.includes(item)) out.push(item);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Scan input + message shaping (publish's, over the edit's new content).\n// ---------------------------------------------------------------------------\n\n/**\n * The text this invocation actually SHIPS, and only that. Two filters, each\n * closing a way the gate could fire on text the edit does not publish:\n *\n * - the key must have survived pruning. A flag whose value already matches the\n * stored one changes nothing, so its text is not \"new content\" at all; blocking\n * on it refuses an edit over a secret that is already public and that no flag\n * here can remove.\n * - the value must be one the user TYPED. The append path contributes its added\n * strings, never the merged array it sends, for the same reason.\n *\n * Everything that does ship is scanned, so a secret in a surviving value blocks in\n * every mode, never cleared by --yes.\n */\nfunction shippedTypedText(args: EditArgs, input: PostUpdateInput): string {\n const parts: string[] = [];\n const add = (v: string | undefined): void => {\n if (v !== undefined) parts.push(v);\n };\n if (input.title !== undefined) add(args.title);\n if (input.excerpt !== undefined) add(args.excerpt);\n\n const card = input.resource;\n if (card === undefined) return parts.join('\\n');\n if (card.scope !== undefined) add(args.scope);\n if (card.exclusions !== undefined) add(args.exclusions);\n if (card.provenanceSummary !== undefined) add(args.provenance);\n if (card.methodologySummary !== undefined) add(args.methodology);\n if (card.asOf !== undefined) add(args.asOf);\n if (card.validUntil !== undefined) add(args.validUntil);\n if (card.questionsAnswered !== undefined) {\n for (const item of args.question ?? args.addQuestion ?? []) add(item);\n }\n if (card.tasksSupported !== undefined) {\n for (const item of args.task ?? args.addTask ?? []) add(item);\n }\n if (card.appliesTo !== undefined && args.appliesTo !== undefined) {\n // The parsed values, matching what actually ships on the card.\n for (const values of Object.values(parseAppliesToFlags(args.appliesTo))) parts.push(...values);\n }\n return parts.join('\\n');\n}\n\nfunction blockMessage(blocking: ScanFinding[]): string {\n return `Edit blocked: the new content contains ${describeFindings(blocking)}.`;\n}\n\nfunction confirmMessage(warnCount: number, changeCount: number): string {\n return warnCount > 0\n ? `Edit needs confirmation: ${changeCount} change(s), ${warnCount} finding(s).`\n : `Edit needs confirmation: ${changeCount} change(s).`;\n}\n\n// ---------------------------------------------------------------------------\n// Small formatting helpers.\n// ---------------------------------------------------------------------------\n\nconst PREVIEW_MAX = 60;\n/** A whole rendered line's budget: a max-size card is 8 keys × 20 × 120 chars. */\nconst LINE_MAX = 200;\n\n/** Terminal-safe, whitespace-collapsed, and capped: the one place values are cut. */\nfunction clip(value: string, max = PREVIEW_MAX): string {\n const clean = sanitizeForTerminal(value).replace(/\\s+/g, ' ').trim();\n return clean.length > max ? `${clean.slice(0, max)}…` : clean;\n}\n\n/** A short, terminal-safe rendering of a stored or new value for the summary. */\nfunction preview(value: string | null | undefined): string {\n if (value === undefined || value === null || value.length === 0) return '(unset)';\n const clean = sanitizeForTerminal(value).replace(/\\s+/g, ' ').trim();\n if (clean.length === 0) return '(unset)';\n return clean.length > PREVIEW_MAX\n ? `${JSON.stringify(clean.slice(0, PREVIEW_MAX))}…`\n : JSON.stringify(clean);\n}\n\nfunction previewList(values: string[]): string {\n return values.map((v) => preview(v)).join(', ');\n}\n\n/**\n * `products=Base|Vercel, runtimes=node` — the VALUES, so a swap reads as a swap.\n * Every value takes the same 60-char cap the rest of the summary uses, and the\n * whole rendering is capped too: a full-size card would otherwise put ~19KB on one\n * stderr line.\n */\nfunction appliesToPreview(appliesTo: Record<string, string[]>): string {\n const entries = Object.entries(appliesTo);\n if (entries.length === 0) return '(unset)';\n const rendered = entries\n .map(([key, values]) => `${clip(key)}=${values.map((v) => clip(v)).join('|')}`)\n .join(', ');\n return clip(rendered, LINE_MAX);\n}\n\nfunction sameList(a: string[], b: string[]): boolean {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\n\nfunction hasText(value: string | null | undefined): boolean {\n return typeof value === 'string' && value.trim().length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,SAAS,eAAe;AA2GjC,eAAsB,QACpB,MACA,KACA,OAAiB,CAAC,GACM;AACxB,QAAM,MAAM,KAAK,OAAO,QAAQ;AAChC,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AAEpC,MAAI,CAAC,QAAQ,KAAK,KAAK,MAAM,GAAG;AAC9B,UAAM,IAAI,SAAS,SAAS,oBAAoB,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI;AAAA,MAC7E,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AAGA,MAAI,KAAK,SAAS,OAAW,sBAAqB,KAAK,MAAM,QAAQ;AAGrE,oBAA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B;AAEA,SAAS,YAAY,QAA0B;AAC7C,SAAO,OAAO,IAAI,CAAC,MAAM,QAAQ,CAAC,CAAC,EAAE,KAAK,IAAI;AAChD;AAQA,SAAS,iBAAiB,WAA6C;AACrE,QAAM,UAAU,OAAO,QAAQ,SAAS;AACxC,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,QAAM,WAAW,QACd,IAAI,CAAC,CAAC,KAAK,MAAM,MAAM,GAAG,KAAK,GAAG,CAAC,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,EAC7E,KAAK,IAAI;AACZ,SAAO,KAAK,UAAU,QAAQ;AAChC;AAEA,SAAS,SAAS,GAAa,GAAsB;AACnD,SAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,CAAC,GAAG,MAAM,MAAM,EAAE,CAAC,CAAC;AAC9D;AAEA,SAAS,QAAQ,OAA2C;AAC1D,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS;AAC5D;","names":[]}
1
+ {"version":3,"sources":["../src/commands/edit.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { resolveContextSettings, resolvePublishSettings } from '../lib/settings';\nimport { parsePublishModeFlag, type PublishMode } from '../lib/config';\nimport { UUID_RE } from '../lib/ids';\nimport { scan, type ScanContext, type ScanFinding } from '../lib/scan';\nimport { deriveProjectMarkers } from '../lib/scan-context';\nimport { sanitizeForTerminal } from '../lib/output';\nimport {\n deriveCard,\n missingSentences,\n parseAppliesToFlags,\n parseFrontmatter,\n type CardFlags,\n type ResourceCardInput,\n} from '../lib/card';\nimport {\n buildPostUpdateBody,\n getOwnPost,\n updatePost,\n type OwnPost,\n type OwnPostCard,\n type PostUpdateInput,\n type ResourceCardUpdate,\n} from '../lib/posts-api';\nimport {\n dedupeFindings,\n describeFindings,\n needsConfirmation,\n publicFinding,\n resolveWriteAuth,\n writeModeNotices,\n} from '../lib/consent';\nimport { describeWallet, resolveWalletProvider, type WalletProvider } from '../lib/wallet';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin edit <postId>`: the agent-side twin of the web answer-card panel. With\n * no change flags it READS the owner-scoped post and prints it; with change flags\n * it merge-updates via `PUT /api/posts/<id>` — omitted key = keep, `--clear` sends\n * the explicit null (or the empty container) the server's merge clears on, and an\n * array flag REPLACES the stored array wholesale (`--add-question` is the append\n * convenience that reads first and sends the merged array).\n *\n * The gates are publish's, deliberately: the same deterministic scan over the new\n * body + card text (a live secret hard-blocks in every mode) and the same\n * publish.mode consent cascade, because an edit ships content to the same public\n * page a publish does.\n *\n * Unlike publish, the wallet is touched BEFORE consent, and that is a real\n * tradeoff, not a technicality: the before→after summary the user approves can\n * only be built from the stored post, and reading it is owner-scoped. The read\n * changes nothing on the server and burns no nonce, but on first use it\n * establishes a session key, so one wallet signature and a delegation persisted to\n * `~/.tenjin/session.json` precede any approval. What that delegation can DO is\n * scoped to the run: a no-flag show mints `read`, and only an invocation that\n * intends to write asks for `read+write`. We accept the remaining cost, because\n * the alternative is asking a human to approve a diff we cannot show them.\n *\n * Exit codes: 0 success (and the read-only show), 2 usage, 3 needs_confirmation /\n * non-bypassable publish_blocked, 4 a write failure after approval.\n */\n\nexport interface EditArgs {\n /** The post uuid to edit. */\n postId: string;\n /** Card array flags: REPLACE the stored array wholesale. */\n question?: string[];\n task?: string[];\n /** Append convenience: read the stored array, add, dedupe, send the merged array. */\n addQuestion?: string[];\n addTask?: string[];\n scope?: string;\n exclusions?: string;\n appliesTo?: string[];\n asOf?: string;\n validUntil?: string;\n artifactType?: string;\n temporalMode?: string;\n provenance?: string;\n methodology?: string;\n /** Post fields. */\n title?: string;\n /** Post price, decimal USD at the edge (O1). */\n price?: string;\n /** A Markdown file whose body (frontmatter stripped) replaces the stored body. */\n body?: string;\n excerpt?: string;\n /** Card fields to clear (repeatable); see CLEAR_FIELDS. */\n clear?: string[];\n yes?: boolean;\n /** Raw `--mode` (review|auto|full-auto); validated at the edge (USAGE on a bad value). */\n mode?: string;\n}\n\nexport interface EditDeps {\n fetchImpl?: typeof fetch;\n provider?: WalletProvider;\n /** Force the plain-SIWX write path (default: session key unless TENJIN_NO_SESSION=1). */\n useSession?: boolean;\n /** Environment seam (mode, base-url, TENJIN_NO_SESSION); defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** Working directory for the `.tenjin.json` walk; defaults to process.cwd(). */\n cwd?: string;\n}\n\nexport async function runEdit(\n args: EditArgs,\n ctx: CommandContext,\n deps: EditDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const cwd = deps.cwd ?? process.cwd();\n\n if (!UUID_RE.test(args.postId)) {\n throw new CliError('USAGE', `Invalid post id: ${JSON.stringify(args.postId)}`, {\n fix: 'Pass the post uuid from `tenjin publish`’s receipt or your desk.',\n });\n }\n // A mistyped --mode must never silently land on a looser mode and apply an edit\n // unconfirmed; validate it at the edge, exactly as publish does.\n if (args.mode !== undefined) parsePublishModeFlag(args.mode, '--mode');\n // Every edge check that can fail on the FLAGS alone runs before the wallet: a\n // typo must cost nothing, not a signature and a round trip.\n rejectEmptyValues(args);\n assertAppendExclusivity(args);\n const clears = parseClears(args);\n const cardFlags = cardFlagsFrom(args);\n const priceAtomic = args.price !== undefined ? parseUsdToAtomic(args.price) : undefined;\n const bodyFile = args.body !== undefined ? await readBodyFile(args.body) : undefined;\n const wantsChange = hasChangeFlags(args);\n\n const runtime = await resolveContextSettings(ctx);\n const provider = resolveWalletProvider(\n ctx,\n deps.provider !== undefined ? { provider: deps.provider } : {},\n );\n await describeWallet(provider); // surfaces WALLET_MISSING with its own fix\n const signer = await provider.getSigner();\n // Least privilege, decided before the wallet is asked for anything: a show is a\n // READ, so it mints a read-scoped delegation rather than leaving a write-capable\n // one on disk for a command that never writes. A cached read+write session still\n // serves it, so this costs no extra signature.\n const auth = resolveWriteAuth({\n signer,\n baseUrl: runtime.baseUrl,\n dataDir: ctx.dataDir,\n scope: wantsChange ? 'read+write' : 'read',\n ...(deps.useSession !== undefined ? { useSession: deps.useSession } : {}),\n env,\n });\n const client = {\n baseUrl: runtime.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n\n const stored = await getOwnPost(args.postId, auth, client);\n if (!wantsChange) return showReceipt(stored);\n\n // The append path merges onto the STORED array (exact-string dedupe) and sends\n // the result: the server replaces arrays wholesale, so there is no append there.\n if (args.addQuestion !== undefined && args.addQuestion.length > 0) {\n cardFlags.question = appendUnique(storedList(stored, 'questionsAnswered'), args.addQuestion);\n }\n if (args.addTask !== undefined && args.addTask.length > 0) {\n cardFlags.task = appendUnique(storedList(stored, 'tasksSupported'), args.addTask);\n }\n\n // deriveCard validates the set fields against the server's bounds and reports\n // them under the same dotted `resource.<field>` keys the server would.\n const intent: PostUpdateInput = {\n ...(args.title !== undefined ? { title: args.title } : {}),\n ...(bodyFile !== undefined ? { bodyMd: bodyFile.body } : {}),\n ...(args.excerpt !== undefined ? { excerpt: args.excerpt } : {}),\n ...(priceAtomic !== undefined ? { priceAtomic } : {}),\n ...withClears(deriveCard({}, cardFlags), clears, stored.resource),\n };\n\n // Diff before deciding anything: a no-op edit is not an edit. With nothing left\n // after pruning there is nothing to confirm, nothing new to scan, and no reason\n // to burn a nonce on a write that changes nothing. Exit 0 with the current post.\n const { input, lines: changes } = diffUpdate(stored, intent);\n if (changes.length === 0) return noChangeReceipt(stored);\n // Bounds-check the pruned body here so a miss is USAGE before the consent\n // prompt; updatePost rebuilds the same body for the wire (pure, so identical).\n buildPostUpdateBody(input);\n\n const settings = await resolvePublishSettings({\n dataDir: ctx.dataDir,\n cwd,\n ...(args.mode !== undefined ? { flag: args.mode } : {}),\n env,\n });\n writeModeNotices(\n ctx.io.stderr,\n settings,\n env,\n 'each edit asks you once. Set auto to apply clean edits automatically',\n );\n\n // Gate parity with publish (#38): the source project's own git remote slugs are\n // private-by-default, so text quoting them warns. Markers derive from the\n // CONTENT's project — the body file's own directory when there is one, else the\n // working directory — never from wherever the shell happens to be.\n const markerRoot = args.body !== undefined ? dirname(resolve(cwd, args.body)) : cwd;\n const scanContext: ScanContext = { projectMarkers: await deriveProjectMarkers(markerRoot) };\n // The scan covers exactly what this edit SHIPS: the typed text behind the keys\n // that survived pruning, plus the body file only when the body itself survived.\n // Scanning the raw flags instead would block on a value that prunes away — a\n // secret already public in the stored scope, restated verbatim, would refuse an\n // unrelated title change while the same flags alone exit 0. A secret in a\n // surviving value still blocks in every mode, never cleared by --yes.\n const findings = dedupeFindings([\n ...(input.bodyMd !== undefined ? scan(bodyFile?.raw ?? '', scanContext) : []),\n ...scan(shippedTypedText(args, input), scanContext),\n ]);\n const blocking = findings.filter((f) => f.severity === 'block');\n const warns = findings.filter((f) => f.severity === 'warn');\n if (blocking.length > 0) {\n throw new CliError('PUBLISH_BLOCKED', blockMessage(blocking), {\n fix: 'Remove the secret from the new content (it is never masked away by --yes), then re-run.',\n details: { mode: settings.mode, findings: blocking.map(publicFinding) },\n });\n }\n\n const notes = editNotes(args, stored, bodyFile, clears);\n for (const line of [...notes, ...changes]) ctx.io.stderr.write(`${line}\\n`);\n\n if (needsConfirmation(settings.mode, warns.length) && args.yes !== true) {\n throw new CliError('NEEDS_CONFIRMATION', confirmMessage(warns.length, changes.length), {\n fix: 'Review the changes, then re-run with --yes.',\n details: {\n mode: settings.mode,\n postId: stored.id,\n title: sanitizeForTerminal(stored.title),\n changes,\n ...(notes.length > 0 ? { notes } : {}),\n findings: warns.map(publicFinding),\n },\n });\n }\n\n const updated = await updatePost(args.postId, input, auth, client);\n return updateReceipt(updated, changes, notes, settings.mode);\n}\n\n// ---------------------------------------------------------------------------\n// Receipts.\n// ---------------------------------------------------------------------------\n\n/** The read half of the loop: the stored post + card, owner view. */\nfunction showReceipt(post: OwnPost): CommandResult {\n const price = toMoney(post.price);\n const card = post.resource;\n const lines = [\n `${sanitizeForTerminal(post.title)} (${sanitizeForTerminal(post.status)}), ${price.usd} USD (${price.atomic} atomic)`,\n `url: ${sanitizeForTerminal(post.url)}`,\n ...(hasText(post.excerpt) ? [`excerpt: ${preview(post.excerpt)}`] : []),\n ...cardLines(card),\n eligibilityLine(card),\n ];\n return { data: post, humanLines: lines };\n}\n\n/**\n * The applied-update receipt. `changes` (and `notes`) are mirrored INTO the data\n * as well as printed, the way publish mirrors its stderr warnings into the\n * receipt: an MCP client gets a discard sink for stderr, so a summary that lives\n * only there is a summary it can never show the user. `changes: []` is the\n * unambiguous machine signal that nothing was written.\n */\nfunction updateReceipt(\n post: OwnPost,\n changes: string[],\n notes: string[],\n mode: PublishMode,\n): CommandResult {\n const card = post.resource;\n const lines = [\n `Updated ${sanitizeForTerminal(post.title)} → ${sanitizeForTerminal(post.url)}`,\n eligibilityLine(card),\n ...(post.warnings ?? []).map((w) => `warning: ${sanitizeForTerminal(w)}`),\n ];\n return {\n // `mode` is echoed because a per-call --mode (or the MCP `mode` argument) is\n // otherwise invisible in a transcript: the receipt would look identical\n // whether the caller loosened the gate for this run or not.\n data: { ...post, mode, changes, ...(notes.length > 0 ? { notes } : {}) },\n humanLines: lines,\n };\n}\n\n/** Nothing to write: the post as it stands, and an empty change list to prove it. */\nfunction noChangeReceipt(post: OwnPost): CommandResult {\n return {\n data: { ...post, changes: [] },\n humanLines: [\n `No changes: every value given already matches ${sanitizeForTerminal(post.title)}. Nothing was written.`,\n ],\n };\n}\n\n/** The card fields that are set, one per line; nothing for a post with no card. */\nfunction cardLines(card: OwnPostCard | undefined): string[] {\n if (card === undefined) return [];\n const lines: string[] = [];\n const list = (label: string, values: string[] | null | undefined): void => {\n if (values !== undefined && values !== null && values.length > 0) {\n lines.push(\n `${label} (${values.length}): ${values.map((v) => sanitizeForTerminal(v)).join(' | ')}`,\n );\n }\n };\n list('questionsAnswered', card.questionsAnswered);\n list('tasksSupported', card.tasksSupported);\n for (const [label, value] of [\n ['scope', card.scope],\n ['exclusions', card.exclusions],\n ['artifactType', card.artifactType],\n ['temporalMode', card.temporalMode],\n ['asOf', card.asOf],\n ['validUntil', card.validUntil],\n ['provenance', card.provenanceSummary],\n ['methodology', card.methodologySummary],\n ['supersedesPostId', card.supersedesPostId],\n ] as const) {\n if (hasText(value)) lines.push(`${label}: ${preview(value)}`);\n }\n if (card.appliesTo !== undefined && card.appliesTo !== null) {\n for (const [key, values] of Object.entries(card.appliesTo)) {\n lines.push(\n `appliesTo ${sanitizeForTerminal(key)}: ${values.map((v) => sanitizeForTerminal(v)).join(', ')}`,\n );\n }\n }\n return lines;\n}\n\nfunction eligibilityLine(card: OwnPostCard | undefined): string {\n if (card === undefined) return 'No answer card (browse-only document).';\n const missing = missingSentences(card.cacheEligibleMissing).map(sanitizeForTerminal);\n if (card.cacheEligible) return 'Answer card is search-eligible.';\n return missing.length > 0\n ? `Answer card not search-eligible yet: ${missing.join(' ')}`\n : 'Answer card is not search-eligible.';\n}\n\n// ---------------------------------------------------------------------------\n// The before→after summary.\n// ---------------------------------------------------------------------------\n\n/**\n * Diff what the flags ASK for against what is stored, and return both the terse\n * summary and an input pruned to the fields that actually move.\n *\n * Pruning is not cosmetic. A card key that rides along unchanged still counts as a\n * card write server-side, which re-runs the embedding for a card nobody edited;\n * and on a post with NO card, a lone `scope: null` mints an all-default card row,\n * turning a browse-only document into a card-bearing one. Comparing first and\n * sending only the difference is what keeps `edit` idempotent.\n */\nfunction diffUpdate(\n stored: OwnPost,\n intent: PostUpdateInput,\n): { input: PostUpdateInput; lines: string[] } {\n const lines: string[] = [];\n const input: PostUpdateInput = {};\n\n // Both sides trimmed, because the server trims these before storing them: an\n // untrimmed compare would call \" x\" a change from \"x\" forever.\n const title = intent.title?.trim();\n if (title !== undefined && title !== stored.title) {\n input.title = title;\n lines.push(`title: ${preview(stored.title)} → ${preview(title)}`);\n }\n if (intent.priceAtomic !== undefined && intent.priceAtomic !== stored.price) {\n const before = toMoney(stored.price);\n const after = toMoney(intent.priceAtomic);\n input.priceAtomic = intent.priceAtomic;\n lines.push(\n `price: ${before.usd} USD (${before.atomic} atomic) → ${after.usd} USD (${after.atomic} atomic)`,\n );\n }\n if (intent.bodyMd !== undefined && intent.bodyMd !== stored.bodyMd) {\n input.bodyMd = intent.bodyMd;\n lines.push(`body: ${(stored.bodyMd ?? '').length} → ${intent.bodyMd.length} characters`);\n }\n const excerpt = intent.excerpt?.trim();\n if (excerpt !== undefined && excerpt !== (stored.excerpt ?? '')) {\n input.excerpt = excerpt;\n lines.push(`excerpt: ${preview(stored.excerpt)} → ${preview(excerpt)}`);\n }\n\n const card = diffCard(stored.resource, intent.resource);\n lines.push(...card.lines);\n if (card.card !== undefined) input.resource = card.card;\n\n // Empty means EMPTY: the caller reads no lines as \"this edit is a no-op\" and\n // skips the write, so a sentinel line here would report a change that isn't one.\n return { input, lines };\n}\n\n/**\n * How each card key is diffed. The Record over `keyof ResourceCardUpdate` is the\n * point: adding a field to the card type without saying how it diffs is a compile\n * error here, not a field that silently never reaches the wire. `none` marks a\n * field no flag and no clear can set today, so it can never appear in `next`;\n * giving one a flag means moving it to a real pass.\n */\ntype CardPass = 'list' | 'iso' | 'scalar' | 'map' | 'none';\nconst CARD_PASS = {\n questionsAnswered: 'list',\n tasksSupported: 'list',\n asOf: 'iso',\n validUntil: 'iso',\n scope: 'scalar',\n exclusions: 'scalar',\n artifactType: 'scalar',\n temporalMode: 'scalar',\n provenanceSummary: 'scalar',\n methodologySummary: 'scalar',\n supersedesPostId: 'scalar',\n appliesTo: 'map',\n mediaType: 'none',\n maintenanceCadence: 'none',\n reproductionMinutes: 'none',\n estimatedPaidInputCost: 'none',\n} as const satisfies Record<keyof ResourceCardUpdate, CardPass>;\n\n/** The card keys assigned to one pass, as a union of literal keys. */\ntype KeysIn<P extends CardPass> = {\n [K in keyof typeof CARD_PASS]: (typeof CARD_PASS)[K] extends P ? K : never;\n}[keyof typeof CARD_PASS];\n\nfunction keysIn<P extends CardPass>(pass: P): KeysIn<P>[] {\n return Object.entries(CARD_PASS)\n .filter(([, value]) => value === pass)\n .map(([key]) => key) as KeysIn<P>[];\n}\n\n/** The two card keys whose flag name differs from the field name. */\nconst CARD_LABEL: Partial<Record<keyof ResourceCardUpdate, string>> = {\n provenanceSummary: 'provenance',\n methodologySummary: 'methodology',\n};\nfunction cardLabel(key: keyof ResourceCardUpdate): string {\n return CARD_LABEL[key] ?? key;\n}\n\n/**\n * The card half of the diff. Every comparison treats an ABSENT stored value as\n * already-cleared, which is what makes clearing a field on a cardless post the\n * no-op it should be rather than a card-creating write.\n */\nfunction diffCard(\n stored: OwnPostCard | undefined,\n next: ResourceCardUpdate | undefined,\n): { card?: ResourceCardUpdate; lines: string[] } {\n const lines: string[] = [];\n const card: Record<string, unknown> = {};\n const keep = (key: keyof ResourceCardUpdate, value: unknown, line: string): void => {\n card[key] = value;\n lines.push(line);\n };\n if (next === undefined) return { lines };\n\n // Lists replace wholesale, so order counts; an absent stored list reads as empty.\n for (const key of keysIn('list')) {\n const after = next[key];\n if (after === undefined) continue;\n const old = stored?.[key] ?? [];\n if (sameList(old, after)) continue;\n const added = after.filter((v) => !old.includes(v));\n const detail =\n after.length === 0 ? ' (cleared)' : added.length > 0 ? ` (new: ${previewList(added)})` : '';\n keep(key, after, `${key}: ${old.length} → ${after.length}${detail}`);\n }\n\n // The timestamps compare as INSTANTS and are sent canonicalized. The server\n // echoes a timestamptz through toISOString(), while a flag carries whatever the\n // user typed, so \"2026-07-01T00:00:00Z\" and \"2026-07-01T00:00:00.000Z\" are the\n // same moment spelled two ways — comparing the spellings would re-write the\n // field on every single run.\n for (const key of keysIn('iso')) {\n const after = next[key];\n if (after === undefined) continue;\n const from = isoInstant(stored?.[key]);\n const to = isoInstant(after);\n if (from === to) continue;\n keep(key, to, `${key}: ${preview(from)} → ${to === null ? '(cleared)' : preview(to)}`);\n }\n\n for (const key of keysIn('scalar')) {\n const after = next[key];\n if (after === undefined) continue;\n const from = stored?.[key] ?? null;\n if (from === after) continue;\n keep(\n key,\n after,\n `${cardLabel(key)}: ${preview(from)} → ${after === null ? '(cleared)' : preview(after)}`,\n );\n }\n\n // appliesTo is one value, not a key count: a same-size swap (products=Base →\n // products=Vercel) has identical counts on both sides, so a count compare would\n // call a real change a no-op and a count RENDER would print it as one.\n for (const key of keysIn('map')) {\n const after = next[key];\n if (after === undefined) continue;\n const before = stored?.[key] ?? {};\n if (sameAppliesTo(before, after)) continue;\n keep(key, after, `${key}: ${appliesToPreview(before)} → ${appliesToPreview(after)}`);\n }\n\n return { ...(Object.keys(card).length > 0 ? { card: card as ResourceCardUpdate } : {}), lines };\n}\n\n/**\n * A timestamp as its canonical instant, so two spellings of one moment compare\n * equal. An unparseable value (never from a flag — validateIso ran — but possible\n * from a future server format) passes through rather than being silently dropped.\n */\nfunction isoInstant(value: string | null | undefined): string | null {\n if (value === undefined || value === null) return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? new Date(ms).toISOString() : value;\n}\n\n/** Map equality: keys order-insensitive, each key's values order-sensitive. */\nfunction sameAppliesTo(a: Record<string, string[]>, b: Record<string, string[]>): boolean {\n const aKeys = Object.keys(a).sort();\n const bKeys = Object.keys(b).sort();\n if (!sameList(aKeys, bKeys)) return false;\n return aKeys.every((key) => sameList(a[key] ?? [], b[key] ?? []));\n}\n\n/** The advisory notes a --body edit needs, in the order a human reads them. */\nfunction editNotes(\n args: EditArgs,\n stored: OwnPost,\n bodyFile: BodyFile | undefined,\n clears: ClearField[],\n): string[] {\n if (bodyFile === undefined) return [];\n const notes: string[] = [];\n if (bodyFile.hadFrontmatter) {\n notes.push(\n 'note: frontmatter in the body file was ignored; metadata changes only through flags.',\n );\n }\n if (args.excerpt === undefined) {\n notes.push(\n `note: the excerpt stays as-is (${preview(stored.excerpt)}) and remains lexically indexed; the server does not re-derive it. Pass --excerpt to change it.`,\n );\n }\n // Only when asOf really is staying put: a run that clears it is already saying\n // so in the summary, and both lines together would contradict each other.\n const asOfMoves = args.asOf !== undefined || clears.includes('asOf');\n if (stored.resource?.temporalMode === 'snapshot' && !asOfMoves) {\n notes.push(\n `note: asOf is unchanged (${preview(stored.resource.asOf)}) on this snapshot card, and search freshness gating uses it. Pass --as-of to move it.`,\n );\n }\n return notes;\n}\n\n// ---------------------------------------------------------------------------\n// Flag parsing + validation.\n// ---------------------------------------------------------------------------\n\n/** The card fields `--clear` accepts, named as the flag that sets each one. */\nconst CLEAR_FIELDS = [\n 'scope',\n 'exclusions',\n 'asOf',\n 'validUntil',\n 'provenance',\n 'methodology',\n 'supersedesPostId',\n 'questionsAnswered',\n 'tasksSupported',\n 'appliesTo',\n] as const;\ntype ClearField = (typeof CLEAR_FIELDS)[number];\n\n/** clear name → the card key it targets. */\nconst CLEAR_KEY = {\n scope: 'scope',\n exclusions: 'exclusions',\n asOf: 'asOf',\n validUntil: 'validUntil',\n provenance: 'provenanceSummary',\n methodology: 'methodologySummary',\n supersedesPostId: 'supersedesPostId',\n questionsAnswered: 'questionsAnswered',\n tasksSupported: 'tasksSupported',\n appliesTo: 'appliesTo',\n} as const satisfies Record<ClearField, keyof ResourceCardUpdate>;\n\n/**\n * clear name → the value that clears its key server-side. Each value is typed as\n * the card field it lands on, so sending the wrong shape (a null where the merge\n * clears with `[]`, or an `[]` where it wants null) is a compile error, not a\n * validation_failed discovered in production.\n */\nconst CLEAR_VALUE: { [F in ClearField]: ResourceCardUpdate[(typeof CLEAR_KEY)[F]] } = {\n scope: null,\n exclusions: null,\n asOf: null,\n validUntil: null,\n provenance: null,\n methodology: null,\n supersedesPostId: null,\n questionsAnswered: [],\n tasksSupported: [],\n appliesTo: {},\n};\n\n/** clear name → the set-flags that would contradict it in the same invocation. */\nconst CLEAR_CONFLICTS: Record<ClearField, Array<keyof EditArgs>> = {\n scope: ['scope'],\n exclusions: ['exclusions'],\n asOf: ['asOf'],\n validUntil: ['validUntil'],\n provenance: ['provenance'],\n methodology: ['methodology'],\n supersedesPostId: [],\n questionsAnswered: ['question', 'addQuestion'],\n tasksSupported: ['task', 'addTask'],\n appliesTo: ['appliesTo'],\n};\n\n/** The CLI spelling of each arg key, for error messages. */\nconst FLAG_NAME: Record<string, string> = {\n question: '--question',\n task: '--task',\n addQuestion: '--add-question',\n addTask: '--add-task',\n scope: '--scope',\n exclusions: '--exclusions',\n appliesTo: '--applies-to',\n asOf: '--as-of',\n validUntil: '--valid-until',\n artifactType: '--artifact-type',\n temporalMode: '--temporal-mode',\n provenance: '--provenance',\n methodology: '--methodology',\n title: '--title',\n price: '--price',\n body: '--body',\n excerpt: '--excerpt',\n};\n\nconst CHANGE_KEYS: Array<keyof EditArgs> = [\n 'question',\n 'task',\n 'addQuestion',\n 'addTask',\n 'scope',\n 'exclusions',\n 'appliesTo',\n 'asOf',\n 'validUntil',\n 'artifactType',\n 'temporalMode',\n 'provenance',\n 'methodology',\n 'title',\n 'price',\n 'body',\n 'excerpt',\n 'clear',\n];\n\nfunction hasChangeFlags(args: EditArgs): boolean {\n return CHANGE_KEYS.some((key) => {\n const value = args[key];\n return Array.isArray(value) ? value.length > 0 : value !== undefined;\n });\n}\n\n/**\n * An explicit empty value is refused for every set-flag: `--scope \"\"` reads as\n * \"clear the scope\", but only `--clear scope` sends the null that clears it, and a\n * silently-sent empty string would set a blank field instead. One spelling per\n * intent, no ambiguity.\n */\nfunction rejectEmptyValues(args: EditArgs): void {\n for (const [key, flag] of Object.entries(FLAG_NAME)) {\n const value = args[key as keyof EditArgs];\n const empties =\n typeof value === 'string'\n ? [value]\n : Array.isArray(value)\n ? value.filter((v) => typeof v === 'string')\n : [];\n for (const v of empties) {\n if (v.trim().length === 0) {\n const clearable = (CLEAR_FIELDS as readonly string[]).includes(clearNameFor(key));\n throw new CliError('USAGE', `${flag} cannot be empty.`, {\n fix: clearable\n ? `Pass a value, or clear the field with \\`--clear ${clearNameFor(key)}\\`.`\n : 'Pass a value, or omit the flag to keep the stored one.',\n });\n }\n }\n }\n}\n\n/** The `--clear` name a set-flag arg key corresponds to (identity where they match). */\nfunction clearNameFor(key: string): string {\n if (key === 'question' || key === 'addQuestion') return 'questionsAnswered';\n if (key === 'task' || key === 'addTask') return 'tasksSupported';\n return key;\n}\n\nfunction assertAppendExclusivity(args: EditArgs): void {\n const both = (a: string[] | undefined, b: string[] | undefined): boolean =>\n a !== undefined && a.length > 0 && b !== undefined && b.length > 0;\n if (both(args.question, args.addQuestion)) {\n throw new CliError('USAGE', 'Pass either --question or --add-question, not both.', {\n fix: '--question replaces the stored questions; --add-question appends to them.',\n });\n }\n if (both(args.task, args.addTask)) {\n throw new CliError('USAGE', 'Pass either --task or --add-task, not both.', {\n fix: '--task replaces the stored tasks; --add-task appends to them.',\n });\n }\n}\n\nfunction parseClears(args: EditArgs): ClearField[] {\n const raw = args.clear ?? [];\n const out: ClearField[] = [];\n for (const name of raw) {\n if (!(CLEAR_FIELDS as readonly string[]).includes(name)) {\n throw new CliError('USAGE', `Cannot clear ${JSON.stringify(name)}.`, {\n fix: `Clearable fields: ${CLEAR_FIELDS.join(', ')}.`,\n });\n }\n const field = name as ClearField;\n for (const key of CLEAR_CONFLICTS[field]) {\n const value = args[key];\n const given = Array.isArray(value) ? value.length > 0 : value !== undefined;\n if (given) {\n throw new CliError(\n 'USAGE',\n `--clear ${field} contradicts ${FLAG_NAME[key as string] ?? String(key)}.`,\n { fix: 'Set the field or clear it, not both in the same run.' },\n );\n }\n }\n if (!out.includes(field)) out.push(field);\n }\n return out;\n}\n\nfunction cardFlagsFrom(args: EditArgs): CardFlags {\n return {\n ...(args.question !== undefined && args.question.length > 0 ? { question: args.question } : {}),\n ...(args.task !== undefined && args.task.length > 0 ? { task: args.task } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n ...(args.exclusions !== undefined ? { exclusions: args.exclusions } : {}),\n ...(args.asOf !== undefined ? { asOf: args.asOf } : {}),\n ...(args.validUntil !== undefined ? { validUntil: args.validUntil } : {}),\n ...(args.artifactType !== undefined ? { artifactType: args.artifactType } : {}),\n ...(args.temporalMode !== undefined ? { temporalMode: args.temporalMode } : {}),\n ...(args.provenance !== undefined ? { provenance: args.provenance } : {}),\n ...(args.methodology !== undefined ? { methodology: args.methodology } : {}),\n ...(args.appliesTo !== undefined && args.appliesTo.length > 0\n ? { appliesTo: parseAppliesToFlags(args.appliesTo) }\n : {}),\n };\n}\n\n/**\n * The card this edit ASKS for: the validated set fields plus the clears. Built\n * from an allowlist (deriveCard's output keys and CLEAR_KEY) and never from a\n * spread of the GET, so a server-owned key (cacheEligible, cacheEligibleMissing,\n * schemaVersion) cannot reach a strictObject body that would reject it.\n *\n * What actually protects the server's D14 invariant (no card row on a browse-only\n * post) is diffCard: it defaults an absent stored value to already-cleared, so a\n * clear on a post with no card compares equal and prunes away. Dropping the clears\n * here as well is a deliberate redundant backstop, one step earlier and local to\n * the one condition that matters, because the cost of that invariant breaking is a\n * plain document silently becoming card-bearing.\n */\nfunction withClears(\n set: ResourceCardInput | undefined,\n clears: ClearField[],\n stored: OwnPostCard | undefined,\n): { resource?: ResourceCardUpdate } {\n const applicable = stored !== undefined ? clears : [];\n if (set === undefined && applicable.length === 0) return {};\n const card: Record<string, unknown> = { ...(set ?? {}) };\n for (const name of applicable) {\n card[CLEAR_KEY[name]] = CLEAR_VALUE[name];\n }\n return Object.keys(card).length > 0 ? { resource: card as ResourceCardUpdate } : {};\n}\n\ninterface BodyFile {\n /** The whole file, frontmatter included; what the scan reads. */\n raw: string;\n /** The Markdown below the frontmatter; what becomes bodyMd. */\n body: string;\n hadFrontmatter: boolean;\n}\n\nasync function readBodyFile(file: string): Promise<BodyFile> {\n let raw: string;\n try {\n raw = await readFile(file, 'utf8');\n } catch (err) {\n throw new CliError('USAGE', `Could not read ${JSON.stringify(file)}`, {\n fix: 'Pass a path to a readable Markdown file, e.g. `tenjin edit <id> --body post.md`.',\n cause: err,\n });\n }\n const { frontmatter, body } = parseFrontmatter(raw);\n return { raw, body, hadFrontmatter: Object.keys(frontmatter).length > 0 };\n}\n\nfunction storedList(post: OwnPost, key: 'questionsAnswered' | 'tasksSupported'): string[] {\n return post.resource?.[key] ?? [];\n}\n\n/** Append, preserving order, skipping exact-string duplicates already stored. */\nfunction appendUnique(stored: string[], additions: string[]): string[] {\n const out = [...stored];\n for (const item of additions) {\n if (!out.includes(item)) out.push(item);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Scan input + message shaping (publish's, over the edit's new content).\n// ---------------------------------------------------------------------------\n\n/**\n * The text this invocation actually SHIPS, and only that. Two filters, each\n * closing a way the gate could fire on text the edit does not publish:\n *\n * - the key must have survived pruning. A flag whose value already matches the\n * stored one changes nothing, so its text is not \"new content\" at all; blocking\n * on it refuses an edit over a secret that is already public and that no flag\n * here can remove.\n * - the value must be one the user TYPED. The append path contributes its added\n * strings, never the merged array it sends, for the same reason.\n *\n * Everything that does ship is scanned, so a secret in a surviving value blocks in\n * every mode, never cleared by --yes.\n */\nfunction shippedTypedText(args: EditArgs, input: PostUpdateInput): string {\n const parts: string[] = [];\n const add = (v: string | undefined): void => {\n if (v !== undefined) parts.push(v);\n };\n if (input.title !== undefined) add(args.title);\n if (input.excerpt !== undefined) add(args.excerpt);\n\n const card = input.resource;\n if (card === undefined) return parts.join('\\n');\n if (card.scope !== undefined) add(args.scope);\n if (card.exclusions !== undefined) add(args.exclusions);\n if (card.provenanceSummary !== undefined) add(args.provenance);\n if (card.methodologySummary !== undefined) add(args.methodology);\n if (card.asOf !== undefined) add(args.asOf);\n if (card.validUntil !== undefined) add(args.validUntil);\n if (card.questionsAnswered !== undefined) {\n for (const item of args.question ?? args.addQuestion ?? []) add(item);\n }\n if (card.tasksSupported !== undefined) {\n for (const item of args.task ?? args.addTask ?? []) add(item);\n }\n if (card.appliesTo !== undefined && args.appliesTo !== undefined) {\n // The parsed values, matching what actually ships on the card.\n for (const values of Object.values(parseAppliesToFlags(args.appliesTo))) parts.push(...values);\n }\n return parts.join('\\n');\n}\n\nfunction blockMessage(blocking: ScanFinding[]): string {\n return `Edit blocked: the new content contains ${describeFindings(blocking)}.`;\n}\n\nfunction confirmMessage(warnCount: number, changeCount: number): string {\n return warnCount > 0\n ? `Edit needs confirmation: ${changeCount} change(s), ${warnCount} finding(s).`\n : `Edit needs confirmation: ${changeCount} change(s).`;\n}\n\n// ---------------------------------------------------------------------------\n// Small formatting helpers.\n// ---------------------------------------------------------------------------\n\nconst PREVIEW_MAX = 60;\n/** A whole rendered line's budget: a max-size card is 8 keys × 20 × 120 chars. */\nconst LINE_MAX = 200;\n\n/** Terminal-safe, whitespace-collapsed, and capped: the one place values are cut. */\nfunction clip(value: string, max = PREVIEW_MAX): string {\n const clean = sanitizeForTerminal(value).replace(/\\s+/g, ' ').trim();\n return clean.length > max ? `${clean.slice(0, max)}…` : clean;\n}\n\n/** A short, terminal-safe rendering of a stored or new value for the summary. */\nfunction preview(value: string | null | undefined): string {\n if (value === undefined || value === null || value.length === 0) return '(unset)';\n const clean = sanitizeForTerminal(value).replace(/\\s+/g, ' ').trim();\n if (clean.length === 0) return '(unset)';\n return clean.length > PREVIEW_MAX\n ? `${JSON.stringify(clean.slice(0, PREVIEW_MAX))}…`\n : JSON.stringify(clean);\n}\n\nfunction previewList(values: string[]): string {\n return values.map((v) => preview(v)).join(', ');\n}\n\n/**\n * `products=Base|Vercel, runtimes=node` — the VALUES, so a swap reads as a swap.\n * Every value takes the same 60-char cap the rest of the summary uses, and the\n * whole rendering is capped too: a full-size card would otherwise put ~19KB on one\n * stderr line.\n */\nfunction appliesToPreview(appliesTo: Record<string, string[]>): string {\n const entries = Object.entries(appliesTo);\n if (entries.length === 0) return '(unset)';\n const rendered = entries\n .map(([key, values]) => `${clip(key)}=${values.map((v) => clip(v)).join('|')}`)\n .join(', ');\n return clip(rendered, LINE_MAX);\n}\n\nfunction sameList(a: string[], b: string[]): boolean {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\n\nfunction hasText(value: string | null | undefined): boolean {\n return typeof value === 'string' && value.trim().length > 0;\n}\n"],"mappings":";;;;;;;;;;;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