### Install Project Dependencies Source: https://github.com/kirodotdev/kiro/blob/main/scripts/README.md Run this command to install all necessary project dependencies. ```bash npm install ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/integration-guide.md Navigate to the scripts directory and install necessary Node.js dependencies using npm. ```bash cd scripts npm install ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/README.md Navigate to the scripts directory, install project dependencies, and compile TypeScript files into the distribution folder. ```bash cd scripts npm install # Install dependencies npm run build # Compile TypeScript → dist/ ``` -------------------------------- ### Workflow Summary Example Source: https://github.com/kirodotdev/kiro/blob/main/docs/STALE_ISSUE_CLOSING_EXPLAINED.md Example of the summary generated by the stale issue closing workflow after each run. ```markdown ## Stale Issue Closer Summary Status: success Run time: 2026-01-14 00:00:00 UTC ``` -------------------------------- ### Workflow Logs Example Source: https://github.com/kirodotdev/kiro/blob/main/docs/STALE_ISSUE_CLOSING_EXPLAINED.md Example output from the stale issue closing workflow, showing which issues were processed, closed, or skipped. ```text === Closing Stale Issues === Repository: owner/repo Found 5 open issue(s) with pending-response label Processing issue #123: App crashes on startup Inactive for: 8.2 days ✓ Closed issue #123 due to inactivity Processing issue #456: Login fails Inactive for: 3.1 days Skipped: not inactive long enough (needs 7 days) === Summary === Closed: 1 Skipped: 4 Total: 5 ``` -------------------------------- ### Output Summary Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-workflows.md Example of the summary output printed to the console after the script execution. ```text === Closing Duplicate Issues === Repository: kirodotdev/kiro Found 15 open issue(s) with duplicate label Processing issue #42: ... Label age: 3.5 days ✓ Closed issue #42 as duplicate === Summary === Closed: 10 Relabeled: 3 Skipped: 2 Total: 15 ``` -------------------------------- ### Usage Example: Setting Environment Variables and Running Script Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-workflows.md Demonstrates how to set the required environment variables and execute the close_duplicates.js script. ```bash export REPOSITORY_OWNER="kirodotdev" export REPOSITORY_NAME="kiro" export GITHUB_TOKEN="ghp_..." node dist/close_duplicates.js ``` -------------------------------- ### Usage Example: Environment Variables and Execution Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-workflows.md Demonstrates how to set the required environment variables and execute the 'close_stale.ts' script using Node.js. ```bash export REPOSITORY_OWNER="kirodotdev" export REPOSITORY_NAME="kiro" export GITHUB_TOKEN="ghp_..." node dist/close_stale.ts ``` -------------------------------- ### LabelTaxonomy Usage Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/types.md Shows practical usage of the LabelTaxonomy class, including getting all labels, checking category counts, converting to a dictionary, and validating labels. ```typescript import { LabelTaxonomy } from "./data_models.js"; const taxonomy = new LabelTaxonomy(); // Get all labels const allLabels = taxonomy.getAllLabels(); console.log(`Total: ${allLabels.length}`); // 40 // Check specific category console.log(`Components: ${taxonomy.feature_component.length}`); // 21 // Convert to dict for AI prompts const dict = taxonomy.toDict(); const prompt = `Choose from: ${JSON.stringify(dict)}`; // Validate a label const isValid = allLabels.includes("cli"); console.log(`"cli" is valid: ${isValid}`); // true ``` -------------------------------- ### LabelTaxonomy toDict() Method Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/types.md Demonstrates converting the LabelTaxonomy instance into a dictionary format, suitable for AI prompts. ```typescript const dict = taxonomy.toDict(); // { // "feature_component": ["auth", "cli", "chat", ...], // "os_specific": ["os: linux", "os: mac", "os: windows"], // "theme": ["theme:performance", ...], // "workflow": ["pending-triage", "duplicate", ...], // "special": ["Autonomous agent", ...] // } ``` -------------------------------- ### RetryWithBackoff Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/types.md Demonstrates how to use the retryWithBackoff function with default and custom RetryOptions. Ensure the retryWithBackoff function is imported. ```typescript import { retryWithBackoff } from "./retry_utils.js"; // Use defaults const result1 = await retryWithBackoff(myAsyncFunction); // Custom options const result2 = await retryWithBackoff(myAsyncFunction, { maxRetries: 5, baseDelay: 500, maxDelay: 10000, retryableErrors: ["Timeout", "ServiceUnavailable"] }); ``` -------------------------------- ### Batch Progress Output Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-utilities.md This shows the expected console output when `processBatch` is used with logging enabled, indicating the progress of batch processing and the delays between them. ```text Processing batch 1/5 (10 items) Waiting 2000ms before next batch... Processing batch 2/5 (10 items) Waiting 2000ms before next batch... ``` -------------------------------- ### IssueData Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/types.md An example of how to instantiate the IssueData interface with sample issue details. ```typescript const issue: IssueData = { number: 42, title: "Add SSH key management to CLI", body: "Users need ability to manage SSH keys for remote development...", created_at: new Date("2026-06-20T10:30:00Z"), updated_at: new Date("2026-06-24T15:45:00Z"), labels: ["cli", "feature", "pending-triage"], url: "https://github.com/kirodotdev/kiro/issues/42", state: "open" }; ``` -------------------------------- ### LabelTaxonomy getAllLabels() Method Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/types.md Illustrates retrieving a flat array of all valid labels managed by the LabelTaxonomy. ```typescript const allLabels = taxonomy.getAllLabels(); // ["auth", "autocomplete", "chat", "cli", ..., "duplicate", "question", ...] // Total: 40 labels ``` -------------------------------- ### Usage Example for Workflow Summary Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-utilities.md Demonstrates how to use `createSummary` and `logError` to generate a GitHub Actions workflow summary. It includes setting up the `WorkflowSummary` object, performing work within a try-catch block, logging errors, and finally creating the summary. ```typescript import { createSummary, logError, WorkflowSummary } from "./workflow_summary.js"; const summary: WorkflowSummary = { success: true, totalProcessed: 1, successCount: 1, failureCount: 0, skippedCount: 0, errors: [] }; try { // Do work } catch (error) { logError(summary.errors, "classification", error, 42); summary.success = false; summary.failureCount++; } createSummary(summary); ``` -------------------------------- ### Usage Example for classifyIssue Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-classification.md Demonstrates how to import and use the `classifyIssue` function. It shows how to initialize the taxonomy, call the function, and handle potential errors or display the classification results. ```typescript import { classifyIssue } from "./bedrock_classifier.js"; import { LabelTaxonomy } from "./data_models.js"; const taxonomy = new LabelTaxonomy(); const result = await classifyIssue( "Add SSH key management to Kiro CLI", "Users need to securely manage SSH keys for remote development...", taxonomy ); if (result.error) { console.error("Classification failed:", result.error); } else { console.log("Recommended labels:", result.recommended_labels); console.log("Confidence:", result.confidence_scores); console.log("Reasoning:", result.reasoning); } ``` -------------------------------- ### Usage Example for getFallbackComment Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-comments.md Demonstrates how to import and use the getFallbackComment function to obtain and log a fallback comment. ```typescript import { getFallbackComment } from "./bedrock_comment_generator.js"; const comment = getFallbackComment(); console.log(comment); ``` -------------------------------- ### Usage Example for Triage Workflow Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-workflows.md Demonstrates how to set the necessary environment variables and execute the `triage_issue.js` script. Ensure all required variables, including GitHub and AWS credentials, are exported before running the script. ```bash export ISSUE_NUMBER=42 export ISSUE_TITLE="Add SSH support to CLI" export ISSUE_BODY="Users need SSH key management..." export REPOSITORY_OWNER="kirodotdev" export REPOSITORY_NAME="kiro" export GITHUB_TOKEN="ghp_..." export AWS_ACCESS_KEY_ID="AKIA..." export AWS_SECRET_ACCESS_KEY="..." node dist/triage_issue.js ``` -------------------------------- ### Usage Example for detectDuplicates Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-duplicates.md Demonstrates how to use the `detectDuplicates` function to find potential duplicate issues and post a comment on GitHub if duplicates are found. Ensure you have the necessary functions imported. ```typescript import { detectDuplicates, generateDuplicateComment, postDuplicateComment } from "./detect_duplicates.js"; const duplicates = await detectDuplicates( "CLI crashes on Windows with SSH keys", "When running kiro with SSH key authentication on Windows, the CLI crashes…", "kirodotdev", "kiro", 42, process.env.GITHUB_TOKEN || "" ); if (duplicates.length > 0) { console.log(`Found ${duplicates.length} potential duplicates`); for (const dup of duplicates) { console.log(`- Issue #${dup.issue_number}: ${dup.issue_title}`); console.log(` Similarity: ${(dup.similarity_score * 100).toFixed(0)}%`); console.log(` Reason: ${dup.reasoning}`); } // Post comment to GitHub await postDuplicateComment( "kirodotdev", "kiro", 42, duplicates, process.env.GITHUB_TOKEN || "" ); } ``` -------------------------------- ### WorkflowSummary Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/types.md Illustrates creating and updating a WorkflowSummary object, including adding error details and setting the overall success status. The createSummary function should be available in scope. ```typescript const summary: WorkflowSummary = { success: true, totalProcessed: 1, successCount: 1, failureCount: 0, skippedCount: 0, errors: [] }; // Add error summary.errors.push({ issueNumber: 42, step: "classification", error: "Bedrock API timeout after 3 retries" }); summary.success = false; summary.failureCount = 1; // Create GitHub Actions summary createSummary(summary); ``` -------------------------------- ### LabelTaxonomy Usage Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-labels.md Demonstrates how to instantiate and use the LabelTaxonomy class. Includes checking the total number of labels, the count of feature labels, and validating if a specific label exists. ```typescript import { LabelTaxonomy } from "./data_models.js"; const taxonomy = new LabelTaxonomy(); // Check all labels console.log(`Total labels: ${taxonomy.getAllLabels().length}`); // Check feature components console.log(`Feature labels: ${taxonomy.feature_component.length}`); console.log(taxonomy.feature_component); // Check if label is valid const allLabels = taxonomy.getAllLabels(); const isValid = allLabels.includes("cli"); console.log(`"cli" is valid: ${isValid}`); ``` -------------------------------- ### Assign Labels Usage Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-labels.md Demonstrates how to use the assignLabels function to assign labels to a GitHub issue. It includes necessary imports, setting up the taxonomy, calling the function with sample data, and handling the success or failure response. Note that invalid labels will be filtered out. ```typescript import { assignLabels } from "./assign_labels.js"; import { LabelTaxonomy } from "./data_models.js"; const taxonomy = new LabelTaxonomy(); const success = await assignLabels( "kirodotdev", "kiro", 42, ["cli", "ssh", "invalid-label"], // invalid-label will be filtered process.env.GITHUB_TOKEN || "", taxonomy ); if (success) { console.log("Labels assigned: cli, ssh, pending-triage"); } else { console.error("Failed to assign labels"); } ``` -------------------------------- ### Usage Example for generateAcknowledgmentComment Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-comments.md Demonstrates how to use the `generateAcknowledgmentComment` function, including importing necessary modules and handling potential errors by falling back to a default comment. Ensure the GITHUB_TOKEN environment variable is set. ```typescript import { generateAcknowledgmentComment, getFallbackComment } from "./bedrock_comment_generator.js"; import { ClassificationResult } from "./data_models.js"; const classification: ClassificationResult = { recommended_labels: ["cli", "ssh"], confidence_scores: { "cli": 0.95, "ssh": 0.87 }, reasoning: "Issue relates to CLI SSH key management" }; let comment: string; try { comment = await generateAcknowledgmentComment( "kirodotdev", "kiro", 42, "CLI crashes on Windows with SSH keys", "When running kiro CLI with SSH key authentication on Windows...", classification, process.env.GITHUB_TOKEN || "" ); } catch (error) { console.warn("Failed to generate comment with Bedrock, using fallback"); comment = getFallbackComment(); } console.log("Generated comment:"); console.log(comment); ``` -------------------------------- ### Issue Closed (No User Response Timeline) Source: https://github.com/kirodotdev/kiro/blob/main/docs/STALE_ISSUE_TIMELINE_EXAMPLES.md This example shows the lifecycle of an issue that is automatically closed due to a lack of user response after a maintainer requests more information. The 'pending-response' label is added on Day 1, and with no activity, the issue is closed on Day 8. ```text ┌─────────────────────────────────────────────────────────────────┐ │ ISSUE LIFECYCLE │ └─────────────────────────────────────────────────────────────────┘ Day 0 Day 1 Day 2-7 Day 8 │ │ │ │ │ │ │ │ ▼ ▼ ▼ ▼ ┌────┐ ┌────┐ ┌────┐ ┌────┐ │User│ │Main│ │ No │ │Auto│ │ │ │ │ │ │ │ │ └────┘ └────┘ └────┘ └────┘ User creates issue: "App crashes on startup" │ │ └──────► Maintainer responds: "Please provide error logs" Adds "pending-response" label (labelDate = Day 1) │ │ └──────► No activity (no comments, no label changes) │ │ └──────► Workflow runs Checks: Day 8 - Day 1 = 7 days Result: CLOSE ✅ Comment posted: "This issue has been automatically closed due to inactivity. It has been 7 days since we requested additional information." Status: CLOSED ``` -------------------------------- ### Bedrock API Call Format Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-comments.md Example JSON payload structure for invoking the Bedrock API, including Anthropic version, token limits, temperature, and user messages. ```json { "anthropic_version": "bedrock-2023-05-31", "max_tokens": 1024, "temperature": 0.7, "messages": [ { "role": "user", "content": "" } ] } ``` -------------------------------- ### Issue Stays Open (User Responds Timeline) Source: https://github.com/kirodotdev/kiro/blob/main/docs/STALE_ISSUE_TIMELINE_EXAMPLES.md This example illustrates an issue that remains open because the user provides a response after the maintainer requests more information. The 'pending-response' label is added on Day 1, the user responds on Day 4, and the workflow skips closing on Day 8 as the activity is recent. ```text ┌─────────────────────────────────────────────────────────────────┐ │ ISSUE LIFECYCLE │ └─────────────────────────────────────────────────────────────────┘ Day 0 Day 1 Day 4 Day 8 │ │ │ │ │ │ │ │ ▼ ▼ ▼ ▼ ┌────┐ ┌────┐ ┌────┐ ┌────┐ │User│ │Main│ │User│ │Auto│ │ │ │ │ │ │ │ │ └────┘ └────┘ └────┘ └────┘ User creates issue: "App crashes on startup" │ │ └──────► Maintainer responds: "Please provide error logs" Adds "pending-response" label (labelDate = Day 1) │ │ └──────► User responds: "Here are the logs: ..." (lastActivityDate = Day 4) │ │ └──────► Workflow runs Checks: Day 8 - Day 4 = 4 days Result: SKIP ⏳ (needs 7 days) Status: OPEN (still waiting for maintainer) ``` -------------------------------- ### Build and Run Local Tests Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/README.md Compile the project and then run the local unit tests. ```bash npm run test:local # Build and run local test ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/kirodotdev/kiro/blob/main/scripts/test/README.md Execute the entire test suite by navigating to the scripts directory and running the 'npm test' command. ```bash cd scripts npm test ``` -------------------------------- ### ClassificationResult Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/types.md An example of a ClassificationResult object, showing recommended labels, confidence scores, and reasoning. Useful for testing or understanding output. ```typescript const result: ClassificationResult = { recommended_labels: ["cli", "ssh", "performance"], confidence_scores: { "cli": 0.95, "ssh": 0.87, "performance": 0.72 }, reasoning: "Issue relates to CLI SSH key performance problems" }; ``` -------------------------------- ### DuplicateMatch Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/types.md An example of a DuplicateMatch object, illustrating a potential duplicate issue with its number, title, similarity score, reasoning, and URL. Used for duplicate detection feedback. ```typescript const match: DuplicateMatch = { issue_number: 123, issue_title: "CLI crashes on Windows with SSH", similarity_score: 0.95, reasoning: "Both report identical SSH key handling crash on Windows with same error symptoms", url: "https://github.com/kirodotdev/kiro/issues/123" }; ``` -------------------------------- ### Run Individual Integration Tests Source: https://github.com/kirodotdev/kiro/blob/main/scripts/test/README.md Build the project and then run specific integration tests using Node.js. Ensure the project is built first with 'npm run build'. ```bash cd scripts npm run build # Run specific test node dist/test/test-local.js node dist/test/test-workflows.js node dist/test/test-prompt-injection.js node dist/test/test-sanitization-integration.js ``` -------------------------------- ### Run Quick Local Test Source: https://github.com/kirodotdev/kiro/blob/main/scripts/test/README.md Execute a quick local test by navigating to the scripts directory and running the 'test:local' npm script. ```bash cd scripts npm run test:local ``` -------------------------------- ### Run All Tests Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/README.md Execute all unit tests defined in the project. ```bash npm run test # Run all tests ``` -------------------------------- ### Initialize AWS Bedrock Runtime Client Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/modules-index.md Demonstrates how to initialize the AWS Bedrock Runtime client, specifying the region and credentials. This client is used for all interactions with Bedrock models. ```typescript const region = process.env.AWS_REGION || "us-east-1"; const client = new BedrockRuntimeClient({ region, credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID || "", secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || "", }, }); ``` -------------------------------- ### Exported Functions Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/COMPLETION_REPORT.txt Reference for all publicly available functions, including their signatures, parameters, return types, and usage examples. ```APIDOC ## Exported Functions This section details all the functions that can be directly called by users of the Kiro library. ### `classifyIssue()` **Description:** Classifies an issue based on its content and metadata. **Parameters:** - `issueData` (IssueData) - Required - The data associated with the issue. - `config` (Configuration) - Required - The configuration settings for classification. **Returns:** - `ClassificationResult` - The result of the classification. ### `detectDuplicates()` **Description:** Detects potential duplicate issues based on a set of criteria. **Parameters:** - `issueData` (IssueData) - Required - The data of the issue to check for duplicates. - `existingIssues` (IssueData[]) - Required - A list of existing issues to compare against. - `config` (Configuration) - Required - The configuration for duplicate detection. **Returns:** - `DuplicateMatch[]` - A list of potential duplicate matches. ### `fetchExistingIssues()` **Description:** Fetches existing issues from the repository. **Parameters:** - `config` (Configuration) - Required - The configuration for fetching issues. **Returns:** - `IssueData[]` - A list of existing issues. ### `postDuplicateComment()` **Description:** Posts a comment on an issue to indicate it is a duplicate. **Parameters:** - `issueId` (string) - Required - The ID of the issue to comment on. - `duplicateOf` (string) - Required - The ID of the issue this one is a duplicate of. - `config` (Configuration) - Required - The configuration for posting comments. ### `generateDuplicateComment()` **Description:** Generates the content for a duplicate comment. **Parameters:** - `issueId` (string) - Required - The ID of the issue. - `duplicateOf` (string) - Required - The ID of the issue it is a duplicate of. - `config` (Configuration) - Required - The configuration for comment generation. **Returns:** - `string` - The generated comment content. ### `assignLabels()` **Description:** Assigns appropriate labels to an issue. **Parameters:** - `issueId` (string) - Required - The ID of the issue. - `labels` (string[]) - Required - The list of labels to assign. - `config` (Configuration) - Required - The configuration for label assignment. ### `validateLabels()` **Description:** Validates the provided labels against the defined taxonomy. **Parameters:** - `labels` (string[]) - Required - The labels to validate. - `taxonomy` (LabelTaxonomy) - Required - The label taxonomy to use for validation. **Returns:** - `string[]` - A list of valid labels. ### `addDuplicateLabel()` **Description:** Adds a specific label to an issue to mark it as a duplicate. **Parameters:** - `issueId` (string) - Required - The ID of the issue. - `config` (Configuration) - Required - The configuration for label management. ### `generateAcknowledgmentComment()` **Description:** Generates a comment to acknowledge a new issue. **Parameters:** - `issueId` (string) - Required - The ID of the issue. - `config` (Configuration) - Required - The configuration for comment generation. **Returns:** - `string` - The generated acknowledgment comment. ### `getFallbackComment()` **Description:** Retrieves a fallback comment to use when specific comments cannot be generated. **Parameters:** - `config` (Configuration) - Required - The configuration for comment retrieval. **Returns:** - `string` - The fallback comment. ### `retryWithBackoff()` **Description:** Retries an operation with a backoff strategy. **Parameters:** - `operation` (function) - Required - The operation to retry. - `options` (RetryOptions) - Required - The retry options. **Returns:** - The result of the operation. ### `checkRateLimit()` **Description:** Checks the current rate limit status for the GitHub API. **Parameters:** - `config` (Configuration) - Required - The configuration for API interaction. **Returns:** - `RateLimitStatus` - The current rate limit status. ### `processBatch()` **Description:** Processes a batch of issues. **Parameters:** - `issues` (IssueData[]) - Required - The batch of issues to process. - `config` (Configuration) - Required - The configuration for batch processing. **Returns:** - `WorkflowSummary` - A summary of the batch processing results. ### `createSummary()` **Description:** Creates a summary of the workflow execution. **Parameters:** - `results` (ClassificationResult[] | DuplicateMatch[] | ...) - Required - The results from various processing steps. - `config` (Configuration) - Required - The configuration for summary creation. **Returns:** - `WorkflowSummary` - The generated workflow summary. ### `logError()` **Description:** Logs an error that occurred during execution. **Parameters:** - `error` (Error) - Required - The error object to log. - `context` (string) - Required - Contextual information about where the error occurred. - `config` (Configuration) - Required - The configuration for logging. ``` -------------------------------- ### Run Local Tests Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/modules-index.md Build the project and execute local tests using npm scripts. Ensure your environment is set up for local development before running. ```bash npm run build && npm run test:local ``` -------------------------------- ### Get Fallback Comment Function Signature Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-comments.md This function signature defines the interface for retrieving a pre-written acknowledgment comment. ```typescript export function getFallbackComment(): string ``` -------------------------------- ### AWS API Call Retry Example Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-utilities.md Illustrates using retryWithBackoff for making AWS API calls, specifically with the InvokeModelCommand and bedrockClient. ```typescript // Common usage: AWS API calls const response = await retryWithBackoff(async () => { const command = new InvokeModelCommand({ /* ... */ }); return await bedrockClient.send(command); }); ``` -------------------------------- ### Test Locally with Debug Output Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/integration-guide.md Run the build and execute the script with verbose output redirection to a log file for debugging. Use `grep` to filter for errors. ```bash # Set verbose output npm run build && node dist/triage_issue.js 2>&1 | tee debug.log # Check log file cat debug.log | grep -i error ``` -------------------------------- ### Initialize Octokit Client Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/errors.md Instantiate the Octokit client for GitHub API interactions. Authentication is implicitly checked on the first API call. ```typescript const client = new Octokit({ auth: githubToken }); // Authentication checked on first API call ``` -------------------------------- ### Get 'pending-response' Label Date Source: https://github.com/kirodotdev/kiro/blob/main/docs/STALE_ISSUE_CLOSING_EXPLAINED.md Retrieves the date when the 'pending-response' label was most recently added to an issue. This is used to calculate inactivity periods. ```typescript async function getPendingResponseLabelDate( client: Octokit, owner: string, repo: string, issueNumber: number ): Promise { const { data: events } = await client.issues.listEvents({ owner, repo, issue_number: issueNumber, per_page: 100, }); // Find the most recent "labeled" event for "pending-response" const labelEvent = events .filter( (event) => event.event === "labeled" && event.label && event.label.name === "pending-response" ) .sort( (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime() )[0]; return labelEvent ? new Date(labelEvent.created_at) : null; } ``` -------------------------------- ### Initialize GitHub Octokit Client Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/modules-index.md Shows the initialization of the Octokit client for interacting with the GitHub API, using a provided authentication token. This client is essential for managing issues, comments, and labels. ```typescript const client = new Octokit({ auth: githubToken }); ``` -------------------------------- ### Classify Issue Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/integration-guide.md Directly call the `classifyIssue` function to get recommended labels, confidence scores, and reasoning for a given issue title and body. ```APIDOC ## Classify Issue ### Description Classifies an issue by providing recommended labels, confidence scores, and reasoning. ### Method `classifyIssue(title: string, body: string, taxonomy: LabelTaxonomy): Promise` ### Parameters - **title** (string) - Required - The title of the issue. - **body** (string) - Required - The description body of the issue. - **taxonomy** (LabelTaxonomy) - Required - An instance of LabelTaxonomy to use for classification. ### Response - **recommended_labels** (string[]) - An array of recommended labels. - **confidence_scores** (object) - An object mapping labels to their confidence scores. - **reasoning** (string) - An explanation for the recommended labels. ### Request Example ```typescript import { classifyIssue } from "./bedrock_classifier.js"; import { LabelTaxonomy } from "./data_models.js"; const taxonomy = new LabelTaxonomy(); const result = await classifyIssue( "Add SSH key management to CLI", "Users need to manage SSH keys for remote development...", taxonomy ); console.log(result); ``` ### Response Example ```json { "recommended_labels": ["cli", "ssh", "feature"], "confidence_scores": { "cli": 0.95, "ssh": 0.87, "feature": 0.72 }, "reasoning": "Issue requests new feature for CLI SSH key management" } ``` ``` -------------------------------- ### Run All Tests Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/configuration.md Executes all defined test suites for the project. ```bash npm run test ``` -------------------------------- ### Get All Labels Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-labels.md Retrieves a flat array containing all valid labels across all categories managed by the LabelTaxonomy. Useful for validation or displaying a complete list. ```typescript const allLabels = taxonomy.getAllLabels(); // Returns: // ["auth", "autocomplete", "chat", "cli", ..., "duplicate", "question", ...] ``` -------------------------------- ### Execute Test Script Source: https://github.com/kirodotdev/kiro/blob/main/scripts/test/README.md Run the main test script by navigating to the scripts directory and executing './test/test.sh'. ```bash cd scripts ./test/test.sh ``` -------------------------------- ### Run Unit Tests Source: https://github.com/kirodotdev/kiro/blob/main/scripts/README.md Executes the project's unit tests. This command is used to verify individual components of the codebase. ```bash npm test ``` -------------------------------- ### Get Last Activity Date Source: https://github.com/kirodotdev/kiro/blob/main/docs/STALE_ISSUE_CLOSING_EXPLAINED.md Determines the most recent activity date for an issue, considering new comments and label changes. This helps in accurately calculating the inactivity period. ```typescript async function getLastActivityDate( client: Octokit, owner: string, repo: string, issueNumber: number ): Promise { // Get comments const { data: comments } = await client.issues.listComments({ owner, repo, issue_number: issueNumber, per_page: 100, sort: "created", direction: "desc", }); // Get timeline events (for label changes) const { data: events } = await client.issues.listEvents({ owner, repo, issue_number: issueNumber, per_page: 100, }); const dates: Date[] = []; // Add comment dates if (comments.length > 0) { dates.push(new Date(comments[0].created_at)); } // Add label event dates const labelEvents = events.filter( (event) => event.event === "labeled" || event.event === "unlabeled" ); if (labelEvents.length > 0) { dates.push(new Date(labelEvents[labelEvents.length - 1].created_at)); } // Return most recent date if (dates.length > 0) { return new Date(Math.max(...dates.map((d) => d.getTime()))); } return null; } ``` -------------------------------- ### Run Local Tests Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/configuration.md Builds the project and then runs local tests. Useful for development and debugging. ```bash npm run test:local ``` -------------------------------- ### Create GitHub Client Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-labels.md Instantiates a new Octokit client for GitHub API interactions. Requires an authentication token. ```typescript function createGitHubClient(token: string): Octokit { return new Octokit({ auth: token }); } ``` -------------------------------- ### Usage Example for logError Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-utilities.md Demonstrates how to use the logError function within try-catch blocks to handle errors during asynchronous operations like API calls. It shows logging with and without an associated issue number. ```typescript import { logError } from "./workflow_summary.js"; try { await classifyIssue(title, body, taxonomy); } catch (error) { logError(summary.errors, "classification", error, 42); // Logs: "Error in classification for issue #42: ..." } try { const result = await fetchSomething(); } catch (error) { logError(summary.errors, "data_fetch", error); // Logs: "Error in data_fetch: ..." } ``` -------------------------------- ### Build Project Source: https://github.com/kirodotdev/kiro/blob/main/scripts/README.md Compiles TypeScript code into JavaScript in the dist/ directory. ```bash npm run build ``` -------------------------------- ### Configure GitHub Token Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/integration-guide.md Generate a GitHub personal access token with necessary permissions and export it as an environment variable. ```bash export GITHUB_TOKEN="ghp_..." ``` -------------------------------- ### GitHub Actions Workflow for Issue Triage Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/integration-guide.md This YAML defines a GitHub Actions workflow that triggers on issue creation, checks out code, sets up Node.js, installs dependencies, builds the project, and runs the triage script. ```yaml name: Issue Triage on: issues: types: [opened] jobs: triage: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: "20" - name: Install dependencies working-directory: scripts run: npm install - name: Build working-directory: scripts run: npm run build - name: Triage issue working-directory: scripts env: ISSUE_NUMBER: ${{ github.event.issue.number }} ISSUE_TITLE: ${{ github.event.issue.title }} ISSUE_BODY: ${{ github.event.issue.body }} REPOSITORY_OWNER: ${{ github.repository_owner }} REPOSITORY_NAME: ${{ github.event.repository.name }} GITHUB_TOKEN: ${{ github.token }} AWS_REGION: us-east-1 AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} run: node dist/triage_issue.js ``` -------------------------------- ### Set GitHub Repository Configuration Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/configuration.md Configure the GitHub repository owner, name, and authentication token using environment variables. ```bash export REPOSITORY_OWNER="kirodotdev" export REPOSITORY_NAME="kiro" export GITHUB_TOKEN="ghp_abcdefghijklmnopqrstuvwxyz" ``` -------------------------------- ### Reproduce Locally with Environment Variables Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/errors.md Set necessary environment variables to replicate the issue locally before running the test command. ```bash export ISSUE_NUMBER=42 export ISSUE_TITLE="Test issue" export ISSUE_BODY="Test body" export REPOSITORY_OWNER="kirodotdev" export REPOSITORY_NAME="kiro" export GITHUB_TOKEN="..." export AWS_REGION="us-east-1" export AWS_ACCESS_KEY_ID="..." export AWS_SECRET_ACCESS_KEY="..." npm run test:local ``` -------------------------------- ### Basic Retry with Defaults Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/integration-guide.md Use this for simple retries with default settings (3 retries, 1-8s backoff). Ensure `retryWithBackoff` is imported. ```typescript import { retryWithBackoff } from "./retry_utils.js"; // With defaults (3 retries, 1-8s backoff) const result = await retryWithBackoff(async () => { return await someFlakeyAPI(); }); ``` -------------------------------- ### Timer Resets Multiple Times Timeline Source: https://github.com/kirodotdev/kiro/blob/main/docs/STALE_ISSUE_TIMELINE_EXAMPLES.md This example demonstrates how the stale issue closing timer resets with each new activity, such as user or maintainer responses. The issue remains open through multiple checks because the activity keeps resetting the inactivity period, eventually closing after 10 days of no activity from Day 5. ```text ┌─────────────────────────────────────────────────────────────────┐ │ ISSUE LIFECYCLE │ └─────────────────────────────────────────────────────────────────┘ Day 0 Day 1 Day 3 Day 5 Day 8 Day 10 Day 15 │ │ │ │ │ │ │ ▼ ▼ ▼ ▼ ▼ ▼ ▼ User creates issue │ └──► Maintainer adds "pending-response" (labelDate = Day 1) │ └──► User responds (lastActivityDate = Day 3) │ └──► Maintainer responds Keeps "pending-response" (lastActivityDate = Day 5) │ └──► Workflow runs Check: Day 8 - Day 5 = 3 days Result: SKIP ⏳ │ └──► Workflow runs again Check: Day 10 - Day 5 = 5 days Result: SKIP ⏳ │ └──► Workflow runs again Check: Day 15 - Day 5 = 10 days Result: CLOSE ✅ Status: CLOSED (no activity for 10 days) ``` -------------------------------- ### Workflow Summary Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/modules-index.md Utilities for creating and logging workflow summaries. ```APIDOC ## createSummary ### Description Creates a workflow summary. ### Parameters - **summary** (object) - Required - The summary data. ### Returns - void ``` ```APIDOC ## logError ### Description Logs an error that occurred during a workflow step. ### Parameters - **errors** (array) - Required - An array of errors. - **step** (string) - Required - The name of the step where the error occurred. - **error** (object) - Required - The error object. - **issueNumber** (number) - Optional - The issue number associated with the error. ### Returns - void ``` -------------------------------- ### Build Project Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/configuration.md Compiles TypeScript code to the dist/ directory. Use 'npm run clean' to remove the dist/ directory. ```bash npm run build ``` -------------------------------- ### Create GitHub Actions Workflow Summary Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-utilities.md Creates and writes a workflow execution summary to the GitHub Actions summary file. It generates a markdown table with statistics and an error table if any errors occurred. The summary is appended to the file specified by the GITHUB_STEP_SUMMARY environment variable. Returns early if the environment variable is not set. ```typescript export function createSummary(summary: WorkflowSummary): void ``` -------------------------------- ### Verify Environment Variables Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/integration-guide.md Use this command to check if all required environment variables are set correctly. Ensure variables like GITHUB_TOKEN and AWS credentials are present. ```bash echo "ISSUE_NUMBER=$ISSUE_NUMBER" echo "ISSUE_TITLE=$ISSUE_TITLE" echo "REPOSITORY_OWNER=$REPOSITORY_OWNER" echo "GITHUB_TOKEN=$GITHUB_TOKEN" echo "AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID:0:10}..." ``` -------------------------------- ### Verify Build Output Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/integration-guide.md Check the 'dist/' directory to ensure compiled JavaScript files are present after the build process. ```bash ls dist/ # Should contain compiled .js files ``` -------------------------------- ### Set Environment Variables for Local Testing Source: https://github.com/kirodotdev/kiro/blob/main/scripts/README.md Configure necessary environment variables before running local scripts. Ensure you replace placeholder values with your actual credentials and repository details. ```bash export ISSUE_NUMBER=123 export ISSUE_TITLE="Test issue" export ISSUE_BODY="Test description" export REPOSITORY_OWNER="owner" export REPOSITORY_NAME="repo" export GITHUB_TOKEN="your-token" export AWS_ACCESS_KEY_ID="your-key" export AWS_SECRET_ACCESS_KEY="your-secret" export AWS_REGION="us-east-1" node dist/triage_issue.js ``` -------------------------------- ### Bedrock Client Creation Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-comments.md Function to create a BedrockRuntimeClient instance, configuring it with AWS region and credentials from environment variables. ```typescript function createBedrockClient(): BedrockRuntimeClient { const region = process.env.AWS_REGION || "us-east-1"; return new BedrockRuntimeClient({ region, credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID || "", secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || "", }, }); } ``` -------------------------------- ### createSummary Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-utilities.md Creates and writes a workflow execution summary to the GitHub Actions summary file. It generates a markdown table with statistics and an error table if any errors occurred. ```APIDOC ## Function: createSummary Creates and writes workflow execution summary to GitHub Actions summary file. ### Signature ```typescript export function createSummary(summary: WorkflowSummary): void ``` ### Parameters #### summary - **Type**: WorkflowSummary - **Required**: Yes - **Description**: Execution summary with statistics and errors. ### WorkflowSummary Interface ```typescript export interface WorkflowSummary { success: boolean; // Whether workflow succeeded totalProcessed: number; // Total items processed successCount: number; // Successfully processed count failureCount: number; // Failed count skippedCount: number; // Skipped count errors: Array<{ issueNumber?: number; // Associated issue number step: string; // Step name where error occurred error: string; // Error message/description }>; } ``` ### Return Type void ### Behavior 1. **File Check** — Reads `GITHUB_STEP_SUMMARY` environment variable. 2. **Skip if missing** — Logs and returns if env var not set. 3. **Markdown generation** — Creates markdown table with statistics. 4. **Error table** — Includes table of all errors if any occurred. 5. **Append** — Appends summary to GitHub Actions workflow summary file. ### Generated Markdown Format ```markdown ## Workflow Summary **Status:** ✅ Success ### Statistics - Total Processed: 1 - Successful: 1 - Failed: 0 - Skipped: 0 ### Errors | Issue | Step | Error | |-------|------|-------| | #42 | classification | Error parsing response | | N/A | initialization | Missing environment variables | ``` ### Usage Example ```typescript import { createSummary, logError, WorkflowSummary } from "./workflow_summary.js"; const summary: WorkflowSummary = { success: true, totalProcessed: 1, successCount: 1, failureCount: 0, skippedCount: 0, errors: [] }; try { // Do work } catch (error) { logError(summary.errors, "classification", error, 42); summary.success = false; summary.failureCount++; } createSummary(summary); ``` ``` -------------------------------- ### Prompt Template Structure Source: https://github.com/kirodotdev/kiro/blob/main/_autodocs/api-reference-comments.md Illustrates the structure and key instructions for the comment generation prompt, including section delimiters. ```plaintext 1. Thank the user for opening the issue 2. Briefly acknowledge what the issue is about (1 sentence) 3. Consider existing comments in the discussion 4. Mention maintainer will review shortly 5. Be warm and encouraging 6. Keep to 2-4 sentences max 7. Use conversational tone 8. End with encouraging note ===== ===== ISSUE TITLE ===== ===== ISSUE BODY ===== ===== EXISTING COMMENTS ===== ===== ASSIGNED LABELS ===== ```