import { i as q } from "./prompts-DfcXHzAI.js";
import { h as P, G as v } from "./get-user-input-Cyvfzkny.js";
import * as u from "zod";
import { d as O, b as A, O as p, K as _, T as y } from "./shared-types-CIxCt9tj.js";
import { T as S, a as b, i as M } from "./tool-usage-meter-CBzE-MaZ.js";
import { b as C, T as I } from "./telemetry-Bf0GI6nJ.js";
import { a as f } from "./tool-tags-NGeoUHCI.js";
import { W as x } from "./workspace-object-CspubCq6.js";
import { U as R } from "./unknown-error-7JAvTvbU.js";
import { g } from "./spec-platform-361SGdHa.js";
var N = Object.defineProperty, W = Object.getOwnPropertyDescriptor, j = (o, s, e, a) => {
  for (var t = W(s, e), r = o.length - 1, i; r >= 0; r--)
    (i = o[r]) && (t = i(s, e, t) || t);
  return t && N(s, e, t), t;
};
const D = C(O.Tool, "Tool.Prework.Detailed"), w = {
  id: "prework",
  description: `Performs acceptance criteria testing prework for a feature design.
This tool stores prework analysis in context for later use in generating correctness properties.
For each criterion, you should determine if it's testable as a property, example, edge case, or not testable.

Use this tool BEFORE writing correctness properties in the design document.

The tool will store your analysis in context following this format:

X.Y Criteria Name
  Thoughts: step by step thoughts on whether or not this requirement is testable
  Testable: yes - property, yes - example, no, or edge-case

Example Usage:
- Analyze requirements: featureName="user-auth", preworkAnalysis="1.1 User login\\n  Thoughts: This is testable...\\n  Testable: yes - property"

Rules:
1. Complete the prework analysis BEFORE writing correctness properties in the design document
2. Each acceptance criterion must be analyzed for testability
3. Use the prework analysis to inform property generation`,
  schema: u.object({
    featureName: u.string().describe("The name of the feature being designed"),
    preworkAnalysis: u.string().describe("The complete prework analysis content following the required format")
  })
};
function G(o, s) {
  try {
    const e = g().parseMarkdownRequirements(s), a = o.split(".");
    if (a.length === 1) {
      const t = e.find((r) => r.number === a[0]);
      if (t)
        return {
          startLine: t.startLine,
          endLine: t.endLine,
          text: t.userStory?.text || t.text
        };
    } else if (a.length === 2) {
      const t = e.find((r) => r.number === a[0]);
      if (t) {
        const r = t.acceptanceCriteria.find((i) => i.number === a[1]);
        return r ? {
          startLine: r.startLine,
          endLine: r.endLine,
          text: r.text
        } : {
          startLine: t.startLine,
          endLine: t.endLine,
          text: t.userStory?.text || t.text
        };
      }
    }
  } catch {
  }
}
function z(o, s) {
  const e = [], a = o.split(`
`);
  let t = 1;
  for (let r = 0; r < a.length; r++) {
    const n = a[r].trim().match(/^(\d+\.\d+)\s+(.+)$/);
    if (n) {
      const c = n[1], m = n[2];
      let h = !1, k = "";
      for (let l = r + 1; l < Math.min(r + 5, a.length); l++) {
        const d = a[l].trim();
        if (d.startsWith("Thoughts:") && (k = d.replace("Thoughts:", "").trim()), d.match(/^Testable:\s*yes\s*-\s*property/i)) {
          h = !0;
          break;
        }
        if (d.match(/^\d+\.\d+\s+/))
          break;
      }
      if (h) {
        const l = s ? G(c, s) : void 0;
        e.push({
          number: t++,
          title: m,
          description: k || void 0,
          validates: `Requirements ${c}`,
          requirementRange: l ? { startLine: l.startLine, endLine: l.endLine } : void 0,
          requirementText: l?.text
        });
      }
    }
  }
  return e;
}
class T extends P {
  constructor() {
    super({
      id: w.id,
      description: w.description,
      schema: w.schema,
      tags: [f.SPEC, f.BUILTIN]
    });
  }
  async isBugfixSpec(s, e) {
    try {
      const a = `.kiro/specs/${e}/.config.kiro`, t = await x.fromRelativePath(s.execution.workspace, a), { content: r } = await s.execution.workspace.readFile({ file: t });
      return JSON.parse(r.text).specType === A.Bugfix;
    } catch {
      return !1;
    }
  }
  async handle({
    actionId: s,
    input: e,
    state: a,
    toolUse: t
  }) {
    return D.callWithTrace("handleInput", async () => {
      const r = S.start(b.Prework);
      a.execution.emit({
        type: "AgentExecutionAction",
        executionId: a.execution.executionId,
        actionId: s,
        actionState: p.Running,
        actionType: "preWork"
      });
      try {
        const { featureName: i, preworkAnalysis: n } = e;
        if (!i) throw new Error("Feature name is required");
        if (!n) throw new Error("Prework analysis is required");
        const m = await this.isBugfixSpec(a, i) ? "bugfix.md" : "requirements.md", h = `.kiro/specs/${i}/${m}`;
        let k;
        try {
          const d = await x.fromRelativePath(a.execution.workspace, h), { content: U } = await a.execution.workspace.readFile({ file: d });
          k = U.text;
        } catch {
        }
        const l = z(n, k);
        return a.execution.emit({
          type: "AgentExecutionAction",
          executionId: a.execution.executionId,
          actionId: s,
          actionState: p.Success,
          actionType: "preWork",
          output: {
            message: n,
            properties: l,
            requirementsPath: h
          }
        }), r.recordToolSuccess(), this.withSyncToolMessage(
          a,
          t,
          `Prework analysis completed for feature "${i}". The analysis has been stored in context and can now be used to generate correctness properties in the design document.`,
          !0
        );
      } catch (i) {
        const n = M(i), c = i instanceof Error ? i : new R(String(i));
        return n ? r.recordToolSuccess() : r.recordToolFault(c), a.execution.emit({
          type: "AgentExecutionAction",
          executionId: a.execution.executionId,
          errorMessage: n ? "" : c.message,
          actionId: s,
          actionState: n ? p.Canceled : p.Error,
          actionType: "preWork"
        }), this.withSyncToolMessage(a, t, `Error processing prework analysis: ${c.message}`, !1);
      }
    });
  }
}
j([
  I.Trace("Tool.Prework")
], T.prototype, "handle");
class H extends _ {
  /**
   * User facing error message.
   */
  get userFacingSessionErrorMessage() {
    return this.message;
  }
}
class E extends _ {
  constructor(s) {
    super(`Invalid PBT status: ${s}`);
  }
  /**
   * User facing error message.
   */
  get userFacingSessionErrorMessage() {
    return "Invalid PBT status parameters provided";
  }
}
var K = Object.defineProperty, J = Object.getOwnPropertyDescriptor, Q = (o, s, e, a) => {
  for (var t = J(s, e), r = o.length - 1, i; r >= 0; r--)
    (i = o[r]) && (t = i(s, e, t) || t);
  return t && K(s, e, t), t;
};
const V = u.enum([
  "passed",
  "failed",
  "not_run",
  "unexpected_pass"
]), F = {
  id: "updatePBTStatus",
  description: `This tool updates the status of Property-Based Test (PBT) tasks after running tests.

Tool instructions:
- Use this tool after executing a PBT task and running the property-based test
- Set status to "passed" when the test passes successfully
- Set status to "failed" when the test fails, and include the failing example from the PBT library
- Set status to "unexpected_pass" when a bugfix exploration test passes unexpectedly (indicating the bug may not be properly reproduced)
- Set status to "not_run" to reset the test status (rarely used)
- The failing example should be the exact output provided by the PBT library (e.g., QuickCheck, Hypothesis, fast-check)
- Only use this tool on tasks that are identified as PBT tasks in the task list`,
  tags: [f.SPEC, f.BUILTIN],
  schema: u.object({
    taskFilePath: u.string().describe(
      "The path to the `tasks.md` file for the spec/plan containing the PBT task. This path should be relative to the workspace root."
    ),
    taskId: u.string().describe(
      "The PBT task that you are updating the status of. It must match the text in the task file exactly. For example if the task file has the text `  - [ ] 2.1 Write property test for task creation`, you should call this tool with `2.1 Write property test for task creation`"
    ),
    status: V.describe(
      'The test execution status: "passed" if test succeeded, "failed" if test failed, "unexpected_pass" if test passed unexpectedly (for bugfix tests), "not_run" to reset status.'
    ),
    failingExample: u.string().optional().nullable().describe(
      'The failing example provided by the PBT library when the test fails. Include the exact counterexample that caused the test to fail. Required when status is "failed".'
    )
  })
};
class L extends P {
  static id = F.id;
  constructor() {
    super(F);
  }
  async handle(s) {
    const { state: e, actionId: a, input: t } = s, r = S.start(b.PBTStatus);
    try {
      g().validateFileAccess(t.taskFilePath), this.validateInput(t), this.emitEvent({
        state: e,
        actionId: a,
        actionState: p.PendingAction,
        taskId: t.taskId,
        taskListUri: t.taskFilePath,
        pbtStatus: t.status,
        failingExample: t.failingExample ?? void 0
      });
      const i = await x.fromRelativePath(e.execution.workspace, t.taskFilePath);
      await e.execution.workspace.updatePBTStatus({
        tasksPath: i,
        taskId: t.taskId,
        status: t.status,
        failingExample: t.failingExample ?? void 0,
        executionId: e.execution.executionId,
        chatSessionId: e.execution.chatSessionId
      }), this.emitEvent({
        state: e,
        actionId: a,
        actionState: p.Success,
        taskId: t.taskId,
        taskListUri: t.taskFilePath,
        pbtStatus: t.status,
        failingExample: t.failingExample ?? void 0
      }), r.recordToolSuccess();
      const n = this.formatStatusMessage(t.status, t.failingExample ?? void 0);
      return this.withSyncToolMessage(e, s.toolUse, `PBT task "${t.taskId}" ${n}`, !0);
    } catch (i) {
      return this.emitEvent({
        state: e,
        actionId: a,
        actionState: p.Error,
        taskId: t.taskId,
        taskListUri: t.taskFilePath,
        pbtStatus: t.status,
        failingExample: t.failingExample ?? void 0
      }), r.recordToolFault(i), this.withSyncToolMessage(
        e,
        s.toolUse,
        `Caught error updating PBT status: ${i instanceof Error ? i.message : String(i)}`,
        !1
      );
    }
  }
  validateInput(s) {
    if (s.status === "failed" && !s.failingExample)
      throw new E('Failing example is required when status is "failed"');
    if (s.status === "unexpected_pass" && !s.failingExample)
      throw new E('Failing example is required when status is "unexpected_pass"');
  }
  formatStatusMessage(s, e) {
    switch (s) {
      case "passed":
        return "test passed successfully";
      case "failed":
        return `test failed${e ? ` with example: ${e}` : ""}`;
      case "unexpected_pass":
        return "test passed unexpectedly (may not properly reproduce the bug)";
      case "not_run":
        return "test status reset to not run";
      default:
        return `status updated to ${s}`;
    }
  }
  emitEvent({
    state: s,
    actionId: e,
    actionState: a,
    ...t
  }) {
    s.execution.emit({
      type: "AgentExecutionAction",
      executionId: s.execution.executionId,
      actionId: e,
      actionState: a,
      actionType: "pbtStatus",
      ...t
    });
  }
}
Q([
  I.Trace("Tool.PBTStatus")
], L.prototype, "handle");
var X = Object.defineProperty, Y = Object.getOwnPropertyDescriptor, Z = (o, s, e, a) => {
  for (var t = Y(s, e), r = o.length - 1, i; r >= 0; r--)
    (i = o[r]) && (t = i(s, e, t) || t);
  return t && X(s, e, t), t;
};
const B = {
  id: "taskStatus",
  description: `This tool updates the status of tasks from the task list in the user's specs.

Tool instructions:
- Use this tool whenever you are executing a task from a spec/plan
- Always set the task status to in progress before you start making changes
- Always set the task status to complete when the task is fully complete
- When executing a task with sub-tasks, always start with the sub tasks. When all sub-tasks are complete, update the parent task to complete as well.
- If the model is not implementing an optional sub-task, then the sub-task should not be marked as completed.
- Never try to use this tool with tasks that are not defined in the spec/plan`,
  tags: [f.SPEC, f.BUILTIN],
  schema: u.object({
    taskFilePath: u.string().describe(
      "The path to the `tasks.md` file for the spec/plan you are executing. This path should be relative to the workspace root."
    ),
    task: u.string().describe(
      "The task that you are updating the status of. It must match the text in the task file exactly. For example if the task file has the text `  - [-] 3.2 This is my task`, you should call this tool with `3.2 This is my task`"
    ),
    status: u.nativeEnum(y).describe("The status you are setting the task to.")
  })
};
class $ extends P {
  static id = B.id;
  constructor() {
    super(B);
  }
  async handle(s) {
    let { state: e } = s;
    const { actionId: a, input: t } = s, r = S.start(b.TaskStatus);
    try {
      g().validateFileAccess(t.taskFilePath), this.emitEvent({
        state: e,
        actionId: a,
        actionState: p.PendingAction,
        taskId: t.task,
        taskListUri: t.taskFilePath,
        taskStatus: t.status
      });
      const i = await x.fromRelativePath(e.execution.workspace, t.taskFilePath), n = t.task, c = await e.execution.workspace.validateTaskStatusChange({
        tasksPath: i,
        taskId: n,
        newStatus: t.status
      });
      if (!c.valid)
        throw new H(c.reason || "Cannot change task status");
      const m = await e.execution.workspace.getTaskMetadata({
        tasksPath: i,
        taskId: n
      });
      let h = "";
      return c.warnings && c.warnings.length > 0 && (h = ` Warning: ${c.warnings.join(" ")}`), await e.execution.workspace.updateTaskStatus({
        tasksPath: await x.fromRelativePath(e.execution.workspace, t.taskFilePath),
        status: t.status,
        executionId: e.execution.executionId,
        chatSessionId: e.execution.chatSessionId,
        taskId: t.task
      }), this.emitEvent({
        state: e,
        actionId: a,
        actionState: p.Success,
        taskId: t.task,
        taskListUri: t.taskFilePath,
        taskStatus: t.status
      }), r.recordToolSuccess(), t.status === y.InProgress && (e = await g().runPreTaskExecutionHooks(
        t.task,
        t.taskFilePath,
        e,
        s.toolUse?.requestMessageId
      )), t.status === y.Completed && (e = await g().runPostTaskExecutionHooks(
        t.task,
        t.taskFilePath,
        e,
        s.toolUse?.requestMessageId
      )), this.withSyncToolMessage(
        {
          ...e,
          specTaskId: m.isLeaf ? t.task : void 0
        },
        s.toolUse,
        `Task "${t.task}" set to status "${t.status}"${h}`,
        !0
      );
    } catch (i) {
      return this.emitEvent({
        state: e,
        actionId: a,
        actionState: p.Error,
        taskId: t.task,
        taskListUri: t.taskFilePath,
        taskStatus: t.status
      }), r.recordToolFault(i), this.withSyncToolMessage(
        e,
        s.toolUse,
        `Caught error updating task status: ${i instanceof Error ? i.message : String(i)}`,
        !1
      );
    }
  }
  emitEvent({
    state: s,
    actionId: e,
    actionState: a,
    ...t
  }) {
    s.execution.emit({
      type: "AgentExecutionAction",
      executionId: s.execution.executionId,
      actionId: e,
      actionState: a,
      actionType: "taskStatus",
      ...t
    });
  }
}
Z([
  I.Trace("Tool.TaskStatus")
], $.prototype, "handle");
const ut = (o) => q(o) ? [new v(), new T()] : [new v(), new $(), new L(), new T()];
export {
  E as I,
  H as T,
  $ as U,
  ut as g
};
//# sourceMappingURL=index-BNsRGrU_.js.map
