tenjin-cli 0.1.0-alpha.13 → 0.1.0-alpha.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -2
- package/dist/{buy-X4VPHFUA.js → buy-2JBYPHAI.js} +16 -14
- package/dist/{chunk-6JKD46OJ.js → chunk-3ZW7HPY5.js} +4 -4
- package/dist/chunk-4UHNXY6B.js +786 -0
- package/dist/chunk-4UHNXY6B.js.map +1 -0
- package/dist/{chunk-IFPKA32J.js → chunk-4Y53PDH6.js} +2 -2
- package/dist/{chunk-SPUORKD7.js → chunk-54AJIO3E.js} +11 -12
- package/dist/chunk-54AJIO3E.js.map +1 -0
- package/dist/{chunk-JVBMPU5G.js → chunk-7GJQ5RGA.js} +5 -3
- package/dist/{chunk-JVBMPU5G.js.map → chunk-7GJQ5RGA.js.map} +1 -1
- package/dist/{chunk-BRAVLUGI.js → chunk-7NADDA2V.js} +9 -6
- package/dist/{chunk-BRAVLUGI.js.map → chunk-7NADDA2V.js.map} +1 -1
- package/dist/{chunk-T4UWMVKV.js → chunk-ACBEHJAH.js} +4 -4
- package/dist/{chunk-XXY77EZJ.js → chunk-DAZAXFSF.js} +7 -7
- package/dist/{chunk-OE36HRWG.js → chunk-DTCXO7HS.js} +257 -405
- package/dist/chunk-DTCXO7HS.js.map +1 -0
- package/dist/{chunk-CA3JV7FX.js → chunk-ETKZWJ4B.js} +2 -2
- package/dist/{chunk-CA3JV7FX.js.map → chunk-ETKZWJ4B.js.map} +1 -1
- package/dist/{chunk-NKN4YC5C.js → chunk-FDUD3W5V.js} +2 -2
- package/dist/{chunk-L4XNT3UW.js → chunk-GEHL43VE.js} +49 -17
- package/dist/chunk-GEHL43VE.js.map +1 -0
- package/dist/chunk-IU2HVT3Y.js +313 -0
- package/dist/chunk-IU2HVT3Y.js.map +1 -0
- package/dist/{chunk-OXUJ3FXU.js → chunk-IUQZ4Z7M.js} +36 -8
- package/dist/chunk-IUQZ4Z7M.js.map +1 -0
- package/dist/{chunk-YMUJZWHB.js → chunk-IXZJ3JOO.js} +5 -5
- package/dist/{chunk-47YKYDOF.js → chunk-L6G35FU5.js} +2 -2
- package/dist/{chunk-ELVDOTU7.js → chunk-LSWP7MU2.js} +4 -4
- package/dist/chunk-LSWP7MU2.js.map +1 -0
- package/dist/{chunk-OUJDDY5L.js → chunk-MJSXP4LW.js} +30 -28
- package/dist/chunk-MJSXP4LW.js.map +1 -0
- package/dist/{chunk-WVHPGQH5.js → chunk-NAAMHWSI.js} +5 -2
- package/dist/chunk-NAAMHWSI.js.map +1 -0
- package/dist/{chunk-IKAJSA7E.js → chunk-O75FOHXS.js} +29 -11
- package/dist/chunk-O75FOHXS.js.map +1 -0
- package/dist/{chunk-WMFRCSNC.js → chunk-PCX2JQ2J.js} +3 -3
- package/dist/{chunk-IGHSLJUF.js → chunk-PKW3H26Z.js} +5 -5
- package/dist/{chunk-3NZCU6SD.js → chunk-PQZVDCCA.js} +4 -4
- package/dist/{chunk-OC3EIDCP.js → chunk-QWBUKIP2.js} +7 -1
- package/dist/chunk-QWBUKIP2.js.map +1 -0
- package/dist/{chunk-FKSAUOJU.js → chunk-UO22YNY4.js} +1 -69
- package/dist/chunk-UO22YNY4.js.map +1 -0
- package/dist/chunk-VEAERJVJ.js +43 -0
- package/dist/chunk-VEAERJVJ.js.map +1 -0
- package/dist/{chunk-GCGMXA2O.js → chunk-VRPLZERE.js} +16 -5
- package/dist/chunk-VRPLZERE.js.map +1 -0
- package/dist/{chunk-IAR25V2E.js → chunk-W4VW5XYB.js} +4 -4
- package/dist/chunk-WYLMJQVH.js +240 -0
- package/dist/chunk-WYLMJQVH.js.map +1 -0
- package/dist/{chunk-TXVC46SA.js → chunk-XVPQGCH4.js} +11 -10
- package/dist/chunk-XVPQGCH4.js.map +1 -0
- package/dist/chunk-ZOBNS7CX.js +73 -0
- package/dist/chunk-ZOBNS7CX.js.map +1 -0
- package/dist/{cli-XK5JZWU6.js → cli-U2BEUA55.js} +34 -36
- package/dist/{cli-XK5JZWU6.js.map → cli-U2BEUA55.js.map} +1 -1
- package/dist/{config-CNK7MYUR.js → config-CNUIX23Q.js} +12 -6
- package/dist/{doctor-R7N7FUX5.js → doctor-QJJXRWTO.js} +11 -7
- package/dist/{edit-QSUEG7CL.js → edit-HJ44P44P.js} +13 -11
- package/dist/{fund-JF6A76YS.js → fund-Y5IAHZ5D.js} +10 -8
- package/dist/index.js +1 -1
- package/dist/{inspect-NFNAA4LA.js → inspect-NFQ6SQQQ.js} +14 -12
- package/dist/{install-YQVM3SUW.js → install-DXX7PVUP.js} +122 -401
- package/dist/install-DXX7PVUP.js.map +1 -0
- package/dist/outcome-ANV4QIED.js +24 -0
- package/dist/{publish-O2I6IAEL.js → publish-PCBTCXCZ.js} +14 -12
- package/dist/{read-UF7QVQOU.js → read-W7QVRBVD.js} +14 -12
- package/dist/{read-UF7QVQOU.js.map → read-W7QVRBVD.js.map} +1 -1
- package/dist/{run-GDZWHNWZ.js → run-CJWPGMIQ.js} +26 -24
- package/dist/{run-GDZWHNWZ.js.map → run-CJWPGMIQ.js.map} +1 -1
- package/dist/search-JGAVKTYJ.js +25 -0
- package/dist/{send-SI254H3R.js → send-C5EOKXOU.js} +7 -6
- package/dist/{send-SI254H3R.js.map → send-C5EOKXOU.js.map} +1 -1
- package/dist/{session-GJZJEXLJ.js → session-OBCUUIFX.js} +7 -6
- package/dist/{session-GJZJEXLJ.js.map → session-OBCUUIFX.js.map} +1 -1
- package/dist/{skill-heal-BPFT22XS.js → skill-heal-D6EPLPS6.js} +3 -3
- package/dist/skill-heal-D6EPLPS6.js.map +1 -0
- package/dist/{uninstall-7ZZG6WQ5.js → uninstall-OWJNJ5LI.js} +11 -5
- package/dist/uninstall-OWJNJ5LI.js.map +1 -0
- package/dist/{update-FPSBITLB.js → update-24Y2CQTT.js} +16 -13
- package/dist/update-24Y2CQTT.js.map +1 -0
- package/dist/{wallet-TZVD2M4I.js → wallet-OFXDIIGP.js} +7 -6
- package/dist/{wallet-NS7TYWNN.js → wallet-SLRIYJ2U.js} +4 -3
- package/docs/agent-permissions.md +100 -16
- package/docs/command-reference.md +21 -11
- package/package.json +1 -1
- package/skills/tenjin-publish/SKILL.md +181 -205
- package/skills/tenjin-publish/references/maintain.md +39 -0
- package/skills/tenjin-search/SKILL.md +86 -279
- package/skills/tenjin-search/references/permissions.md +106 -0
- package/dist/chunk-ELVDOTU7.js.map +0 -1
- package/dist/chunk-FKSAUOJU.js.map +0 -1
- package/dist/chunk-GCGMXA2O.js.map +0 -1
- package/dist/chunk-IKAJSA7E.js.map +0 -1
- package/dist/chunk-L4XNT3UW.js.map +0 -1
- package/dist/chunk-OC3EIDCP.js.map +0 -1
- package/dist/chunk-OE36HRWG.js.map +0 -1
- package/dist/chunk-OUJDDY5L.js.map +0 -1
- package/dist/chunk-OXUJ3FXU.js.map +0 -1
- package/dist/chunk-SPUORKD7.js.map +0 -1
- package/dist/chunk-TXVC46SA.js.map +0 -1
- package/dist/chunk-UUARTUY2.js +0 -349
- package/dist/chunk-UUARTUY2.js.map +0 -1
- package/dist/chunk-WVHPGQH5.js.map +0 -1
- package/dist/install-YQVM3SUW.js.map +0 -1
- package/dist/outcome-IUSYFJTN.js +0 -22
- package/dist/search-JVOHEF3E.js +0 -23
- package/dist/skill-heal-BPFT22XS.js.map +0 -1
- package/dist/uninstall-7ZZG6WQ5.js.map +0 -1
- package/dist/update-FPSBITLB.js.map +0 -1
- /package/dist/{buy-X4VPHFUA.js.map → buy-2JBYPHAI.js.map} +0 -0
- /package/dist/{chunk-6JKD46OJ.js.map → chunk-3ZW7HPY5.js.map} +0 -0
- /package/dist/{chunk-IFPKA32J.js.map → chunk-4Y53PDH6.js.map} +0 -0
- /package/dist/{chunk-T4UWMVKV.js.map → chunk-ACBEHJAH.js.map} +0 -0
- /package/dist/{chunk-XXY77EZJ.js.map → chunk-DAZAXFSF.js.map} +0 -0
- /package/dist/{chunk-NKN4YC5C.js.map → chunk-FDUD3W5V.js.map} +0 -0
- /package/dist/{chunk-YMUJZWHB.js.map → chunk-IXZJ3JOO.js.map} +0 -0
- /package/dist/{chunk-47YKYDOF.js.map → chunk-L6G35FU5.js.map} +0 -0
- /package/dist/{chunk-WMFRCSNC.js.map → chunk-PCX2JQ2J.js.map} +0 -0
- /package/dist/{chunk-IGHSLJUF.js.map → chunk-PKW3H26Z.js.map} +0 -0
- /package/dist/{chunk-3NZCU6SD.js.map → chunk-PQZVDCCA.js.map} +0 -0
- /package/dist/{chunk-IAR25V2E.js.map → chunk-W4VW5XYB.js.map} +0 -0
- /package/dist/{config-CNK7MYUR.js.map → config-CNUIX23Q.js.map} +0 -0
- /package/dist/{doctor-R7N7FUX5.js.map → doctor-QJJXRWTO.js.map} +0 -0
- /package/dist/{edit-QSUEG7CL.js.map → edit-HJ44P44P.js.map} +0 -0
- /package/dist/{fund-JF6A76YS.js.map → fund-Y5IAHZ5D.js.map} +0 -0
- /package/dist/{inspect-NFNAA4LA.js.map → inspect-NFQ6SQQQ.js.map} +0 -0
- /package/dist/{outcome-IUSYFJTN.js.map → outcome-ANV4QIED.js.map} +0 -0
- /package/dist/{publish-O2I6IAEL.js.map → publish-PCBTCXCZ.js.map} +0 -0
- /package/dist/{search-JVOHEF3E.js.map → search-JGAVKTYJ.js.map} +0 -0
- /package/dist/{wallet-NS7TYWNN.js.map → wallet-OFXDIIGP.js.map} +0 -0
- /package/dist/{wallet-TZVD2M4I.js.map → wallet-SLRIYJ2U.js.map} +0 -0
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
} from "./chunk-ZQIQ55KK.js";
|
|
5
5
|
import {
|
|
6
6
|
HARNESS_TARGETS
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-QWBUKIP2.js";
|
|
8
8
|
import {
|
|
9
9
|
CliError,
|
|
10
10
|
external_exports
|
|
@@ -33,12 +33,12 @@ function parseSearchHookModeFlag(value, flagName) {
|
|
|
33
33
|
fix: 'Use "auto", "remind", or "off".'
|
|
34
34
|
});
|
|
35
35
|
}
|
|
36
|
-
var StopNagModeSchema = external_exports.enum(["on", "off"]);
|
|
36
|
+
var StopNagModeSchema = external_exports.enum(["on", "deliberate-only", "off"]);
|
|
37
37
|
function parseStopNagFlag(value, flagName) {
|
|
38
38
|
const parsed = StopNagModeSchema.safeParse(value);
|
|
39
39
|
if (parsed.success) return parsed.data;
|
|
40
40
|
throw new CliError("USAGE", `Invalid ${flagName} ${JSON.stringify(value)}`, {
|
|
41
|
-
fix: 'Use "on" or "off".'
|
|
41
|
+
fix: 'Use "on", "deliberate-only", or "off".'
|
|
42
42
|
});
|
|
43
43
|
}
|
|
44
44
|
var HooksConfigSchema = external_exports.object({
|
|
@@ -287,4 +287,4 @@ export {
|
|
|
287
287
|
resolvePublishMode,
|
|
288
288
|
resolvePublishDefaultPrice
|
|
289
289
|
};
|
|
290
|
-
//# sourceMappingURL=chunk-
|
|
290
|
+
//# sourceMappingURL=chunk-LSWP7MU2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/config.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { configPath } from './paths';\nimport { HARNESS_TARGETS } from './skill-wiring';\nimport { writeFileAtomic } from './atomic-json';\n\n/** A non-negative integer string in USDC atomic units (6-decimal base). */\nconst atomicString = z.string().regex(/^\\d+$/, 'expected an atomic USDC integer string');\n\n/** The publish consent mode (B3, D38). `full-auto` is loosening-gated, below. */\nexport const PublishModeSchema = z.enum(['review', 'auto', 'full-auto']);\nexport type PublishMode = z.infer<typeof PublishModeSchema>;\n\n/**\n * Validate a publish-mode value at a command edge (`--mode`, `--publish-mode`):\n * an unrecognized value is USAGE (exit 2), never silently dropped. `flagName` is\n * woven into the message so the failing flag is named.\n */\nexport function parsePublishModeFlag(value: string, flagName: string): PublishMode {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid ${flagName} ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * The publish block (B3): `mode` governs the confirm cascade a `publish` runs,\n * `defaultPrice` is the atomic USDC price a card is published at when no\n * per-publish price is given. Stored atomic like the spend keys.\n */\nconst PublishConfigSchema = z.object({\n mode: PublishModeSchema,\n defaultPrice: atomicString,\n});\n\n/**\n * What the harness WebSearch hook does when the agent is about to search the web\n * (see lib/hook-scripts.ts). `auto` asks Tenjin first and mentions a tested\n * answer when one exists, `remind` says the marketplace is there without sending\n * the query anywhere, `off` leaves the installed hook inert.\n */\nexport const SearchHookModeSchema = z.enum(['auto', 'remind', 'off']);\nexport type SearchHookMode = z.infer<typeof SearchHookModeSchema>;\n\n/**\n * Validate a search-hook mode at a command edge (`--search-hooks`), the same way\n * publish-mode values are validated: an unrecognized value is USAGE, never a\n * silent fallback to the default.\n */\nexport function parseSearchHookModeFlag(value: string, flagName: string): SearchHookMode {\n const parsed = SearchHookModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid ${flagName} ${JSON.stringify(value)}`, {\n fix: 'Use \"auto\", \"remind\", or \"off\".',\n });\n}\n\n/**\n * Which open loops the Stop hook may raise at the end of a turn.\n *\n * `deliberate-only` is the middle setting the two-value toggle was missing. The\n * hook has two arms, and they are not equally welcome: a deliberate `tenjin\n * search` MISS is a question the agent chose to ask, while the batched\n * ride-along web searches are a firehose in a research session. With only `on`\n * and `off`, silencing the noisy arm meant silencing both, and nothing ever\n * prompts turning them back on (tenjin-agent #162). This keeps the high-signal\n * arm and drops the batch.\n */\nexport const StopNagModeSchema = z.enum(['on', 'deliberate-only', 'off']);\nexport type StopNagMode = z.infer<typeof StopNagModeSchema>;\n\nexport function parseStopNagFlag(value: string, flagName: string): StopNagMode {\n const parsed = StopNagModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid ${flagName} ${JSON.stringify(value)}`, {\n fix: 'Use \"on\", \"deliberate-only\", or \"off\".',\n });\n}\n\n/**\n * The harness-hook block. BOTH keys are read by the installed scripts at run\n * time, which is what makes them runtime toggles rather than install-time\n * choices: `tenjin config set hooks.searchMode off` or `hooks.stopNag off`\n * silences a hook immediately, with no re-install and nothing to unwire. The\n * scripts stay registered and no-op, which is also what lets turning one back on\n * be a single `config set`.\n */\nconst HooksConfigSchema = z.object({\n searchMode: SearchHookModeSchema,\n stopNag: StopNagModeSchema,\n});\n\n/**\n * What the daily update check is allowed to do about a newer version.\n *\n * `nudge` reports it — one dim line for a human at a terminal, and an\n * `updateAvailable` field on the JSON envelope for everyone else, which is how\n * an agent learns to run `tenjin update` itself. `off` reports neither and stops\n * asking npm entirely.\n *\n * There is deliberately no mode that installs on its own. Replacing the binary\n * under a running agent has no safe moment in a CLI that starts a fresh process\n * per invocation: \"next start\" IS \"mid-session\". Reporting is the part that was\n * missing, so reporting is what this key controls.\n */\nexport const UpdateModeSchema = z.enum(['nudge', 'off']);\nexport type UpdateMode = z.infer<typeof UpdateModeSchema>;\n\nconst UpdateConfigSchema = z.object({\n mode: UpdateModeSchema,\n});\n\nexport function parseUpdateModeFlag(value: string, flagName: string): UpdateMode {\n const parsed = UpdateModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid ${flagName} ${JSON.stringify(value)}`, {\n fix: 'Use \"nudge\" or \"off\".',\n });\n}\n\n/**\n * What `install` recorded about its OWN targets. `harness` is the explicit\n * `--harness` set of the last install that passed the flag, and it exists so\n * `doctor` keeps judging a directory the user named by hand: detection cannot see a\n * harness this CLI does not probe for, and without the record such a directory is a\n * target for one run and invisible to every later check. Written by `install`, not a\n * `config set` key.\n */\nconst InstallConfigSchema = z.object({\n harness: z.array(z.enum(HARNESS_TARGETS)),\n});\n\n/**\n * The persisted config shape. Spend keys are stored atomic (accepted as decimal\n * USD at the command edge, see lib/money); `confirm` is the stored form\n * \"always\" | \"above:<atomic>\". These are client-enforced guardrails, not a\n * security boundary — any process that runs the CLI can also edit this file.\n */\nexport const ConfigSchema = z.object({\n maxAutoSpend: atomicString,\n sessionBudget: atomicString,\n confirm: z.union([z.literal('always'), z.string().regex(/^above:\\d+$/)]),\n /**\n * Hard per-send cap for `tenjin send`, NOT satisfiable by --yes or a prompt\n * (the spend-policy posture): an atomic amount caps each send, \"0\" disables\n * the verb entirely, and \"none\" = explicitly uncapped (send exists to drain\n * the wallet, but uncapped is an opt-in, never a default). The key has NO\n * usable default: absent from config.json, `tenjin send` refuses until it is\n * set (see resolveSendMaxAmount). Client-enforced like every spend key (see\n * the note above).\n */\n sendMaxAmount: z.union([z.literal('none'), atomicString]),\n allowlistCreators: z.array(z.string()),\n baseUrl: z.url(),\n rpcUrl: z.url(),\n /**\n * Evaluation-cohort opt-in (spec 09 §3): when true, search sends\n * X-Tenjin-Eval-Cohort: 1 and the server stores the generalized question for\n * 90 days. Off by default; no query text is retained server-side without it.\n */\n evalCohort: z.boolean(),\n publish: PublishConfigSchema,\n install: InstallConfigSchema,\n hooks: HooksConfigSchema,\n update: UpdateConfigSchema,\n});\nexport type Config = z.infer<typeof ConfigSchema>;\n\n/**\n * Values as they may appear in config.json — every known key optional; absent =\n * default. `.passthrough()` PRESERVES unknown keys through load + persist: without\n * it an older binary's `config set` would strip (and re-serialize away) any newer\n * block a later CLI wrote, e.g. B3's `publish.*`. Known keys are still validated;\n * unknown keys ride along untouched.\n */\nexport const RawConfigSchema = ConfigSchema.partial()\n // The publish block is itself partial + passthrough: `config set publish.mode`\n // writes only the one subkey, and a subkey a newer CLI adds (e.g. publish.*\n // beyond mode/defaultPrice) survives an older binary's set, same reason the\n // outer object passes unknown keys through.\n .extend({\n publish: PublishConfigSchema.partial().passthrough().optional(),\n install: InstallConfigSchema.partial().passthrough().optional(),\n hooks: HooksConfigSchema.partial().passthrough().optional(),\n update: UpdateConfigSchema.partial().passthrough().optional(),\n })\n .passthrough();\nexport type PartialConfig = z.infer<typeof RawConfigSchema>;\n\n/**\n * The resolved-view sentinel for an absent sendMaxAmount. Never a persistable\n * value (ConfigSchema rejects it, and `config set` has no way to produce it);\n * while the resolved value is this sentinel, `tenjin send` refuses —\n * require-set-before-first-send.\n */\nexport const SEND_MAX_UNSET = 'unset';\n\nexport const CONFIG_DEFAULTS: Config = {\n maxAutoSpend: '0',\n sessionBudget: '0',\n confirm: 'always',\n // A type placeholder only, never honored: Config requires every key (and\n // CONFIG_KEYS derives from these). resolveSendMaxAmount never reads it — an\n // absent key resolves to SEND_MAX_UNSET and `tenjin send` refuses until the\n // cap is set. '0' (send disabled) rather than 'none' (uncapped) so that if a\n // future caller ever DOES read the cap through loadConfig/fileOrDefault, the\n // leak fails closed instead of silently running uncapped.\n sendMaxAmount: '0',\n allowlistCreators: [],\n baseUrl: 'https://tenjin.blog',\n rpcUrl: 'https://mainnet.base.org',\n evalCohort: false,\n publish: { mode: 'review', defaultPrice: '100000' },\n install: { harness: [] },\n // `auto` is the default because the hook exists to be useful without being\n // asked for; the disclosure and the undo ride the install output, and `off`\n // leaves the installed script inert without touching settings.json.\n hooks: { searchMode: 'auto', stopNag: 'on' },\n update: { mode: 'nudge' },\n};\n\n/**\n * Scalar keys `config get/set/list` render one line each. The nested blocks are\n * excluded: `publish` and `hooks` are addressed by their dotted keys (see\n * PUBLISH_CONFIG_KEYS / HOOKS_CONFIG_KEYS), and `install` is a record `install`\n * writes about itself rather than a setting to hand-edit, so none is ever a bare\n * scalar.\n */\nexport type ScalarConfigKey = Exclude<keyof Config, 'publish' | 'install' | 'hooks' | 'update'>;\nconst NESTED_CONFIG_KEYS: ReadonlySet<string> = new Set(['publish', 'install', 'hooks', 'update']);\nexport const CONFIG_KEYS = (Object.keys(CONFIG_DEFAULTS) as Array<keyof Config>).filter(\n (key): key is ScalarConfigKey => !NESTED_CONFIG_KEYS.has(key),\n);\n\n/** The dotted keys `config get/set` accept for the nested publish block. */\nexport const PUBLISH_CONFIG_KEYS = ['publish.mode', 'publish.defaultPrice'] as const;\nexport type PublishConfigKey = (typeof PUBLISH_CONFIG_KEYS)[number];\n\n/** The dotted keys `config get/set` accept for the nested hooks block. */\nexport const HOOKS_CONFIG_KEYS = ['hooks.searchMode', 'hooks.stopNag'] as const;\nexport type HooksConfigKey = (typeof HOOKS_CONFIG_KEYS)[number];\n\n/** The dotted key `config get/set` accepts for the nested update block. */\nexport const UPDATE_CONFIG_KEYS = ['update.mode'] as const;\nexport type UpdateConfigKey = (typeof UPDATE_CONFIG_KEYS)[number];\n\n/**\n * Read and validate config.json WITHOUT applying defaults, so provenance can\n * distinguish \"present in file\" from \"absent\". Missing file is fine (returns\n * {}); malformed JSON or a failed schema is CONFIG_INVALID with a fix.\n */\nexport async function loadRawConfig(dir: string): Promise<PartialConfig> {\n const path = configPath(dir);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNotFound(err)) return {};\n throw new CliError('CONFIG_INVALID', `Could not read config at ${path}`, {\n fix: `Check file permissions on ${path}.`,\n cause: err,\n });\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `Config at ${path} is not valid JSON`, {\n fix: `Fix the JSON syntax in ${path}, or delete it to restore defaults.`,\n cause: err,\n });\n }\n const parsed = RawConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `Config at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it to restore defaults.`,\n details: parsed.error.issues,\n });\n }\n return parsed.data;\n}\n\n/** File values merged over defaults — the effective persisted config. The nested\n * publish block is merged per-subkey so a file that sets only publish.mode keeps\n * the default defaultPrice (a shallow spread would drop it). */\nexport async function loadConfig(dir: string): Promise<Config> {\n const raw = await loadRawConfig(dir);\n return {\n ...CONFIG_DEFAULTS,\n ...raw,\n publish: {\n mode: raw.publish?.mode ?? CONFIG_DEFAULTS.publish.mode,\n defaultPrice: raw.publish?.defaultPrice ?? CONFIG_DEFAULTS.publish.defaultPrice,\n },\n install: { harness: raw.install?.harness ?? CONFIG_DEFAULTS.install.harness },\n hooks: {\n searchMode: raw.hooks?.searchMode ?? CONFIG_DEFAULTS.hooks.searchMode,\n stopNag: raw.hooks?.stopNag ?? CONFIG_DEFAULTS.hooks.stopNag,\n },\n update: { mode: raw.update?.mode ?? CONFIG_DEFAULTS.update.mode },\n };\n}\n\nexport type Provenance = 'default' | 'file' | 'project' | 'env' | 'flag';\n\nexport interface ResolvedSetting<T> {\n value: T;\n source: Provenance;\n}\n\n/**\n * The per-project `.tenjin.json` layer (B3, D38): publish overrides discovered by\n * walking up from cwd, plus whether that file is gitignored. `gitignored` gates\n * `full-auto` — a committed file requesting it is downgraded (loosening gate).\n */\nexport interface ProjectPublishLayer {\n publish?: { mode?: PublishMode; defaultPrice?: string };\n gitignored: boolean;\n}\n\n/** publish.mode resolution: value, source, and the downgrade warning (if any). */\nexport interface PublishModeResolution {\n value: PublishMode;\n source: Provenance;\n /** Set when a committed `.tenjin.json`'s `full-auto` was downgraded to `auto`. */\n downgradedWarning?: string;\n}\n\n/** Effective value + where it came from, per key. What `config` (bare) renders. */\nexport interface EffectiveSettings {\n maxAutoSpend: ResolvedSetting<string>;\n sessionBudget: ResolvedSetting<string>;\n confirm: ResolvedSetting<string>;\n sendMaxAmount: ResolvedSetting<string>;\n allowlistCreators: ResolvedSetting<string[]>;\n baseUrl: ResolvedSetting<string>;\n rpcUrl: ResolvedSetting<string>;\n evalCohort: ResolvedSetting<boolean>;\n publishMode: PublishModeResolution;\n publishDefaultPrice: ResolvedSetting<string>;\n hooksSearchMode: ResolvedSetting<SearchHookMode>;\n hooksStopNag: ResolvedSetting<StopNagMode>;\n updateMode: ResolvedSetting<UpdateMode>;\n}\n\n/** CLI flags that participate in settings precedence (`--base-url`). */\nexport interface SettingsFlags {\n baseUrl?: string;\n}\n\nexport interface ResolveSettingsInput {\n /** Raw file values (present keys only) — from loadRawConfig, not loadConfig. */\n config: PartialConfig;\n flags: SettingsFlags;\n env: NodeJS.ProcessEnv;\n /** The nearest `.tenjin.json` layer, when one was found (see publish-settings). */\n project?: ProjectPublishLayer;\n}\n\n/**\n * Apply precedence flag > env > file > default per key, returning each effective\n * value with its source. In B1 only baseUrl has flag/env overrides\n * (`--base-url`, TENJIN_BASE_URL); the rest resolve file-or-default. B3 adds the\n * publish keys, which additionally fold in the per-project `.tenjin.json` layer.\n */\nexport function resolveSettings(input: ResolveSettingsInput): EffectiveSettings {\n const { config, flags, env, project } = input;\n return {\n maxAutoSpend: fileOrDefault('maxAutoSpend', config),\n sessionBudget: fileOrDefault('sessionBudget', config),\n confirm: fileOrDefault('confirm', config),\n sendMaxAmount: resolveSendMaxAmount(config),\n allowlistCreators: fileOrDefault('allowlistCreators', config),\n baseUrl: resolveBaseUrl(config, flags, env),\n rpcUrl: fileOrDefault('rpcUrl', config),\n evalCohort: fileOrDefault('evalCohort', config),\n publishMode: resolvePublishMode({ config, project, env }),\n publishDefaultPrice: resolvePublishDefaultPrice({ config, project }),\n hooksSearchMode: resolveHooksSearchMode(config),\n hooksStopNag: resolveHooksStopNag(config),\n updateMode: resolveUpdateMode(config),\n };\n}\n\n/** update.mode: file or default, no env or flag. Every surface that reports a\n * newer version reads this one resolved value, so they cannot disagree. */\nfunction resolveUpdateMode(config: PartialConfig): ResolvedSetting<UpdateMode> {\n const fromFile = config.update?.mode;\n if (fromFile !== undefined) return { value: fromFile, source: 'file' };\n return { value: CONFIG_DEFAULTS.update.mode, source: 'default' };\n}\n\n/** hooks.stopNag: file or default, same shape as hooks.searchMode. */\nfunction resolveHooksStopNag(config: PartialConfig): ResolvedSetting<StopNagMode> {\n const fromFile = config.hooks?.stopNag;\n if (fromFile !== undefined) return { value: fromFile, source: 'file' };\n return { value: CONFIG_DEFAULTS.hooks.stopNag, source: 'default' };\n}\n\n/** hooks.searchMode: file or default. No env, flag, or project layer, because the\n * installed hook script reads the global file directly and has no CLI edge. */\nfunction resolveHooksSearchMode(config: PartialConfig): ResolvedSetting<SearchHookMode> {\n const fromFile = config.hooks?.searchMode;\n if (fromFile !== undefined) return { value: fromFile, source: 'file' };\n return { value: CONFIG_DEFAULTS.hooks.searchMode, source: 'default' };\n}\n\n/**\n * The loosening gate (D38): a committed (not-gitignored) `.tenjin.json` requesting\n * `full-auto` is downgraded to `auto`, never silently honored — cloning a repo\n * must not enable auto-publish. `full-auto` from global config / env / flag (all\n * inherently local, not cloned) is always honored.\n */\nconst FULL_AUTO_DOWNGRADE_WARNING =\n 'Ignoring publish.mode \"full-auto\" from a committed .tenjin.json (cloning a repo must not enable auto-publish); using \"auto\". Add .tenjin.json to .gitignore to opt in.';\n\nfunction coercePublishMode(raw: string | undefined): PublishMode | undefined {\n if (raw === undefined || raw.length === 0) return undefined;\n const parsed = PublishModeSchema.safeParse(raw);\n return parsed.success ? parsed.data : undefined;\n}\n\n/**\n * Resolve publish.mode through global file < project `.tenjin.json` < env\n * (TENJIN_PUBLISH_MODE) < flag (`--mode`). Total: an invalid env/flag value is\n * ignored (validation lives at the command edge, like baseUrl). The project\n * layer's `full-auto` is gated on that file being gitignored.\n */\nexport function resolvePublishMode(input: {\n config: PartialConfig;\n project?: ProjectPublishLayer;\n env: NodeJS.ProcessEnv;\n flag?: string;\n}): PublishModeResolution {\n const { config, project, env, flag } = input;\n let winner: PublishModeResolution = { value: CONFIG_DEFAULTS.publish.mode, source: 'default' };\n\n const fromFile = config.publish?.mode;\n if (fromFile !== undefined) winner = { value: fromFile, source: 'file' };\n\n if (project !== undefined && project.publish?.mode !== undefined) {\n const fromProject = project.publish.mode;\n if (fromProject === 'full-auto' && !project.gitignored) {\n winner = { value: 'auto', source: 'project', downgradedWarning: FULL_AUTO_DOWNGRADE_WARNING };\n } else {\n winner = { value: fromProject, source: 'project' };\n }\n }\n\n const fromEnv = coercePublishMode(env.TENJIN_PUBLISH_MODE);\n if (fromEnv !== undefined) winner = { value: fromEnv, source: 'env' };\n\n const fromFlag = coercePublishMode(flag);\n if (fromFlag !== undefined) winner = { value: fromFlag, source: 'flag' };\n\n return winner;\n}\n\n/** Resolve publish.defaultPrice (atomic) through global file < project < default. */\nexport function resolvePublishDefaultPrice(input: {\n config: PartialConfig;\n project?: ProjectPublishLayer;\n}): ResolvedSetting<string> {\n const { config, project } = input;\n let result: ResolvedSetting<string> = {\n value: CONFIG_DEFAULTS.publish.defaultPrice,\n source: 'default',\n };\n if (config.publish?.defaultPrice !== undefined) {\n result = { value: config.publish.defaultPrice, source: 'file' };\n }\n if (project?.publish?.defaultPrice !== undefined) {\n result = { value: project.publish.defaultPrice, source: 'project' };\n }\n return result;\n}\n\n/** Persist a full, validated config via the atomic writer (0700 dir, 0644 file). */\nexport async function writeConfig(dir: string, config: Config): Promise<void> {\n const validated = ConfigSchema.parse(config);\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o700,\n });\n}\n\n/**\n * sendMaxAmount deliberately bypasses fileOrDefault: it has no usable default\n * (the operator's require-set-before-first-send posture). Absent from\n * config.json it resolves to the SEND_MAX_UNSET sentinel with source 'default',\n * which `tenjin send` refuses outright — the cap must be set to an amount, \"0\"\n * (disable), or an explicit \"none\" (uncapped opt-in) before the first send.\n */\nfunction resolveSendMaxAmount(config: PartialConfig): ResolvedSetting<string> {\n if (config.sendMaxAmount !== undefined) return { value: config.sendMaxAmount, source: 'file' };\n return { value: SEND_MAX_UNSET, source: 'default' };\n}\n\nfunction fileOrDefault<K extends keyof Config>(\n key: K,\n config: PartialConfig,\n): ResolvedSetting<Config[K]> {\n const fromFile = config[key];\n // PartialConfig[K] is Config[K] | undefined; narrowing an indexed access of a\n // type parameter doesn't refine K, so assert the excluded-undefined type.\n if (fromFile !== undefined) return { value: fromFile as Config[K], source: 'file' };\n return { value: CONFIG_DEFAULTS[key], source: 'default' };\n}\n\nfunction resolveBaseUrl(\n config: PartialConfig,\n flags: SettingsFlags,\n env: NodeJS.ProcessEnv,\n): ResolvedSetting<string> {\n if (flags.baseUrl !== undefined && flags.baseUrl.length > 0) {\n return { value: flags.baseUrl, source: 'flag' };\n }\n const fromEnv = env.TENJIN_BASE_URL;\n if (fromEnv !== undefined && fromEnv.length > 0) {\n return { value: fromEnv, source: 'env' };\n }\n if (config.baseUrl !== undefined) return { value: config.baseUrl, source: 'file' };\n return { value: CONFIG_DEFAULTS.baseUrl, source: 'default' };\n}\n\nfunction isNotFound(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code?: unknown }).code === 'ENOENT'\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAQzB,IAAM,eAAe,iBAAE,OAAO,EAAE,MAAM,SAAS,wCAAwC;AAGhF,IAAM,oBAAoB,iBAAE,KAAK,CAAC,UAAU,QAAQ,WAAW,CAAC;AAQhE,SAAS,qBAAqB,OAAe,UAA+B;AACjF,QAAM,SAAS,kBAAkB,UAAU,KAAK;AAChD,MAAI,OAAO,QAAS,QAAO,OAAO;AAClC,QAAM,IAAI,SAAS,SAAS,WAAW,QAAQ,IAAI,KAAK,UAAU,KAAK,CAAC,IAAI;AAAA,IAC1E,KAAK;AAAA,EACP,CAAC;AACH;AAOA,IAAM,sBAAsB,iBAAE,OAAO;AAAA,EACnC,MAAM;AAAA,EACN,cAAc;AAChB,CAAC;AAQM,IAAM,uBAAuB,iBAAE,KAAK,CAAC,QAAQ,UAAU,KAAK,CAAC;AAQ7D,SAAS,wBAAwB,OAAe,UAAkC;AACvF,QAAM,SAAS,qBAAqB,UAAU,KAAK;AACnD,MAAI,OAAO,QAAS,QAAO,OAAO;AAClC,QAAM,IAAI,SAAS,SAAS,WAAW,QAAQ,IAAI,KAAK,UAAU,KAAK,CAAC,IAAI;AAAA,IAC1E,KAAK;AAAA,EACP,CAAC;AACH;AAaO,IAAM,oBAAoB,iBAAE,KAAK,CAAC,MAAM,mBAAmB,KAAK,CAAC;AAGjE,SAAS,iBAAiB,OAAe,UAA+B;AAC7E,QAAM,SAAS,kBAAkB,UAAU,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AC7F,SAAO,EAAE,OAAO,gBAAgB,QAAQ,UAAU;AACpD;AAEA,SAAS,cACP,KACA,QAC4B;AAC5B,QAAM,WAAW,OAAO,GAAG;AAG3B,MAAI,aAAa,OAAW,QAAO,EAAE,OAAO,UAAuB,QAAQ,OAAO;AAClF,SAAO,EAAE,OAAO,gBAAgB,GAAG,GAAG,QAAQ,UAAU;AAC1D;AAEA,SAAS,eACP,QACA,OACA,KACyB;AACzB,MAAI,MAAM,YAAY,UAAa,MAAM,QAAQ,SAAS,GAAG;AAC3D,WAAO,EAAE,OAAO,MAAM,SAAS,QAAQ,OAAO;AAAA,EAChD;AACA,QAAM,UAAU,IAAI;AACpB,MAAI,YAAY,UAAa,QAAQ,SAAS,GAAG;AAC/C,WAAO,EAAE,OAAO,SAAS,QAAQ,MAAM;AAAA,EACzC;AACA,MAAI,OAAO,YAAY,OAAW,QAAO,EAAE,OAAO,OAAO,SAAS,QAAQ,OAAO;AACjF,SAAO,EAAE,OAAO,gBAAgB,SAAS,QAAQ,UAAU;AAC7D;AAEA,SAAS,WAAW,KAAuB;AACzC,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACT,IAA2B,SAAS;AAEzC;","names":[]}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
package_default
|
|
4
|
-
} from "./chunk-CA3JV7FX.js";
|
|
5
2
|
import {
|
|
6
3
|
emitNotice
|
|
7
4
|
} from "./chunk-B676GPS2.js";
|
|
8
5
|
import {
|
|
9
6
|
loadConfig
|
|
10
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-LSWP7MU2.js";
|
|
8
|
+
import {
|
|
9
|
+
package_default
|
|
10
|
+
} from "./chunk-ETKZWJ4B.js";
|
|
11
11
|
import {
|
|
12
12
|
updateCheckPath
|
|
13
13
|
} from "./chunk-ZQIQ55KK.js";
|
|
@@ -23,7 +23,8 @@ var FETCH_TIMEOUT_MS = 1500;
|
|
|
23
23
|
var DIST_TAGS_URL = "https://registry.npmjs.org/-/package/tenjin-cli/dist-tags";
|
|
24
24
|
var TagEntrySchema = external_exports.object({
|
|
25
25
|
checkedAtMs: external_exports.number(),
|
|
26
|
-
|
|
26
|
+
/** The version the tag named. Absent when the answer was unusable. */
|
|
27
|
+
latest: external_exports.string().optional(),
|
|
27
28
|
/** When the nudge was last PRINTED for this tag. Absent until one has been. */
|
|
28
29
|
notifiedAtMs: external_exports.number().optional()
|
|
29
30
|
});
|
|
@@ -57,14 +58,20 @@ async function maybeUpdate(deps) {
|
|
|
57
58
|
const cached = await readCache(path);
|
|
58
59
|
const entry = cached?.tags[tag];
|
|
59
60
|
const fresh = entry !== void 0 && nowMs - entry.checkedAtMs < CHECK_INTERVAL_MS;
|
|
60
|
-
|
|
61
|
-
if (
|
|
62
|
-
|
|
61
|
+
let latest;
|
|
62
|
+
if (fresh) {
|
|
63
|
+
latest = entry.latest ?? null;
|
|
64
|
+
} else {
|
|
65
|
+
const answer = await resolveLatest(current, deps);
|
|
66
|
+
if (answer === null) return;
|
|
67
|
+
latest = answer.latest;
|
|
68
|
+
}
|
|
69
|
+
const upgradeable = latest !== null && isNewer(latest, current);
|
|
63
70
|
const human = deps.io.isTTY && !deps.json;
|
|
64
71
|
const notifiedAtMs = entry?.notifiedAtMs;
|
|
65
72
|
const due = human && upgradeable && (notifiedAtMs === void 0 || nowMs - notifiedAtMs >= CHECK_INTERVAL_MS);
|
|
66
73
|
const nudgedAtMs = due ? nowMs : notifiedAtMs;
|
|
67
|
-
const signal = upgradeable ? { current, latest } : void 0;
|
|
74
|
+
const signal = upgradeable && latest !== null ? { current, latest } : void 0;
|
|
68
75
|
const signalChanged = cached?.signal?.current !== signal?.current || cached?.signal?.latest !== signal?.latest;
|
|
69
76
|
if (!fresh || due || signalChanged) {
|
|
70
77
|
await writeCache(path, {
|
|
@@ -76,18 +83,19 @@ async function maybeUpdate(deps) {
|
|
|
76
83
|
...cached?.tags,
|
|
77
84
|
[tag]: {
|
|
78
85
|
checkedAtMs: fresh ? entry.checkedAtMs : nowMs,
|
|
79
|
-
latest,
|
|
86
|
+
...latest !== null ? { latest } : {},
|
|
80
87
|
...nudgedAtMs !== void 0 ? { notifiedAtMs: nudgedAtMs } : {}
|
|
81
88
|
}
|
|
82
89
|
}
|
|
83
90
|
});
|
|
84
91
|
}
|
|
85
|
-
if (
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
92
|
+
if (due && latest !== null) {
|
|
93
|
+
emitNotice(
|
|
94
|
+
deps.io,
|
|
95
|
+
`tenjin-cli ${latest} is available (you have ${current}). Update: run tenjin update`,
|
|
96
|
+
{ json: deps.json }
|
|
97
|
+
);
|
|
98
|
+
}
|
|
91
99
|
} catch {
|
|
92
100
|
}
|
|
93
101
|
}
|
|
@@ -106,20 +114,14 @@ async function readUpdateSignal(dir, currentVersion) {
|
|
|
106
114
|
}
|
|
107
115
|
}
|
|
108
116
|
function channelTag(version) {
|
|
109
|
-
|
|
110
|
-
if (parsed === null) return null;
|
|
111
|
-
return parsed.alpha !== null ? "alpha" : "latest";
|
|
117
|
+
return parseVersion(version) === null ? null : "latest";
|
|
112
118
|
}
|
|
113
119
|
function resolveTarget(current, tags) {
|
|
114
120
|
const channel = channelTag(current);
|
|
115
121
|
if (channel === null) return null;
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
if (candidate === void 0 || parseVersion(candidate) === null) continue;
|
|
120
|
-
if (best === null || isNewer(candidate, best)) best = candidate;
|
|
121
|
-
}
|
|
122
|
-
return best;
|
|
122
|
+
const candidate = tags[channel];
|
|
123
|
+
if (candidate === void 0 || parseVersion(candidate) === null) return null;
|
|
124
|
+
return candidate;
|
|
123
125
|
}
|
|
124
126
|
async function fetchDistTags(opts) {
|
|
125
127
|
const doFetch = opts.fetchImpl ?? fetch;
|
|
@@ -136,7 +138,7 @@ async function fetchDistTags(opts) {
|
|
|
136
138
|
}
|
|
137
139
|
async function resolveLatest(current, deps) {
|
|
138
140
|
const tags = await fetchDistTags({ fetchImpl: deps.fetchImpl, timeoutMs: FETCH_TIMEOUT_MS });
|
|
139
|
-
return tags === null ? null : resolveTarget(current, tags);
|
|
141
|
+
return tags === null ? null : { latest: resolveTarget(current, tags) };
|
|
140
142
|
}
|
|
141
143
|
async function writeCache(path, cache) {
|
|
142
144
|
await writeFileAtomic(path, `${JSON.stringify(cache, null, 2)}
|
|
@@ -186,4 +188,4 @@ export {
|
|
|
186
188
|
fetchDistTags,
|
|
187
189
|
isNewer
|
|
188
190
|
};
|
|
189
|
-
//# sourceMappingURL=chunk-
|
|
191
|
+
//# sourceMappingURL=chunk-MJSXP4LW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/update-check.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { z } from 'zod';\nimport pkg from '../../package.json';\nimport { writeFileAtomic } from './atomic-json';\nimport { loadConfig } from './config';\nimport type { UpdateMode } from './config';\nimport { emitNotice } from './output';\nimport type { Io } from './output';\nimport type { UpdateAvailable } from '../schemas';\nimport { updateCheckPath } from './paths';\n\n/**\n * \"A newer tenjin-cli exists\", asked of npm at most once a day and reported\n * three ways: one dim stderr line for a human at a terminal, `updateAvailable`\n * on the JSON envelope, and a line on the generated hook scripts' output.\n *\n * It REPORTS and never installs. A CLI that starts a fresh process per\n * invocation has no deferred-activation window to hide a binary swap in — \"next\n * start\" is \"mid-session\" for whatever is driving it — so the decision to run\n * `tenjin update` belongs to the agent or the human, not to this check.\n *\n * Everything here is subordinate to the command that ran: the fetch happens\n * AFTER the envelope is written, it never touches stdout, it never changes an\n * exit code, and every failure it can have (offline, slow registry, junk JSON, a\n * tag that does not exist) is swallowed. CI skips the whole thing: a build log\n * can act on none of it. `update.mode off` is the opt-out and silences all three\n * surfaces, including the request to npm.\n */\n\nconst CHECK_INTERVAL_MS = 86_400_000; // 24h\nconst FETCH_TIMEOUT_MS = 1500;\nconst DIST_TAGS_URL = 'https://registry.npmjs.org/-/package/tenjin-cli/dist-tags';\n\n/** What is known about ONE dist-tag: when it was asked, and what it said. */\nconst TagEntrySchema = z.object({\n checkedAtMs: z.number(),\n /** The version the tag named. Absent when the answer was unusable. */\n latest: z.string().optional(),\n /** When the nudge was last PRINTED for this tag. Absent until one has been. */\n notifiedAtMs: z.number().optional(),\n});\n\n/**\n * The cache is a pure optimization, so a bad one is re-fetched, never repaired.\n * Keyed by dist-tag: an entry this build did not ask about is carried forward\n * untouched rather than evicted.\n */\nconst CacheSchema = z.object({\n schemaVersion: z.literal(1),\n tags: z.record(z.string(), TagEntrySchema),\n /**\n * The resolved \"you could upgrade\" fact, written whenever it changes and\n * cleared when it stops being true.\n *\n * Denormalized from `tags` on purpose: the generated hook scripts are\n * standalone .mjs that cannot import this module and do not know which\n * version is running, so a per-tag entry would leave them unable to tell an\n * upgrade from a match. Storing the comparison's ANSWER is what lets a hook\n * report it without reimplementing any of it.\n */\n signal: z.object({ current: z.string(), latest: z.string() }).optional(),\n});\ntype Cache = z.infer<typeof CacheSchema>;\n\n/** `{\"latest\":\"1.2.3\",\"alpha\":\"1.3.0-alpha.1\"}` — tag names are not fixed. */\nconst DistTagsSchema = z.record(z.string(), z.string());\n\nexport interface UpdateCheckDeps {\n dir: string;\n io: Io;\n /** The global --json flag; ANDed with io.isTTY exactly as the emit path does. */\n json: boolean;\n env?: NodeJS.ProcessEnv;\n /** Clock seam (ms since epoch) for deterministic TTL tests. */\n now?: () => number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** The running version; defaults to this build's. Injectable for tests. */\n currentVersion?: string;\n /** Resolved update.mode; defaults to reading the config file. */\n mode?: UpdateMode;\n}\n\n/**\n * Print the update nudge if one is due. NEVER rejects — the caller awaits it\n * between a command's output and its exit, so a throw here would replace a\n * finished command's result with an internal error.\n */\nexport async function maybeUpdate(deps: UpdateCheckDeps): Promise<void> {\n try {\n const env = deps.env ?? process.env;\n // Never in CI, in either mode: a build log cannot act on a nudge, and a\n // build machine must not silently acquire a different binary mid-pipeline.\n if (env.CI !== undefined && env.CI.length > 0) return;\n\n const mode = deps.mode ?? (await loadConfig(deps.dir)).update.mode;\n if (mode === 'off') return;\n\n const nowMs = (deps.now ?? Date.now)();\n const current = deps.currentVersion ?? pkg.version;\n const path = updateCheckPath(deps.dir);\n const tag = channelTag(current);\n if (tag === null) return; // a version this build cannot parse follows no channel\n\n // Only this tag's entry answers this binary's question; the other channel's\n // is neither used nor disturbed.\n const cached = await readCache(path);\n const entry = cached?.tags[tag];\n const fresh = entry !== undefined && nowMs - entry.checkedAtMs < CHECK_INTERVAL_MS;\n\n // Resolved through the same function `tenjin update` uses, so the nudge can\n // never advertise a version the command would decline to install, nor stay\n // quiet about one it would.\n //\n // Only a registry that could not be ASKED returns without caching; an answer\n // this build cannot use has still been answered, and moves the clock below.\n let latest: string | null;\n if (fresh) {\n latest = entry.latest ?? null;\n } else {\n const answer = await resolveLatest(current, deps);\n if (answer === null) return;\n latest = answer.latest;\n }\n\n const upgradeable = latest !== null && isNewer(latest, current);\n\n // Once a day means once a day, not once per FETCH: a fresh cache would\n // otherwise repeat the same line on every command for 24h. The two clocks are\n // separate because they answer separate questions — when we last asked npm,\n // and when we last interrupted the human.\n //\n // `human` is part of `due` for the second of those: this code now runs on\n // every surface, to feed the envelope signal, so without it an agent run\n // would stamp the nudge clock having printed nothing and leave a shared\n // machine's terminal quiet for 24h.\n const human = deps.io.isTTY && !deps.json;\n const notifiedAtMs = entry?.notifiedAtMs;\n const due =\n human &&\n upgradeable &&\n (notifiedAtMs === undefined || nowMs - notifiedAtMs >= CHECK_INTERVAL_MS);\n\n // Carried forward when nothing is printed: the day since the last nudge does\n // not restart just because the registry was asked again.\n const nudgedAtMs = due ? nowMs : notifiedAtMs;\n\n // Carries the agent-visible half of the answer, so a hook or an envelope can\n // report it without knowing which version is running.\n const signal = upgradeable && latest !== null ? { current, latest } : undefined;\n const signalChanged =\n cached?.signal?.current !== signal?.current || cached?.signal?.latest !== signal?.latest;\n\n // Nothing learned and nothing said means nothing to write. Deliberately NOT\n // locked: two concurrent CLI processes can both nudge, and one duplicated\n // line is cheaper than a lock on the exit path of every command.\n if (!fresh || due || signalChanged) {\n await writeCache(path, {\n schemaVersion: 1,\n ...(signal !== undefined ? { signal } : {}),\n // Read-modify-write: the tag this run did not ask about keeps whatever it\n // knew, including its own nudge clock.\n tags: {\n ...cached?.tags,\n [tag]: {\n checkedAtMs: fresh ? entry.checkedAtMs : nowMs,\n ...(latest !== null ? { latest } : {}),\n ...(nudgedAtMs !== undefined ? { notifiedAtMs: nudgedAtMs } : {}),\n },\n },\n });\n }\n\n // Named as the command, not the npm invocation it wraps: `update` prints the\n // right instructions itself for an install it cannot perform (a source\n // checkout, a yarn global), so this line is correct everywhere.\n if (due && latest !== null) {\n emitNotice(\n deps.io,\n `tenjin-cli ${latest} is available (you have ${current}). Update: run tenjin update`,\n { json: deps.json },\n );\n }\n } catch {\n // Unreachable by construction (every step below is already guarded); here so\n // that staying invisible does not depend on that remaining true.\n }\n}\n\n/**\n * What the last check learned, for the envelope. Cache only: this runs before\n * every command's output, so it may not fetch, may not block, and may not throw.\n * Null when nothing newer is known, when the cache is absent or stale-shaped, or\n * when `update.mode` is `off` — off silences BOTH surfaces, not just the line a\n * human sees.\n *\n * Reporting rather than installing is the whole design. A CLI that starts a\n * fresh process per invocation has no deferred-activation moment to hide a\n * binary swap in, so the agent is told and decides for itself.\n */\nexport async function readUpdateSignal(\n dir: string,\n currentVersion?: string,\n): Promise<UpdateAvailable | null> {\n try {\n const current = currentVersion ?? pkg.version;\n const tag = channelTag(current);\n if (tag === null) return null;\n if ((await loadConfig(dir)).update.mode === 'off') return null;\n const cached = await readCache(updateCheckPath(dir));\n const latest = cached?.tags[tag]?.latest;\n if (latest === undefined || !isNewer(latest, current)) return null;\n return { current, latest };\n } catch {\n return null; // never the command's business\n }\n}\n\n/**\n * Which dist-tag this build follows, or null for a version string this package\n * has no channel for. Null rather than a default, because every caller's right\n * answer differs: the nudge goes quiet, and `tenjin update` refuses instead of\n * silently reporting a foreign build \"up to date\" against a tag it never\n * belonged to.\n *\n * Every build follows `latest`; see RELEASING.md, which changes with this.\n */\nexport function channelTag(version: string): 'latest' | null {\n return parseVersion(version) === null ? null : 'latest';\n}\n\n/**\n * The version this build can move to: whatever sits on the tag it follows.\n * Consulting a second tag added no reachable version and one way to be wrong: a\n * tag sitting ahead of `latest` could redirect the self-update to a build the\n * release line never promoted. Null both when that tag is absent and when it\n * names a version VERSION_RE rejects; `runUpdate` separates those, and neither\n * means the registry was unreachable.\n */\nexport function resolveTarget(current: string, tags: Record<string, string>): string | null {\n const channel = channelTag(current);\n if (channel === null) return null;\n const candidate = tags[channel];\n // Unparseable counts as absent: isNewer loses every comparison against junk,\n // so admitting one would read as \"up to date\" forever.\n if (candidate === undefined || parseVersion(candidate) === null) return null;\n return candidate;\n}\n\n/**\n * Ask the registry for tenjin-cli's whole dist-tag map. Returns null for every\n * failure there is, INCLUDING a response that arrives too late — the AbortSignal\n * is what bounds the delay a finished command can suffer. Nothing is written\n * here: a failed check caches nothing, so the next command retries rather than\n * going quiet for 24h over one dropped packet. The nudge passes its own short\n * budget; `tenjin update` passes the run's request timeout, because there the\n * fetch IS the command rather than a stowaway on someone else's exit path.\n *\n * The whole map rather than one tag, so a caller can tell an unreachable\n * registry (null) from one that answered without the tag it asked for (a map\n * that lacks the key) — two failures with two different fixes.\n */\nexport async function fetchDistTags(opts: {\n fetchImpl?: typeof fetch;\n timeoutMs: number;\n}): Promise<Record<string, string> | null> {\n const doFetch = opts.fetchImpl ?? fetch;\n let json: unknown;\n try {\n const res = await doFetch(DIST_TAGS_URL, { signal: AbortSignal.timeout(opts.timeoutMs) });\n if (!res.ok) return null;\n json = await res.json();\n } catch {\n return null;\n }\n const parsed = DistTagsSchema.safeParse(json);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * The nudge's one-shot: fetch, then resolve. Null when the registry could not be\n * asked; `{ latest: null }` when it answered with nothing usable.\n */\nasync function resolveLatest(\n current: string,\n deps: UpdateCheckDeps,\n): Promise<{ latest: string | null } | null> {\n const tags = await fetchDistTags({ fetchImpl: deps.fetchImpl, timeoutMs: FETCH_TIMEOUT_MS });\n return tags === null ? null : { latest: resolveTarget(current, tags) };\n}\n\nasync function writeCache(path: string, cache: Cache): Promise<void> {\n await writeFileAtomic(path, `${JSON.stringify(cache, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\nasync function readCache(path: string): Promise<Cache | null> {\n try {\n const parsed = CacheSchema.safeParse(JSON.parse(await readFile(path, 'utf8')));\n return parsed.success ? parsed.data : null;\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Version comparison: this package's shape only, no semver dependency.\n// ---------------------------------------------------------------------------\n\n/** `major.minor.patch` with an optional `-alpha.N` — every version tenjin-cli\n * has ever published. Anything else is unparseable ON PURPOSE (see isNewer). */\nconst VERSION_RE = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-alpha\\.(\\d+))?$/;\n\ninterface Version {\n major: number;\n minor: number;\n patch: number;\n /** null = a release; a number = that prerelease counter. */\n alpha: number | null;\n}\n\nfunction parseVersion(raw: string): Version | null {\n const m = VERSION_RE.exec(raw);\n if (m === null) return null;\n const [, major, minor, patch, alpha] = m;\n if (major === undefined || minor === undefined || patch === undefined) return null;\n return {\n major: Number(major),\n minor: Number(minor),\n patch: Number(patch),\n alpha: alpha !== undefined ? Number(alpha) : null,\n };\n}\n\n/**\n * Is `candidate` newer than `current`? An unparseable version on EITHER side is\n * \"not newer\": the registry is untrusted input, and the failure mode of guessing\n * is nagging every single command with a line the user cannot act on. A true\n * return therefore also certifies that BOTH sides parse, which is what lets\n * `tenjin update` splice the candidate into an npm argv without re-validating.\n */\nexport function isNewer(candidate: string, current: string): boolean {\n const a = parseVersion(candidate);\n const b = parseVersion(current);\n if (a === null || b === null) return false;\n if (a.major !== b.major) return a.major > b.major;\n if (a.minor !== b.minor) return a.minor > b.minor;\n if (a.patch !== b.patch) return a.patch > b.patch;\n // Same release triple: semver says a prerelease precedes its own release, so\n // 0.1.0 beats 0.1.0-alpha.9 and never the other way around.\n if (a.alpha === null) return b.alpha !== null;\n if (b.alpha === null) return false;\n return a.alpha > b.alpha;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AA6BzB,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB;AACzB,IAAM,gBAAgB;AAGtB,IAAM,iBAAiB,iBAAE,OAAO;AAAA,EAC9B,aAAa,iBAAE,OAAO;AAAA;AAAA,EAEtB,QAAQ,iBAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAE5B,cAAc,iBAAE,OAAO,EAAE,SAAS;AACpC,CAAC;AAOD,IAAM,cAAc,iBAAE,OAAO;AAAA,EAC3B,eAAe,iBAAE,QAAQ,CAAC;AAAA,EAC1B,MAAM,iBAAE,OAAO,iBAAE,OAAO,GAAG,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWzC,QAAQ,iBAAE,OAAO,EAAE,SAAS,iBAAE,OAAO,GAAG,QAAQ,iBAAE,OAAO,EAAE,CAAC,EAAE,SAAS;AACzE,CAAC;AAID,IAAM,iBAAiB,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,OAAO,CAAC;AAuBtD,eAAsB,YAAY,MAAsC;AACtE,MAAI;AACF,UAAM,MAAM,KAAK,OAAO,QAAQ;AAGhC,QAAI,IAAI,OAAO,UAAa,IAAI,GAAG,SAAS,EAAG;AAE/C,UAAM,OAAO,KAAK,SAAS,MAAM,WAAW,KAAK,GAAG,GAAG,OAAO;AAC9D,QAAI,SAAS,MAAO;AAEpB,UAAM,SAAS,KAAK,OAAO,KAAK,KAAK;AACrC,UAAM,UAAU,KAAK,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,MAAI,EAAE,UAAU,KAAM,QAAO,EAAE,UAAU;AACzC,MAAI,EAAE,UAAU,KAAM,QAAO;AAC7B,SAAO,EAAE,QAAQ,EAAE;AACrB;","names":[]}
|
|
@@ -2,7 +2,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
|
|
|
2
2
|
import {
|
|
3
3
|
HOSTED_SKILL_NAME,
|
|
4
4
|
readSkillFile
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-QWBUKIP2.js";
|
|
6
6
|
import {
|
|
7
7
|
CliError,
|
|
8
8
|
hasCode,
|
|
@@ -18,6 +18,9 @@ async function installSkill(srcDir, destDir, dryRun, name, opts = {}) {
|
|
|
18
18
|
if (src === null) {
|
|
19
19
|
throw new CliError("INTERNAL", `Packaged skill source ${srcDir} is empty`);
|
|
20
20
|
}
|
|
21
|
+
if (opts.materialize !== void 0) {
|
|
22
|
+
for (const [rel, content] of src) src.set(rel, opts.materialize(rel, content));
|
|
23
|
+
}
|
|
21
24
|
const writeTo = /* @__PURE__ */ new Map();
|
|
22
25
|
await assertReachable(destDir, name);
|
|
23
26
|
await assertNoCaseCollision(destDir, name);
|
|
@@ -147,4 +150,4 @@ export {
|
|
|
147
150
|
installSkill,
|
|
148
151
|
resolveThroughLink
|
|
149
152
|
};
|
|
150
|
-
//# sourceMappingURL=chunk-
|
|
153
|
+
//# sourceMappingURL=chunk-NAAMHWSI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/skill-writer.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\nimport { hasCode } from './errno';\nimport { CliError } from './errors';\nimport { HOSTED_SKILL_NAME, readSkillFile } from './skill-wiring';\n\n/**\n * Writing one packaged skill into one harness directory, and the path guards that\n * write needs. Its own module, free of the command layer's dependencies, because\n * `install` and the post-command self-heal both write skills and the heal runs on\n * every command: reaching into commands/install would parse the wallet's viem\n * chunk on a `tenjin config`.\n */\n\nexport type SkillInstallStatus =\n 'installed' | 'updated' | 'up-to-date' | 'would-install' | 'would-update';\n\nexport interface SkillInstallResult {\n status: SkillInstallStatus;\n warning?: string;\n /** Was a real copy (a SKILL.md, not just the directory) already on disk before this run? */\n preexisting: boolean;\n}\n\nexport interface SkillWriteOptions {\n /**\n * Write THROUGH a symlinked destination (default), or replace it. `install`\n * follows the link, because the operator pointed it somewhere on purpose. The\n * unattended self-heal does not, and passes false: it has already refused every\n * link it could see, and this closes the gap between that look and this write,\n * where a link appearing in between would otherwise be followed. `rename` never\n * follows its final component, so the worst a race can now do is leave our\n * regular file where the new link was.\n */\n followSymlinks?: boolean;\n /**\n * Shape a packaged file before it is compared and written (config-conditional\n * skill content; see lib/skill-materialize). Applied to the SOURCE side only,\n * before the on-disk compare, so \"up-to-date\" means \"matches what this config\n * state would write\" and a config change makes the same source differ again. A\n * transform that throws aborts the whole install of this skill: a half-shaped\n * skill must never be written.\n */\n materialize?: (rel: string, content: Buffer) => Buffer;\n}\n\nexport async function installSkill(\n srcDir: string,\n destDir: string,\n dryRun: boolean,\n name: string,\n opts: SkillWriteOptions = {},\n): Promise<SkillInstallResult> {\n const src = await readTree(srcDir);\n if (src === null) {\n // assertSkillsSource already guards SKILL.md; this is defensive for an empty dir.\n throw new CliError('INTERNAL', `Packaged skill source ${srcDir} is empty`);\n }\n if (opts.materialize !== undefined) {\n for (const [rel, content] of src) src.set(rel, opts.materialize(rel, content));\n }\n\n // Only the files this package SHIPS are read and written. Everything else in the\n // directory belongs to the operator: never inspected, listed, or removed. That is\n // what package managers do (npm, dpkg, Homebrew all own their files, not the\n // directory), and wholesale replacement was the single cause behind a run of\n // data-loss, symlink and enumeration bugs.\n //\n // Resolved on BOTH paths, dry run included, so a dry run cannot promise a write\n // the real run refuses.\n const writeTo = new Map<string, string>();\n await assertReachable(destDir, name);\n await assertNoCaseCollision(destDir, name);\n for (const rel of src.keys()) {\n const declared = join(destDir, rel);\n writeTo.set(\n rel,\n opts.followSymlinks === false ? declared : await resolveThroughLink(declared, name),\n );\n }\n\n let differs = false;\n let preexisting = false;\n for (const [rel, content] of src) {\n const current = await readShippedFile(writeTo.get(rel)!, name, destDir);\n if (rel === 'SKILL.md') preexisting = current !== null;\n if (current === null || !current.equals(content)) differs = true;\n }\n const change = !preexisting ? 'create' : differs ? 'update' : 'none';\n\n if (!dryRun && change !== 'none') {\n for (const [rel, content] of src) {\n const target = writeTo.get(rel)!;\n try {\n // An existing file keeps the mode it has. A skill an operator (or their\n // dotfiles) made group-readable or read-only is theirs to have set that\n // way, and an update is no reason to hand it back at the default 0644.\n const current = await stat(target).catch(() => null);\n await writeFileAtomic(\n target,\n content,\n current === null ? {} : { mode: current.mode & 0o777 },\n );\n } catch (err) {\n // Culprit is derived from the file that FAILED, not assumed to be the\n // skills root: an existing skill directory that refuses the temp file is\n // itself the thing to chmod, and a symlinked SKILL.md fails in the link's\n // TARGET directory, which no path under destDir names.\n throw wrapWriteError(\n err,\n destDir,\n `the ${name} skill`,\n await deepestExisting(dirname(target)),\n { expected: ': a skill is a directory holding SKILL.md' },\n );\n }\n }\n }\n\n if (change === 'create') return { status: dryRun ? 'would-install' : 'installed', preexisting };\n if (change === 'none') return { status: 'up-to-date', preexisting };\n return {\n status: dryRun ? 'would-update' : 'updated',\n preexisting,\n // The hosted skill is a MIRROR of tenjin.blog/skills.md (roadmap G4), so a\n // differing local copy is a replacement, not the drift warning the CLI skills\n // get. Neither side carries a version or date, so the wording claims no\n // direction: the local file may well be a newer fetch than this package's copy.\n warning:\n name === HOSTED_SKILL_NAME\n ? `${destDir}: the hosted Tenjin skill differed and ${dryRun ? 'would be' : 'was'} replaced by this package's mirror of tenjin.blog/skills.md, which may be older; it stays as the zero-install fallback. Re-fetch it from tenjin.blog/skills.md if you need the current one.`\n : `${destDir}: local edits to ${name}'s SKILL.md ${dryRun ? 'would be' : 'were'} overwritten (the packaged copy is canonical).`,\n };\n}\n\n/**\n * Read a shipped file, or null when it is not there.\n *\n * The node-type guard lives in `readSkillFile`, shared with the wiring check and\n * the staleness check, because all three read the same operator-controlled paths\n * and a pipe at one of them used to hang whichever command got there first.\n */\nasync function readShippedFile(\n path: string,\n name: string,\n destDir: string,\n): Promise<Buffer | null> {\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return null;\n if (read.kind === 'ok') return read.bytes;\n if (read.kind === 'not-regular') {\n throw new CliError('INTERNAL', `${path} is not a regular file, so ${name} was not written.`, {\n fix: `A skill file must be a regular file. Check what is there (\\`ls -l ${path}\\`) and remove or replace it, then re-run \\`tenjin install\\`.`,\n });\n }\n // Names the FILE, not its directory: this is a read failure, and pointing at a\n // perfectly writable parent is what sent operators to chmod the wrong thing.\n throw wrapWriteError(read.err, destDir, `the ${name} skill`, path, { verb: 'read' });\n}\n\n/**\n * A destination the operator manages through a symlink is written THROUGH it, so\n * their link survives and their target is what actually changes. Same call the\n * settings.json writer makes, and the same reason: committing with `rename` over a\n * link would replace it with a regular file and strand the target.\n */\nexport async function resolveThroughLink(path: string, name: string): Promise<string> {\n const entry = await lstat(path).catch(() => null);\n if (entry === null || !entry.isSymbolicLink()) return path;\n const target = await realpath(path).catch(() => null);\n if (target !== null) return target;\n throw new CliError('INTERNAL', `${path} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a path that exists, or remove it (\\`ls -ld ${path}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * On a case-insensitive filesystem (the macOS default), a user directory named a\n * case variant of a shipped skill ALIASES the skill's path, so the write would\n * replace the user's own SKILL.md under a warning naming a path that is not on\n * disk. Detected by the alias itself: the destination resolves but the parent\n * lists only a differently-cased entry, which also means a case-SENSITIVE\n * filesystem (where both names can coexist) never trips this. Dry runs too.\n */\nasync function assertNoCaseCollision(destDir: string, name: string): Promise<void> {\n if (!existsSync(destDir)) return;\n const entries = await readdir(dirname(destDir)).catch(() => null);\n if (entries === null || entries.includes(name)) return;\n const variant = entries.find((e) => e.toLowerCase() === name.toLowerCase());\n if (variant === undefined) return;\n const actual = join(dirname(destDir), variant);\n throw new CliError(\n 'INTERNAL',\n `${actual} is a case variant of the ${name} skill and this filesystem treats them as the same directory, so ${name} was not written.`,\n {\n fix: `Rename or remove ${actual}, then re-run \\`tenjin install\\`.`,\n },\n );\n}\n\n/**\n * Fail a destination directory that is a BROKEN SYMLINK, on dry runs too, so a dry\n * run cannot report `would-install` where the real run cannot write. It checks only\n * that: an unwritable but real directory passes here and fails at the write, with\n * the permission-denied error.\n */\nasync function assertReachable(destDir: string, name: string): Promise<void> {\n const entry = await lstat(destDir).catch(() => null);\n if (entry?.isSymbolicLink() !== true) return;\n if ((await realpath(destDir).catch(() => null)) !== null) return;\n throw new CliError('INTERNAL', `${destDir} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a directory that exists, or remove it (\\`ls -ld ${destDir}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * The directory a denied WRITE should point the operator at: the deepest existing\n * ancestor of the failed target's directory, RESOLVED. An existing skill directory\n * that refuses the temp file names itself; a directory that could not be created\n * names the ancestor that refused to create it, because `ls -ld` on a path that is\n * not there says nothing. Resolved because a destination managed through a symlink\n * denies the write in the link's TARGET, and telling the operator to chmod the\n * link's path leaves them staring at a healthy link.\n */\nexport async function deepestExisting(dir: string): Promise<string> {\n for (let cur = dir; ; cur = dirname(cur)) {\n if (existsSync(cur)) return realpath(cur).catch(() => cur);\n if (dirname(cur) === cur) return cur;\n }\n}\n\n/** A raw errno under INTERNAL reads as a CLI bug and carries no fix. */\nexport function wrapWriteError(\n err: unknown,\n /** The destination as the operator knows it (the declared path, pre-resolution). */\n dest: string,\n /** What could not be written, e.g. `the tenjin-search skill` or `the Tenjin pointer`. */\n subject: string,\n /**\n * The path to point the operator at. A READ failure names the file itself, which\n * is the thing whose mode is wrong. A WRITE failure names the deepest existing\n * directory on the failed target's resolved path.\n */\n culprit: string,\n opts: {\n /** Which side failed; a read error reported as \"could not write\" misleads. */\n verb?: 'read' | 'write';\n /** Sentence tail for the wrong-kind fix, telling the operator the expected shape. */\n expected?: string;\n } = {},\n): unknown {\n const verb = opts.verb ?? 'write';\n const denied = hasCode(err, 'EACCES') || hasCode(err, 'EPERM');\n const missing = hasCode(err, 'ENOENT');\n // A skills directory that resolves to a regular file, or a SKILL.md that resolves\n // to a directory. Pathological, but a raw ENOTDIR/EISDIR says nothing about which\n // path is the wrong kind of thing.\n const wrongKind = hasCode(err, 'ENOTDIR') || hasCode(err, 'EISDIR');\n if (!denied && !missing && !wrongKind) return err;\n const fix = denied\n ? `Permission denied on ${culprit}. Check it (\\`ls -ld ${culprit}\\`), then re-run \\`tenjin install\\`.`\n : wrongKind\n ? `${dest} (or a path inside it) is not the kind of thing it needs to be${opts.expected ?? ''}. Check it (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`\n : `${dest} could not be created; if it is a symlink, check that its target exists (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`;\n return new CliError(\n 'INTERNAL',\n `Could not ${verb} ${subject} ${verb === 'read' ? 'at' : 'to'} ${dest}.`,\n { fix, cause: err },\n );\n}\n\n/**\n * Read a directory tree into a rel-path -> content map, or null when it does not\n * exist. Reads as raw `Buffer`, not `utf8`: today's skills are markdown-only, but\n * this is a general recursive dir-copy, and decoding to a string here would\n * silently corrupt a future non-text asset (an image, a font) on write, or worse,\n * make two different corrupted binaries both decode to U+FFFD and compare equal.\n */\nasync function readTree(dir: string): Promise<Map<string, Buffer> | null> {\n if (!existsSync(dir)) return null;\n const entries = await readdir(dir, { recursive: true, withFileTypes: true });\n const files = new Map<string, Buffer>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const full = join(entry.parentPath, entry.name);\n files.set(relative(dir, full), await readFile(full));\n }\n return files;\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,UAAU,SAAS,UAAU,Y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C1B,QAAM,SAAS,QAAQ,KAAK,QAAQ,KAAK,QAAQ,KAAK,OAAO;AAC7D,QAAM,UAAU,QAAQ,KAAK,QAAQ;AAIrC,QAAM,YAAY,QAAQ,KAAK,SAAS,KAAK,QAAQ,KAAK,QAAQ;AAClE,MAAI,CAAC,UAAU,CAAC,WAAW,CAAC,UAAW,QAAO;AAC9C,QAAM,MAAM,SACR,wBAAwB,OAAO,wBAAwB,OAAO,yCAC9D,YACE,GAAG,IAAI,iEAAiE,KAAK,YAAY,EAAE,wBAAwB,IAAI,yCACvH,GAAG,IAAI,qFAAqF,IAAI;AACtG,SAAO,IAAI;AAAA,IACT;AAAA,IACA,aAAa,IAAI,IAAI,OAAO,IAAI,SAAS,SAAS,OAAO,IAAI,IAAI,IAAI;AAAA,IACrE,EAAE,KAAK,OAAO,IAAI;AAAA,EACpB;AACF;AASA,eAAe,SAAS,KAAkD;AACxE,MAAI,CAAC,WAAW,GAAG,EAAG,QAAO;AAC7B,QAAM,UAAU,MAAM,QAAQ,KAAK,EAAE,WAAW,MAAM,eAAe,KAAK,CAAC;AAC3E,QAAM,QAAQ,oBAAI,IAAoB;AACtC,aAAW,SAAS,SAAS;AAC3B,QAAI,CAAC,MAAM,OAAO,EAAG;AACrB,UAAM,OAAO,KAAK,MAAM,YAAY,MAAM,IAAI;AAC9C,UAAM,IAAI,SAAS,KAAK,IAAI,GAAG,MAAM,SAAS,IAAI,CAAC;AAAA,EACrD;AACA,SAAO;AACT;","names":[]}
|
|
@@ -2,6 +2,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
|
|
|
2
2
|
import {
|
|
3
3
|
EXCERPT_MAX_LENGTH,
|
|
4
4
|
PUBLISH_STATUSES,
|
|
5
|
+
SEARCH_ID_WIRE_RE,
|
|
5
6
|
dedupeFindings,
|
|
6
7
|
deriveCard,
|
|
7
8
|
deriveProjectMarkers,
|
|
@@ -16,18 +17,18 @@ import {
|
|
|
16
17
|
resolveWriteAuth,
|
|
17
18
|
scan,
|
|
18
19
|
writeModeNotices
|
|
19
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-VRPLZERE.js";
|
|
20
21
|
import {
|
|
21
22
|
headingOutline
|
|
22
23
|
} from "./chunk-SGK2B724.js";
|
|
23
24
|
import {
|
|
24
25
|
loadSearches,
|
|
25
26
|
markSearchResolved
|
|
26
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-7NADDA2V.js";
|
|
27
28
|
import {
|
|
28
29
|
describeWallet,
|
|
29
30
|
resolveWalletProvider
|
|
30
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-7GJQ5RGA.js";
|
|
31
32
|
import {
|
|
32
33
|
trimSlash
|
|
33
34
|
} from "./chunk-XGZ5EVMB.js";
|
|
@@ -38,15 +39,14 @@ import {
|
|
|
38
39
|
import {
|
|
39
40
|
resolveContextSettings,
|
|
40
41
|
resolvePublishSettings
|
|
41
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-PKW3H26Z.js";
|
|
42
43
|
import {
|
|
43
|
-
UUID_RE,
|
|
44
44
|
parseUsdToAtomic,
|
|
45
45
|
toMoney
|
|
46
46
|
} from "./chunk-736DW4V3.js";
|
|
47
47
|
import {
|
|
48
48
|
parsePublishModeFlag
|
|
49
|
-
} from "./chunk-
|
|
49
|
+
} from "./chunk-LSWP7MU2.js";
|
|
50
50
|
import {
|
|
51
51
|
CliError
|
|
52
52
|
} from "./chunk-PAOVPSP6.js";
|
|
@@ -149,7 +149,13 @@ async function runPublish(args, ctx, deps = {}) {
|
|
|
149
149
|
priceAtomic,
|
|
150
150
|
...handle !== void 0 ? { handle } : {},
|
|
151
151
|
status,
|
|
152
|
-
...card !== void 0 ? { resource: card } : {}
|
|
152
|
+
...card !== void 0 ? { resource: card } : {},
|
|
153
|
+
// The attribution half of `--search-id`, and it follows the SAME rule the
|
|
154
|
+
// local ledger already follows: a draft answers nobody, so it claims nobody's
|
|
155
|
+
// demand either. Sending it on a draft put one demand signal on two posts —
|
|
156
|
+
// no command promotes a draft, so reaching a public piece means a second
|
|
157
|
+
// publish carrying the same id — with one of them possibly never shipping.
|
|
158
|
+
...args.searchId !== void 0 && status !== "draft" ? { searchId: args.searchId } : {}
|
|
153
159
|
};
|
|
154
160
|
const result = await publishPost(input, auth, {
|
|
155
161
|
baseUrl: runtime.baseUrl,
|
|
@@ -165,7 +171,7 @@ async function runPublish(args, ctx, deps = {}) {
|
|
|
165
171
|
}
|
|
166
172
|
function validateSearchId(args) {
|
|
167
173
|
if (args.searchId === void 0) return;
|
|
168
|
-
if (!
|
|
174
|
+
if (!SEARCH_ID_WIRE_RE.test(args.searchId)) {
|
|
169
175
|
throw new CliError("USAGE", `Invalid --search-id: ${JSON.stringify(args.searchId)}.`, {
|
|
170
176
|
fix: "Pass the searchId from a prior `tenjin search` (a uuid)."
|
|
171
177
|
});
|
|
@@ -181,7 +187,9 @@ async function closeNamedSearch(ctx, searchId, stored, parksPrivately, prefill)
|
|
|
181
187
|
if (stored === null) {
|
|
182
188
|
return open(`Published, but search ${searchId} is not in the local store.`);
|
|
183
189
|
}
|
|
184
|
-
const outcome = await markSearchResolved(ctx.dataDir, searchId, "publish"
|
|
190
|
+
const outcome = await markSearchResolved(ctx.dataDir, searchId, "publish", void 0, {
|
|
191
|
+
relink: true
|
|
192
|
+
});
|
|
185
193
|
if (outcome === "failed") {
|
|
186
194
|
return open(
|
|
187
195
|
`Published, but the local record for search ${searchId} could not be updated, so the open-loop reminder may repeat. Close it with \`tenjin outcome --search-id ${searchId} --status used\`.`
|
|
@@ -190,6 +198,14 @@ async function closeNamedSearch(ctx, searchId, stored, parksPrivately, prefill)
|
|
|
190
198
|
if (outcome === "not-found") {
|
|
191
199
|
return open(`Published, but search ${searchId} is no longer in the local store.`);
|
|
192
200
|
}
|
|
201
|
+
if (outcome === "relinked") return { id: searchId, closed: true, relinked: true, prefill };
|
|
202
|
+
if (outcome === "already-resolved" && stored.resolved?.by === "publish") {
|
|
203
|
+
ctx.io.stderr.write(
|
|
204
|
+
`Search ${searchId} was already answered by an earlier publish; this piece did not claim it.
|
|
205
|
+
`
|
|
206
|
+
);
|
|
207
|
+
return { id: searchId, closed: true, alreadyAnswered: true, prefill };
|
|
208
|
+
}
|
|
193
209
|
return { id: searchId, closed: true, prefill };
|
|
194
210
|
}
|
|
195
211
|
async function readSource(args) {
|
|
@@ -209,7 +225,9 @@ function receipt(result, baseUrl, searchInfo) {
|
|
|
209
225
|
const human = [
|
|
210
226
|
`Published ${title} (${sanitizeForTerminal(result.status)}) for ${price.usd} USD \u2192 ${sanitizeForTerminal(result.url)}`,
|
|
211
227
|
cacheEligible ? "Answer card is search-eligible." : missing.length > 0 ? `Answer card not search-eligible yet: ${missing.join(" ")}` : "Published as a browse-only document (no answer card).",
|
|
212
|
-
...searchInfo?.closed === true ? [
|
|
228
|
+
...searchInfo?.closed === true ? [
|
|
229
|
+
searchInfo.relinked === true ? `Re-linked search ${searchInfo.id} to this piece; it had been closed without one.` : searchInfo.alreadyAnswered === true ? `Search ${searchInfo.id} was already answered by an earlier publish.` : `Closed the loop on search ${searchInfo.id}.`
|
|
230
|
+
] : [],
|
|
213
231
|
...result.warnings.map((w) => `warning: ${sanitizeForTerminal(w)}`)
|
|
214
232
|
];
|
|
215
233
|
return {
|
|
@@ -351,4 +369,4 @@ function confirmMessage(warnCount, priceUsd) {
|
|
|
351
369
|
export {
|
|
352
370
|
runPublish
|
|
353
371
|
};
|
|
354
|
-
//# sourceMappingURL=chunk-
|
|
372
|
+
//# sourceMappingURL=chunk-O75FOHXS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/publish.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 } from '../lib/config';\nimport { loadSearches, markSearchResolved, type StoredSearch } from '../lib/search-store';\nimport { scan, type ScanContext, type ScanFinding } from '../lib/scan';\nimport { deriveProjectMarkers } from '../lib/scan-context';\nimport { headingOutline } from '../lib/markdown';\nimport { sanitizeForTerminal, sanitizeWireText } from '../lib/output';\nimport { trimSlash } from '../lib/url';\nimport {\n deriveCard,\n localCardEligibility,\n missingSentences,\n parseAppliesToFlags,\n parseFrontmatter,\n type CardFlags,\n type Frontmatter,\n type ResourceCardInput,\n} from '../lib/card';\nimport {\n publishPost,\n EXCERPT_MAX_LENGTH,\n PUBLISH_STATUSES,\n SEARCH_ID_WIRE_RE,\n type PublishInput,\n type PublishStatus,\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 publish <file.md>`: read the Markdown, parse\n * frontmatter for post + answer-card fields, run the deterministic scan (every\n * mode), gate on the D38\n * consent cascade, then write via the session key (minted on first use) or the\n * plain-SIWX fallback and return a compact receipt. The ordering is the point and\n * is enforced here: scan and consent BEFORE any wallet touch or network write.\n *\n * Exit codes: 0 success (incl. an ineligible-but-published card), 2 usage, 3\n * needs_confirmation / non-bypassable publish_blocked, 4 a write failure after\n * approval.\n */\n\nexport interface PublishArgs {\n /** The Markdown file to publish. */\n file?: string;\n /** The search this publish answers; closes its open loop. */\n searchId?: string;\n draft?: boolean;\n yes?: boolean;\n /** Raw `--mode` (review|auto|full-auto); validated at the edge (USAGE on a bad value). */\n mode?: string;\n /** Top-level post price, decimal USD at the edge (O1). */\n price?: string;\n /** The public preview text; overrides frontmatter `excerpt`. Absent, the server\n * derives one from the body's leading prose. */\n excerpt?: string;\n question?: string[];\n task?: 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}\n\nexport interface PublishDeps {\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 runPublish(\n args: PublishArgs,\n ctx: CommandContext,\n deps: PublishDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const cwd = deps.cwd ?? process.cwd();\n // Validate --mode at the edge (USAGE, exit 2) BEFORE any consent resolution: a\n // typo like `--mode Review` must never be silently dropped onto a looser mode\n // and publish unconfirmed. Mirrors install's --publish-mode edge check.\n if (args.mode !== undefined) parsePublishModeFlag(args.mode, '--mode');\n validateSearchId(args);\n\n const raw = await readSource(args);\n // Read the named search ONCE, here: it prefills the card's question below, and\n // whether it was found decides what the post-publish close reports. Local read,\n // and a missing store reads as no entry rather than failing the publish.\n const storedSearch =\n args.searchId !== undefined\n ? ((await loadSearches(ctx.dataDir)).find((s) => s.searchId === args.searchId) ?? null)\n : null;\n const { frontmatter, body } = parseFrontmatter(raw);\n\n const status = resolveStatus(args, frontmatter);\n const title = resolveTitle(frontmatter, body);\n const tags = resolveTags(frontmatter);\n const excerpt = resolveExcerpt(args, frontmatter);\n const handle = expectString(frontmatter, 'handle');\n // The named search's question prefills questionsAnswered, but only as a\n // fallback: an explicit --question OR a frontmatter questionsAnswered still\n // wins. That phrasing is what the next searcher will send.\n const cardFlags = cardFlagsFrom(args);\n const wanted = storedSearch?.question;\n const prefillQuestion = wanted === undefined ? undefined : cardQuestion(wanted);\n const roomForPrefill =\n cardFlags.question === undefined && frontmatter.questionsAnswered === undefined;\n if (prefillQuestion !== undefined && roomForPrefill) cardFlags.question = [prefillQuestion];\n // A prefill that was WANTED, had room, and was dropped anyway is the one case a\n // caller cannot infer: the card simply comes back without the question it asked\n // for. Reported on both surfaces, because --json never sees the stderr line.\n const prefill: PrefillOutcome =\n wanted === undefined || !roomForPrefill\n ? 'none'\n : prefillQuestion !== undefined\n ? 'applied'\n : 'dropped-too-long';\n if (prefill === 'dropped-too-long') {\n ctx.io.stderr.write(\n `The searched question is longer than ${CARD_QUESTION_MAX} characters, so it was not added to the answer card; pass --question to set a shorter one.\\n`,\n );\n }\n const card = deriveCard(frontmatter, cardFlags);\n\n // The consent cascade + resolved price (global < project < env < flag), with the\n // full-auto loosening gate. Its downgrade warnings go to stderr, not the receipt.\n const settings = await resolvePublishSettings({\n dataDir: ctx.dataDir,\n cwd,\n ...(args.mode !== undefined ? { flag: args.mode } : {}),\n env,\n });\n // The resolver's downgrade warnings, a mistyped env mode, and the one-line\n // explainer for an unconfigured mode: all stderr, all invisible to --json.\n writeModeNotices(\n ctx.io.stderr,\n settings,\n env,\n 'each publish asks you once. Set auto to publish clean scans automatically',\n );\n const priceAtomic = resolvePrice(args, frontmatter, settings.defaultPriceAtomic);\n\n // The scan runs in EVERY mode (D38): it gates the gate, it does not replace it.\n // Scan the whole file AND the derived card's text, so a secret reaches the same\n // gates whether it arrives in the body, in frontmatter, or via a card-authoring\n // flag (--provenance, --scope, …) — the card ships to the PUBLIC card, so a flag\n // secret must block exactly like an in-file one. Dedupe by check+excerpt so a\n // frontmatter value (present in both raw and the card) is not double-counted.\n // The scan context carries the source project's git remote slugs (offline FS\n // read, best-effort): a draft quoting its own project's repo/org warns as a\n // private-by-default reference (open-questions publishing-safety check-set).\n // Markers derive from the DRAFT's project, not the shell's cwd (review r5): a\n // file publish walks up from the file's own directory, so the process cwd is\n // unrelated to where the draft actually lives.\n const markerRoot = args.file !== undefined ? dirname(resolve(cwd, args.file)) : cwd;\n const scanContext: ScanContext = { projectMarkers: await deriveProjectMarkers(markerRoot) };\n const findings = dedupeFindings([\n ...scan(raw, scanContext),\n ...scan(cardScanText(card), scanContext),\n ]);\n const blocking = findings.filter((f) => f.severity === 'block');\n const warns = findings.filter((f) => f.severity === 'warn');\n\n const eligibility = localCardEligibility(card);\n const price = toMoney(priceAtomic);\n\n // A hard-block finding refuses in EVERY mode and is never clearable by --yes or\n // full-auto — the same non-bypassable posture as buy's price cap.\n if (blocking.length > 0) {\n throw new CliError('PUBLISH_BLOCKED', blockMessage(blocking), {\n fix: 'Remove the secret from the file (it is never masked away by --yes), then re-run.',\n details: {\n mode: settings.mode,\n findings: blocking.map(publicFinding),\n price: { atomic: price.atomic, usd: price.usd },\n },\n });\n }\n\n // --yes clears the soft findings and the review confirm alike.\n if (needsConfirmation(settings.mode, warns.length) && args.yes !== true) {\n throw new CliError('NEEDS_CONFIRMATION', confirmMessage(warns.length, price.usd), {\n fix: 'Review the findings, then re-run with --yes (or resolve the source and re-run).',\n details: {\n mode: settings.mode,\n price: { atomic: price.atomic, usd: price.usd },\n findings: warns.map(publicFinding),\n card: eligibility,\n target: { status, titlePreview: sanitizeForTerminal(title ?? '(untitled draft)') },\n },\n });\n }\n\n // Approved (or nothing to confirm): from here a wallet is required. The write\n // base URL is resolved through the shared settings seam and used for BOTH the\n // SIWX/session header domain and the POST host, so the two never diverge.\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 const auth = resolveWriteAuth({\n signer,\n baseUrl: runtime.baseUrl,\n dataDir: ctx.dataDir,\n // A publish always writes.\n scope: 'read+write',\n ...(deps.useSession !== undefined ? { useSession: deps.useSession } : {}),\n env,\n });\n\n const input: PublishInput = {\n ...(title !== undefined ? { title } : {}),\n bodyMd: body,\n ...(excerpt !== undefined ? { excerpt } : {}),\n ...(tags !== undefined ? { tags } : {}),\n priceAtomic,\n ...(handle !== undefined ? { handle } : {}),\n status,\n ...(card !== undefined ? { resource: card } : {}),\n // The attribution half of `--search-id`, and it follows the SAME rule the\n // local ledger already follows: a draft answers nobody, so it claims nobody's\n // demand either. Sending it on a draft put one demand signal on two posts —\n // no command promotes a draft, so reaching a public piece means a second\n // publish carrying the same id — with one of them possibly never shipping.\n ...(args.searchId !== undefined && status !== 'draft' ? { searchId: args.searchId } : {}),\n };\n\n const result = await publishPost(input, auth, {\n baseUrl: runtime.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n // A DRAFT answered nobody. It parks the piece privately, so it clears no parked\n // loop: the draft is still the pending answer, and the later real publish is\n // what resolves it.\n const parksPrivately = status === 'draft';\n\n let searchInfo: SearchReceipt | undefined;\n if (args.searchId !== undefined) {\n searchInfo = await closeNamedSearch(ctx, args.searchId, storedSearch, parksPrivately, prefill);\n }\n return receipt(result, runtime.baseUrl, searchInfo);\n}\n\n/**\n * What `--search-id` did, as a machine field. `--json` suppresses every stderr\n * note below, so without this an agent that named a search had no way to learn\n * whether its loop actually closed — the same silent-flag failure the draft note\n * fixes for a human.\n */\ninterface SearchReceipt {\n id: string;\n closed: boolean;\n /**\n * The loop had already been closed by something else (an `outcome` report) and\n * this publish took it over. Reported because it is the one case where naming a\n * search changed a record that was already there.\n */\n relinked?: boolean;\n /**\n * An earlier publish had already closed this loop, so this one attributed\n * nothing new. Distinct from `relinked`, which took a loop over from an\n * `outcome` report.\n */\n alreadyAnswered?: boolean;\n prefill: PrefillOutcome;\n}\n\n/**\n * What became of the searched question as a card entry. `none` covers both \"no\n * stored question\" and \"the draft named its own\", which are the cases where\n * nothing was expected; `dropped-too-long` is the one a caller has to be told.\n */\ntype PrefillOutcome = 'applied' | 'dropped-too-long' | 'none';\n\n/**\n * `--search-id` at the edge: a uuid, refused before any wallet touch so a typo\n * costs a message rather than a signing prompt.\n *\n * Checked against the shape the SERVER declares, not the looser local UUID_RE,\n * because this value is now sent on the publish body: an id that satisfied only\n * the local shape would be refused by the server as a 400, and that refusal\n * would arrive after the wallet signature rather than here.\n */\nfunction validateSearchId(args: PublishArgs): void {\n if (args.searchId === undefined) return;\n if (!SEARCH_ID_WIRE_RE.test(args.searchId)) {\n throw new CliError('USAGE', `Invalid --search-id: ${JSON.stringify(args.searchId)}.`, {\n fix: 'Pass the searchId from a prior `tenjin search` (a uuid).',\n });\n }\n}\n\n/**\n * Close the loop a `--search-id` file publish named, and say what happened in\n * both registers: a stderr line for a human, the returned receipt for `--json`.\n *\n * Two outcomes close nothing, and neither is an error — the piece is already\n * published, and bookkeeping never fails the write that ran. A `--draft` parks\n * privately and answers nobody, and an unknown id (aged out of the local store,\n * or from another machine) has no loop here to close.\n *\n * `closed: true` describes the LOOP, not this call: a search an `outcome` already\n * closed reports closed here too, which is what the caller is actually asking\n * about. It reports the OUTCOME of the write rather than the intent to write, so\n * a swallowed lock timeout comes back as `closed: false` and a stderr line\n * instead of a receipt claiming a close that never landed.\n *\n * A publish RELINKS a loop something else already closed. Closing as\n * `regenerated` is what an agent does when the answer is still being written, so\n * treating that as final is what severed seventeen demand signals from the two\n * pieces that answered them (tenjin-agent #161). Nothing is lost by taking the\n * loop over: the `outcome` report was already sent, and this only records who\n * ended up answering it.\n */\nasync function closeNamedSearch(\n ctx: CommandContext,\n searchId: string,\n stored: StoredSearch | null,\n parksPrivately: boolean,\n prefill: PrefillOutcome,\n): Promise<SearchReceipt> {\n const open = (reason: string): SearchReceipt => {\n ctx.io.stderr.write(`${reason}\\n`);\n return { id: searchId, closed: false, prefill };\n };\n if (parksPrivately) return open(`Saved as a draft, so search ${searchId} stays open.`);\n if (stored === null) {\n return open(`Published, but search ${searchId} is not in the local store.`);\n }\n const outcome = await markSearchResolved(ctx.dataDir, searchId, 'publish', undefined, {\n relink: true,\n });\n if (outcome === 'failed') {\n return open(\n `Published, but the local record for search ${searchId} could not be updated, so the open-loop reminder may repeat. Close it with \\`tenjin outcome --search-id ${searchId} --status used\\`.`,\n );\n }\n // `not-found` here means the entry was evicted between the read above and this\n // write: nothing was closed, so nothing claims to have been.\n if (outcome === 'not-found') {\n return open(`Published, but search ${searchId} is no longer in the local store.`);\n }\n if (outcome === 'relinked') return { id: searchId, closed: true, relinked: true, prefill };\n // A PRIOR publish already closed this loop. Reporting a fresh close here is a\n // receipt for something that did not happen, on the one path where a different\n // post already claims the demand this body is claiming again.\n if (outcome === 'already-resolved' && stored.resolved?.by === 'publish') {\n ctx.io.stderr.write(\n `Search ${searchId} was already answered by an earlier publish; this piece did not claim it.\\n`,\n );\n return { id: searchId, closed: true, alreadyAnswered: true, prefill };\n }\n return { id: searchId, closed: true, prefill };\n}\n\n/** The Markdown to publish. A missing path is USAGE before any wallet touch. */\nasync function readSource(args: PublishArgs): Promise<string> {\n if (args.file === undefined) {\n throw new CliError('USAGE', 'Nothing to publish.', {\n fix: 'Pass a Markdown file, e.g. `tenjin publish post.md`.',\n });\n }\n return readMarkdown(args.file);\n}\n\nfunction receipt(\n result: Awaited<ReturnType<typeof publishPost>>,\n baseUrl: string,\n searchInfo?: SearchReceipt,\n): CommandResult {\n const price = toMoney(result.priceAtomic);\n const missing = missingSentences(result.cacheEligibleMissing).map(sanitizeForTerminal);\n const cacheEligible = result.cacheEligible ?? false;\n const deskUrl = `${trimSlash(baseUrl)}/desk`;\n const title = sanitizeForTerminal(result.title);\n // status and url are server-sent open strings (posts-api declares both as bare\n // z.string()), so they get the same treatment as the title beside them: this\n // line is what an author reads to learn where their piece went.\n const human = [\n `Published ${title} (${sanitizeForTerminal(result.status)}) for ${price.usd} USD → ${sanitizeForTerminal(result.url)}`,\n cacheEligible\n ? 'Answer card is search-eligible.'\n : missing.length > 0\n ? `Answer card not search-eligible yet: ${missing.join(' ')}`\n : 'Published as a browse-only document (no answer card).',\n ...(searchInfo?.closed === true\n ? [\n searchInfo.relinked === true\n ? `Re-linked search ${searchInfo.id} to this piece; it had been closed without one.`\n : searchInfo.alreadyAnswered === true\n ? `Search ${searchInfo.id} was already answered by an earlier publish.`\n : `Closed the loop on search ${searchInfo.id}.`,\n ]\n : []),\n ...result.warnings.map((w) => `warning: ${sanitizeForTerminal(w)}`),\n ];\n return {\n data: {\n resourceId: result.resourceId,\n url: result.url,\n status: result.status,\n price,\n cacheEligible,\n missing,\n deskUrl,\n ...(searchInfo !== undefined ? { search: searchInfo } : {}),\n ...(result.warnings.length > 0 ? { warnings: result.warnings } : {}),\n },\n humanLines: human,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Field resolution.\n// ---------------------------------------------------------------------------\n\nasync function readMarkdown(file: string): Promise<string> {\n try {\n return 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 publish post.md`.',\n cause: err,\n });\n }\n}\n\nfunction resolveStatus(args: PublishArgs, frontmatter: Frontmatter): PublishStatus {\n if (args.draft === true) return 'draft';\n const fm = frontmatter.status;\n if (fm === undefined) return 'published';\n if (typeof fm !== 'string' || !(PUBLISH_STATUSES as readonly string[]).includes(fm)) {\n throw new CliError('USAGE', `Invalid status ${JSON.stringify(fm)} in frontmatter.`, {\n fix: 'Use status: draft | published | unlisted, or pass --draft.',\n });\n }\n return fm as PublishStatus;\n}\n\nfunction resolveTitle(frontmatter: Frontmatter, body: string): string | undefined {\n const fm = frontmatter.title;\n if (fm !== undefined) {\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', 'frontmatter title must be a single string.');\n }\n return fm.trim();\n }\n // Fall back to the first heading (level 1 preferred) so a plain `# Title` post\n // needs no frontmatter.\n const headings = headingOutline(body);\n const h1 = headings.find((h) => h.level === 1) ?? headings[0];\n return h1?.text;\n}\n\n/** The server's per-item bound on `questionsAnswered` (mirrored by deriveCard). */\nconst CARD_QUESTION_MAX = 200;\n\n/**\n * A stored question as a card entry, or undefined when it cannot be one.\n *\n * Dropped rather than cut over the item bound: a search question may run to the\n * server's 512, and a prefill that fails card validation would turn a publish\n * that was fine into a usage error the caller never asked for. Truncating is\n * worse still — half a question is a different question, and this text is what\n * the next searcher matches against.\n */\nfunction cardQuestion(raw: string): string | undefined {\n const question = sanitizeWireText(raw);\n return question.length > 0 && question.length <= CARD_QUESTION_MAX ? question : undefined;\n}\n\n/**\n * The public preview text: `--excerpt` over frontmatter `excerpt`, or undefined\n * to let the server derive one from the body's leading prose.\n *\n * The bound is checked HERE as well as in the request builder, because the\n * builder runs after a wallet signature has been collected and this is the edge:\n * a too-long excerpt should cost a message, not a signing prompt. Refused rather\n * than truncated — a silently cut preview is a different preview, and the whole\n * point of setting one is controlling exactly what a non-buyer reads. Sanitized\n * before the bound for the same reason the builder is: the stripped text is what\n * ships, so it is what the length has to describe.\n */\nfunction resolveExcerpt(args: PublishArgs, frontmatter: Frontmatter): string | undefined {\n const raw = args.excerpt ?? expectString(frontmatter, 'excerpt');\n if (raw === undefined) return undefined;\n const excerpt = sanitizeWireText(raw);\n if (excerpt.length > EXCERPT_MAX_LENGTH) {\n throw new CliError(\n 'USAGE',\n `excerpt must be at most ${EXCERPT_MAX_LENGTH} characters (got ${excerpt.length}).`,\n { fix: `Shorten it to ${EXCERPT_MAX_LENGTH} characters or fewer.` },\n );\n }\n return excerpt;\n}\n\nfunction resolveTags(frontmatter: Frontmatter): string[] | undefined {\n const fm = frontmatter.tags;\n if (fm === undefined) return undefined;\n if (typeof fm === 'string') return [fm];\n if (Array.isArray(fm)) return fm;\n throw new CliError('USAGE', 'frontmatter tags must be a list of strings.');\n}\n\nfunction expectString(frontmatter: Frontmatter, key: string): string | undefined {\n const fm = frontmatter[key];\n if (fm === undefined) return undefined;\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', `frontmatter ${key} must be a single string.`);\n }\n return fm;\n}\n\nfunction resolvePrice(args: PublishArgs, frontmatter: Frontmatter, defaultAtomic: string): string {\n if (args.price !== undefined) return parseUsdToAtomic(args.price);\n const fm = frontmatter.price;\n if (fm !== undefined) {\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', 'frontmatter price must be a decimal-USD string, e.g. \"0.10\".');\n }\n return parseUsdToAtomic(fm);\n }\n return defaultAtomic;\n}\n\nfunction cardFlagsFrom(args: PublishArgs): 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 derived card's free-text values as one newline-joined document, so the scan\n * covers card-flag input (which never touches the file) at the same severity as\n * the body. Empty when there is no card.\n */\nfunction cardScanText(card: ResourceCardInput | undefined): string {\n if (card === undefined) return '';\n const parts: string[] = [];\n const add = (v: string | undefined): void => {\n if (v !== undefined) parts.push(v);\n };\n add(card.scope);\n add(card.exclusions);\n add(card.provenanceSummary);\n add(card.methodologySummary);\n add(card.mediaType);\n add(card.maintenanceCadence);\n add(card.asOf);\n add(card.validUntil);\n add(card.estimatedPaidInputCost);\n if (card.questionsAnswered !== undefined) parts.push(...card.questionsAnswered);\n if (card.tasksSupported !== undefined) parts.push(...card.tasksSupported);\n if (card.appliesTo !== undefined) {\n for (const values of Object.values(card.appliesTo)) parts.push(...values);\n }\n return parts.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Finding + message shaping.\n// ---------------------------------------------------------------------------\n\nfunction blockMessage(blocking: ScanFinding[]): string {\n return `Publish blocked: the file contains ${describeFindings(blocking)}.`;\n}\n\nfunction confirmMessage(warnCount: number, priceUsd: string): string {\n return warnCount > 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I,KAAK,mBAAmB,OAAW,OAAM,KAAK,GAAG,KAAK,cAAc;AACxE,MAAI,KAAK,cAAc,QAAW;AAChC,eAAW,UAAU,OAAO,OAAO,KAAK,SAAS,EAAG,OAAM,KAAK,GAAG,MAAM;AAAA,EAC1E;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;AAMA,SAAS,aAAa,UAAiC;AACrD,SAAO,sCAAsC,iBAAiB,QAAQ,CAAC;AACzE;AAEA,SAAS,eAAe,WAAmB,UAA0B;AACnE,SAAO,YAAY,IACf,+BAA+B,SAAS,uBAAuB,QAAQ,MACvE,sCAAsC,QAAQ;AACpD;","names":[]}
|
|
@@ -6,10 +6,10 @@ import {
|
|
|
6
6
|
} from "./chunk-OWVVI4VQ.js";
|
|
7
7
|
import {
|
|
8
8
|
rateLimitError
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-FDUD3W5V.js";
|
|
10
10
|
import {
|
|
11
11
|
httpRequest
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-54AJIO3E.js";
|
|
13
13
|
import {
|
|
14
14
|
SLUG_RE,
|
|
15
15
|
UUID_RE
|
|
@@ -230,4 +230,4 @@ function readMessage(json) {
|
|
|
230
230
|
export {
|
|
231
231
|
fetchRead
|
|
232
232
|
};
|
|
233
|
-
//# sourceMappingURL=chunk-
|
|
233
|
+
//# sourceMappingURL=chunk-PCX2JQ2J.js.map
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
parseConfirmPolicy
|
|
4
|
-
} from "./chunk-FKSAUOJU.js";
|
|
5
2
|
import {
|
|
6
3
|
parseUsdToAtomic
|
|
7
4
|
} from "./chunk-736DW4V3.js";
|
|
5
|
+
import {
|
|
6
|
+
parseConfirmPolicy
|
|
7
|
+
} from "./chunk-UO22YNY4.js";
|
|
8
8
|
import {
|
|
9
9
|
PublishModeSchema,
|
|
10
10
|
SEND_MAX_UNSET,
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
resolvePublishDefaultPrice,
|
|
13
13
|
resolvePublishMode,
|
|
14
14
|
resolveSettings
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-LSWP7MU2.js";
|
|
16
16
|
import {
|
|
17
17
|
CliError,
|
|
18
18
|
external_exports
|
|
@@ -160,4 +160,4 @@ export {
|
|
|
160
160
|
resolvePublishSettings,
|
|
161
161
|
loadProjectConfig
|
|
162
162
|
};
|
|
163
|
-
//# sourceMappingURL=chunk-
|
|
163
|
+
//# sourceMappingURL=chunk-PKW3H26Z.js.map
|
|
@@ -3,17 +3,17 @@ import {
|
|
|
3
3
|
latestSearch,
|
|
4
4
|
loadSearches,
|
|
5
5
|
markSearchResolved
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-7NADDA2V.js";
|
|
7
7
|
import {
|
|
8
8
|
buildOutcomeItem,
|
|
9
9
|
postOutcomes
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-FDUD3W5V.js";
|
|
11
11
|
import {
|
|
12
12
|
sanitizeForTerminal
|
|
13
13
|
} from "./chunk-B676GPS2.js";
|
|
14
14
|
import {
|
|
15
15
|
resolveContextSettings
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-PKW3H26Z.js";
|
|
17
17
|
import {
|
|
18
18
|
isPaidPrice
|
|
19
19
|
} from "./chunk-736DW4V3.js";
|
|
@@ -122,4 +122,4 @@ function offeredSomethingToBuy(stored) {
|
|
|
122
122
|
export {
|
|
123
123
|
runOutcome
|
|
124
124
|
};
|
|
125
|
-
//# sourceMappingURL=chunk-
|
|
125
|
+
//# sourceMappingURL=chunk-PQZVDCCA.js.map
|