/**
 * SF Bootstrap — Ask-User Gate
 *
 * Runtime safety net for `ask_user_questions` calls in autonomous mode.
 * The system prompt already forbids these calls when canAskUser=false, but
 * this gate provides a second line of defence at the tool layer.
 *
 * Usage: call `gateAskUserQuestions(payload)` inside the tool handler for
 * `ask_user_questions`. If the return value has `allow: false`, return the
 * `reason` string as the tool's error response so the agent re-plans.
 *
 * // TODO: integrate into ask_user_questions tool registry once the workflow tools
 * //        handler and any coding-agent tool registration path surface a
 * //        pre-invoke hook point. Current wiring entry point candidates:
 * //          - packages/coding-agent/src/modes/rpc/rpc-mode.ts (tool dispatch)
 * //          - src/resources/extensions/sf/workflow-tools.js (structured question support)
 */
import { isAutoActive, isCanAskUser } from "../auto.js";
import { logWarning } from "../workflow-logger.js";
/**
 * Gate for `ask_user_questions` tool calls. In autonomous mode
 * (`isAutoActive() && !isCanAskUser()`) the call is blocked with a structured
 * rejection message the agent can read and act on (escalate to Tier 1/2).
 *
 * In manual/assisted mode (`canAskUser=true`) all calls pass through.
 *
 * @param questionPayload - Raw tool-call input; used only for diagnostic logging.
 * @returns `{ allow: true }` to permit the call, or `{ allow: false, reason }` to block.
 */
export function gateAskUserQuestions(questionPayload) {
	if (!isAutoActive() || isCanAskUser()) {
		return { allow: true };
	}
	const reason =
		"ask_user_questions is forbidden in autonomous mode. " +
		"Resolve via Tier 1 (code/sift/source files/.sf/KNOWLEDGE.md/.sf/DECISIONS.md) " +
		"or Tier 2 (WebSearch/WebFetch/Context7). " +
		"If the question is genuinely user-only (a preference, intent, design choice), " +
		"exit with a structured blocker message naming the unresolved ambiguity instead of calling this tool.";
	logWarning("safety", "blocked ask_user_questions in autonomous mode", {
		payload:
			typeof questionPayload === "object"
				? JSON.stringify(questionPayload).slice(0, 200)
				: String(questionPayload),
	});
	return { allow: false, reason };
}
