diff --git a/src/cli/parser.test.ts b/src/cli/parser.test.ts index 57b640d..1d5630c 100644 --- a/src/cli/parser.test.ts +++ b/src/cli/parser.test.ts @@ -157,6 +157,26 @@ describe("option helpers", () => { expect(() => parseHoseExpireSeconds("0s")).toThrow("必须为大于 0 的有效时长"); expect(() => parseHoseExpireSeconds("invalid")).toThrow("必须为有效时长"); }); + + test("both --expire flags read a unitless literal the same way", () => { + // Regression: the two parsers used to each carry their own copy of the + // unitless heuristic, so `--expire 300` meant 5 minutes on one path and + // clamped to 1 hour on the other purely by implementation accident. + for (const literal of [300, "300", 86400, "86400", 7200, "7200"]) { + const hours = parseDelegationExpireHours(literal); + const seconds = parseHoseExpireSeconds(literal); + const unitlessSeconds = typeof literal === "number" ? literal : Number(literal); + expect(seconds).toBe(unitlessSeconds); + // Delegation floors to whole hours and never drops below 1h. + expect(hours).toBe(Math.max(Math.floor(seconds / 3600), 1)); + } + + // A small unitless value is hours on both paths. + expect(parseDelegationExpireHours("24")).toBe(24); + expect(parseHoseExpireSeconds("24")).toBe(86_400); + expect(parseDelegationExpireHours(2)).toBe(2); + expect(parseHoseExpireSeconds(2)).toBe(7200); + }); }); describe("flag registry cross-check", () => { diff --git a/src/cli/parser.ts b/src/cli/parser.ts index cd08e17..5ed41f7 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -1,6 +1,7 @@ import type { WebhookMode } from "../domains/seal/types.js"; import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js"; import type { ParsedArgs } from "./types.js"; +import { type DurationToken, expireSeconds, tokenizeDuration } from "../core/duration.js"; import { usageError } from "./errors.js"; /** @@ -437,6 +438,42 @@ export function materialPackFilePolicyOptions( }; } +/** + * Read an `--expire` literal through the shared tokenizer, raising the two + * usage errors both link flags share. The format hint differs per flag only in + * which example it recommends. + */ +function readExpireToken( + value: string | boolean | number, + options: { formatHint: string; unitlessHint?: string } +): DurationToken { + if (typeof value === "number") { + if (!Number.isFinite(value) || value <= 0) { + throw usageError( + `Invalid --expire: ${value}。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。` + ); + } + const token = tokenizeDuration(value); + if (!token) throw usageError(`Invalid --expire: ${value}。`); + return token; + } + + if (typeof value !== "string") { + throw usageError(`Invalid --expire: ${String(value)}。`); + } + + const token = tokenizeDuration(value); + if (!token) { + throw usageError(`Invalid --expire: '${value}'。必须为有效时长格式${options.formatHint}`); + } + if (token.value <= 0) { + throw usageError( + `Invalid --expire: '${value}'。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。` + ); + } + return token; +} + export function parseDelegationExpireHours( value: string | boolean | number | undefined, defaultHours = 24 @@ -444,80 +481,30 @@ export function parseDelegationExpireHours( if (value === undefined || value === null || value === "") { return defaultHours; } - let rawHours: number; - let isFractionalOrTruncated = false; - if (typeof value === "number") { - if (!Number.isFinite(value) || value <= 0) { - throw usageError(`Invalid --expire: ${value}。必须为大于 0 的有效时长,推荐使用 '7d' 或 '24h'。`); - } - if (value > 168) { - rawHours = value / 3600; - if (value % 3600 !== 0) isFractionalOrTruncated = true; - } else { - rawHours = value; - if (!Number.isInteger(value)) isFractionalOrTruncated = true; - } - } else if (typeof value === "string") { - const trimmed = value.trim(); - const match = trimmed.match( - /^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i - ); - if (!match || !match[1]) { - throw usageError( - `Invalid --expire: '${value}'。必须为有效时长格式,推荐使用 '7d' 或 '24h'(支持 d/h/m/s 及秒数)。` - ); - } - const val = parseFloat(match[1]); - if (!Number.isFinite(val) || val <= 0) { - throw usageError(`Invalid --expire: '${value}'。必须为大于 0 的有效时长,推荐使用 '7d' 或 '24h'。`); - } - const unit = (match[2] ?? "").toLowerCase(); - - if (!unit) { - if (val > 168) { - rawHours = val / 3600; - if (val % 3600 !== 0) isFractionalOrTruncated = true; - } else { - rawHours = val; - if (!Number.isInteger(val)) isFractionalOrTruncated = true; - } - } else if (unit.startsWith("d")) { - rawHours = val * 24; - if (!Number.isInteger(rawHours)) isFractionalOrTruncated = true; - } else if (unit.startsWith("h")) { - rawHours = val; - if (!Number.isInteger(rawHours)) isFractionalOrTruncated = true; - } else if (unit.startsWith("m")) { - rawHours = val / 60; - if (val % 60 !== 0) isFractionalOrTruncated = true; - } else if (unit.startsWith("s")) { - rawHours = val / 3600; - if (val % 3600 !== 0) isFractionalOrTruncated = true; - } else { - rawHours = val; - } - } else { - throw usageError(`Invalid --expire: ${String(value)}。`); - } + const token = readExpireToken(value, { + formatHint: ",推荐使用 '7d' 或 '24h'(支持 d/h/m/s 及秒数)", + unitlessHint: ",推荐使用 '7d' 或 '24h'" + }); + // Seal delegation links are hourly and capped at 7 days. + const rawHours = expireSeconds(token) / 3600; if (rawHours > 168) { throw usageError( `Invalid --expire: 计算得 ${rawHours > 168.1 ? Math.floor(rawHours) : rawHours} 小时。Seal delegation 授权有效期最多为 7 天 (168h)。建议使用 --expire 7d。` ); } - let finalHours = Math.floor(rawHours); + const finalHours = Math.floor(rawHours); if (finalHours < 1) { - finalHours = 1; console.error( `👉 提示: Seal 协助链接按整小时生效(最少 1 小时),输入值 ${String(value)} 已自动保底设置为 1 小时 (1h)。建议后续使用 --expire 1h。` ); - return finalHours; + return 1; } - if (isFractionalOrTruncated) { + if (!Number.isInteger(rawHours)) { console.error( `👉 提示: Seal 协助链接按整小时生效,输入值 ${String(value)} 已自动向下取整为 ${finalHours} 小时 (${finalHours}h)。建议后续使用 --expire ${finalHours}h 或 --expire 7d。` ); @@ -533,59 +520,19 @@ export function parseHoseExpireSeconds( if (value === undefined || value === null || value === "") { return defaultSeconds; } - let seconds: number; - if (typeof value === "number") { - if (!Number.isFinite(value) || value <= 0) { - throw usageError(`Invalid --expire: ${value}。必须为大于 0 的有效时长。`); - } - if (value <= 168) { - seconds = Math.round(value * 3600); - console.error( - `👉 提示: 检测到未加单位的数值 ${value},已按 ${value} 小时 (${seconds}s) 自动换算。建议明确使用 --expire ${value}h。` - ); - } else { - seconds = Math.round(value); - } - } else if (typeof value === "string") { - const trimmed = value.trim(); - const match = trimmed.match( - /^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i - ); - if (!match || !match[1]) { - throw usageError( - `Invalid --expire: '${value}'。必须为有效时长,推荐使用 '7d' 或 '2h'(支持 d/h/m/s 及秒数)。` - ); - } - const val = parseFloat(match[1]); - if (!Number.isFinite(val) || val <= 0) { - throw usageError(`Invalid --expire: '${value}'。必须为大于 0 的有效时长。`); - } - const unit = (match[2] ?? "").toLowerCase(); - if (!unit) { - if (val <= 168) { - seconds = Math.round(val * 3600); - console.error( - `👉 提示: 检测到未加单位的数值 ${value},已按 ${val} 小时 (${seconds}s) 自动换算。建议明确使用 --expire ${val}h。` - ); - } else { - seconds = Math.round(val); - } - } else if (unit.startsWith("d")) { - seconds = Math.round(val * 86400); - } else if (unit.startsWith("h")) { - seconds = Math.round(val * 3600); - } else if (unit.startsWith("m")) { - seconds = Math.round(val * 60); - } else if (unit.startsWith("s")) { - seconds = Math.round(val); - } else { - seconds = Math.round(val); - } - } else { - throw usageError(`Invalid --expire: ${String(value)}。`); + const token = readExpireToken(value, { + formatHint: ",推荐使用 '7d' 或 '2h'(支持 d/h/m/s 及秒数)" + }); + + // A bare number is ambiguous: <=168 is read as hours, larger as seconds. + if (token.unit === undefined && token.value <= 168) { + console.error( + `👉 提示: 检测到未加单位的数值 ${token.value},已按 ${token.value} 小时 (${Math.round(token.value * 3600)}s) 自动换算。建议明确使用 --expire ${token.value}h。` + ); } + const seconds = Math.round(expireSeconds(token)); if (seconds <= 0) { throw usageError(`Invalid --expire: 计算得 ${seconds} 秒。必须为大于 0 的有效时长。`); } diff --git a/src/core/duration.test.ts b/src/core/duration.test.ts new file mode 100644 index 0000000..3651060 --- /dev/null +++ b/src/core/duration.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, test } from "bun:test"; +import { + durationSeconds, + expireSeconds, + parseDurationMs, + tokenizeDuration +} from "./duration.js"; + +describe("tokenizeDuration", () => { + test("splits magnitude from unit and accepts every alias", () => { + expect(tokenizeDuration("7d")).toEqual({ value: 7, unit: "d" }); + expect(tokenizeDuration("24h")).toEqual({ value: 24, unit: "h" }); + expect(tokenizeDuration("90m")).toEqual({ value: 90, unit: "m" }); + expect(tokenizeDuration("7200s")).toEqual({ value: 7200, unit: "s" }); + expect(tokenizeDuration("1.5h")).toEqual({ value: 1.5, unit: "h" }); + expect(tokenizeDuration("2 hours")).toEqual({ value: 2, unit: "h" }); + expect(tokenizeDuration("500ms")).toEqual({ value: 500, unit: "ms" }); + expect(tokenizeDuration(" 300 ")).toEqual({ value: 300, unit: undefined }); + expect(tokenizeDuration(168)).toEqual({ value: 168, unit: undefined }); + }); + + test("rejects unparseable input instead of guessing", () => { + expect(tokenizeDuration("invalid")).toBeUndefined(); + expect(tokenizeDuration("")).toBeUndefined(); + expect(tokenizeDuration("-5m")).toBeUndefined(); + expect(tokenizeDuration("5parsecs")).toBeUndefined(); + expect(tokenizeDuration(Number.NaN)).toBeUndefined(); + expect(tokenizeDuration(true as unknown as string)).toBeUndefined(); + }); +}); + +describe("expireSeconds", () => { + test("reads a unitless number at most 168 as hours and a larger one as seconds", () => { + // Both --expire paths used to reimplement this rule separately, and they + // disagreed at the boundary; 300 now means 5 minutes everywhere. + expect(expireSeconds({ value: 168, unit: undefined })).toBe(168 * 3600); + expect(expireSeconds({ value: 169, unit: undefined })).toBe(169); + expect(expireSeconds({ value: 300, unit: undefined })).toBe(300); + expect(expireSeconds({ value: 86400, unit: undefined })).toBe(86_400); + }); + + test("converts explicit units regardless of magnitude", () => { + expect(expireSeconds({ value: 7, unit: "d" })).toBe(604_800); + expect(expireSeconds({ value: 7200, unit: "s" })).toBe(7200); + expect(expireSeconds({ value: 30, unit: "m" })).toBe(1800); + }); +}); + +describe("durationSeconds", () => { + test("uses the caller's unitless policy when none is written", () => { + expect(durationSeconds({ value: 5, unit: undefined }, "s")).toBe(5); + expect(durationSeconds({ value: 5, unit: undefined }, "h")).toBe(18_000); + expect(durationSeconds({ value: 5, unit: "ms" }, "h")).toBe(0.005); + }); +}); + +describe("parseDurationMs", () => { + test("converts simulation windows to milliseconds", () => { + expect(parseDurationMs("2s")).toBe(2000); + expect(parseDurationMs("10m")).toBe(600_000); + expect(parseDurationMs("5m")).toBe(300_000); + expect(parseDurationMs("500ms")).toBe(500); + expect(parseDurationMs("1h")).toBe(3_600_000); + expect(parseDurationMs("1d")).toBe(86_400_000); + }); + + test("reads unitless input as seconds, matching the flag's defaults", () => { + expect(parseDurationMs("30")).toBe(30_000); + }); + + test("falls back rather than failing a batch over a bad poll interval", () => { + expect(parseDurationMs("soon")).toBe(600_000); + expect(parseDurationMs("soon", 1000)).toBe(1000); + }); +}); diff --git a/src/core/duration.ts b/src/core/duration.ts new file mode 100644 index 0000000..503f6b3 --- /dev/null +++ b/src/core/duration.ts @@ -0,0 +1,118 @@ +/** + * Duration tokenizing shared by every flag that accepts `7d` / `1.5h` / `300`. + * + * The tokenizer owns exactly one job: turning the written form into a magnitude + * plus a canonical unit. Interpretation stays with each caller, because the + * three consumers genuinely disagree — Seal delegation links take whole hours + * in 1..168, Hose assistance links take seconds, simulation windows take + * milliseconds. Sharing the grammar (and the unitless heuristic) is what stops + * `--expire 300` from parsing two different ways in two files. + */ + +export type DurationUnit = "ms" | "s" | "m" | "h" | "d"; + +export interface DurationToken { + /** The magnitude exactly as written, before any unit conversion. */ + value: number; + /** `undefined` when the input carried no unit, e.g. `300`. */ + unit: DurationUnit | undefined; +} + +const UNIT_ALIASES: Record = { + ms: "ms", + s: "s", + sec: "s", + secs: "s", + second: "s", + seconds: "s", + m: "m", + min: "m", + mins: "m", + minute: "m", + minutes: "m", + h: "h", + hr: "h", + hrs: "h", + hour: "h", + hours: "h", + d: "d", + day: "d", + days: "d" +}; + +const DURATION_PATTERN = /^(\d+(?:\.\d+)?)\s*([a-z]+)?$/i; + +/** + * Parse a duration literal. Returns `undefined` when the input cannot be read + * at all — callers decide whether that is a usage error or a default. + * + * A unitless number keeps whatever magnitude it had; pair it with + * {@link expireSeconds} or an explicit `unitless` argument to resolve it. + */ +export function tokenizeDuration(value: string | number): DurationToken | undefined { + if (typeof value === "number") { + return Number.isFinite(value) ? { value, unit: undefined } : undefined; + } + if (typeof value !== "string") { + return undefined; + } + + const match = value.trim().match(DURATION_PATTERN); + if (!match || !match[1]) { + return undefined; + } + + const rawUnit = match[2]?.toLowerCase(); + if (!rawUnit) { + return { value: parseFloat(match[1]), unit: undefined }; + } + + const unit = UNIT_ALIASES[rawUnit]; + if (!unit) { + return undefined; + } + return { value: parseFloat(match[1]), unit }; +} + +/** Convert a token to seconds, resolving a unitless value as `unitless`. */ +export function durationSeconds(token: DurationToken, unitless: DurationUnit): number { + switch (token.unit ?? unitless) { + case "ms": + return token.value / 1000; + case "m": + return token.value * 60; + case "h": + return token.value * 3600; + case "d": + return token.value * 86400; + case "s": + default: + return token.value; + } +} + +/** + * Unitless `--expire` heuristic shared by the Seal and Hose link flags: + * a bare number at most 168 reads as hours (7 days of them), a larger one + * reads as seconds. Without this, `--expire 300` would mean 300 hours on one + * path and 5 minutes on another. + */ +export function expireSeconds(token: DurationToken): number { + return durationSeconds(token, token.value <= 168 ? "h" : "s"); +} + +/** Default used by {@link parseDurationMs} when the literal is unreadable. */ +export const DEFAULT_DURATION_MS = 600_000; + +/** + * Simulation windows and poll intervals: milliseconds, unitless input read as + * seconds, and an unreadable literal falls back to the default instead of + * failing the call — a poll interval is not worth aborting a batch over. + */ +export function parseDurationMs(duration: string, fallbackMs = DEFAULT_DURATION_MS): number { + const token = tokenizeDuration(duration); + if (!token || token.value < 0) { + return fallbackMs; + } + return Math.round(durationSeconds(token, "s") * 1000); +} diff --git a/src/domains/seal/capabilities/helpers.ts b/src/domains/seal/capabilities/helpers.ts index 24f1fd5..a52d552 100644 --- a/src/domains/seal/capabilities/helpers.ts +++ b/src/domains/seal/capabilities/helpers.ts @@ -254,21 +254,6 @@ export type SimulationBatchCreateInput = { rawParams?: Record; }; -export function parseDurationMs(duration: string): number { - const match = duration.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i); - if (!match || !match[1]) return 600000; - const val = parseFloat(match[1]); - const unit = (match[2] ?? "s").toLowerCase(); - switch (unit) { - case "ms": return val; - case "s": return val * 1000; - case "m": return val * 60 * 1000; - case "h": return val * 3600 * 1000; - case "d": return val * 86400 * 1000; - default: return val * 1000; - } -} - export function redactIntegrationSecrets(integration: Record) { return Object.fromEntries( Object.entries(integration).map(([key, value]) => [ diff --git a/src/domains/seal/capabilities/simulation.ts b/src/domains/seal/capabilities/simulation.ts index a07970e..25585c4 100644 --- a/src/domains/seal/capabilities/simulation.ts +++ b/src/domains/seal/capabilities/simulation.ts @@ -6,9 +6,9 @@ import { type SimulationBatch } from "../types.js"; import * as helpers from "./helpers.js"; +import { parseDurationMs } from "../../../core/duration.js"; const { - parseDurationMs, buildSimulationBatchParams, summarizeSimulationBatch, summarizeApprovalRun,