AITraining2U

Programs

Resources

Case Studies

Quick Links

Enquire Now
AI Prompt Library

30 AI Prompts for IT & Software Engineering

Copy-ready prompts that assume you will attach the code, the error or the config — engineered to ship faster while you always test and review before merging.

30 copy-ready prompts Works with Claude, Copilot & ChatGPT
AI prompts for IT and software engineering teams — developers working across multiple code screens, Malaysia

Each prompt sets the AI an engineering persona, references what you will paste or attach, and specifies the approach and output — with a reminder to review and test. These prompts are tool-agnostic and optimised to work across all major AI assistants — Claude, Microsoft Copilot and ChatGPT (and Google Gemini). Replace the [bracketed placeholders] with your own details, and always review AI output before you act on it.

Coding

1

Function With Assumptions Stated

Role

senior [language] engineer

Attach

no file - describe the function's purpose, inputs and outputs in [X]

Task
  • State your assumptions and edge cases before writing any code
  • Write the function with clear naming and input validation
  • Add comments explaining only the non-obvious parts
  • Note the time and space complexity in one line
Constraints
  • Idiomatic to the language
  • No over-engineering or unused abstractions
  • Complexity note must be accurate, not generic
Output

Assumptions list, then the code block, then a one-line Big-O complexity note.

See example AI output
Assumptions: input is a list of hashable items; order must be preserved; None values are valid entries. Edge cases handled: empty list, all-duplicate list, single item.

```python
def dedupe_ordered(items: list) -> list:
    """Return items with duplicates removed, preserving first-seen order."""
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result
```

Complexity: O(n) time, O(n) space - one pass, one hash set.
2

Cross-Language Code Translator

Role

code translator fluent in both languages

Attach

the source code block in language A, plus the target language B

Task
  • Read the source code and identify its exact behaviour
  • Rewrite it in language B using idiomatic patterns
  • Compare behaviour line by line against the original
  • Flag anything that does not map cleanly (e.g. GC, typing, concurrency model)
Constraints
  • Behaviour must be preserved exactly
  • Use target-language idioms, not a literal transliteration
  • Call out any semantic difference explicitly
Output

The translated code block followed by a short list of caveats or semantic gaps.

See example AI output
```go
func WithRetry(fn func() error, attempts int) error {
    var err error
    for i := 0; i < attempts; i++ {
        if err = fn(); err == nil {
            return nil
        }
        time.Sleep(time.Duration(i*i) * 100 * time.Millisecond)
    }
    return fmt.Errorf("failed after %d attempts: %w", attempts, err)
}
```

Caveats: Python's decorator wraps any callable implicitly; Go needs an explicit function parameter. Python's version used random jitter via random.uniform - omitted here; add rand.Float64() if jitter matters for your retry storms.
3

Behaviour-Preserving Refactor

Role

refactoring specialist

Attach

the function or file to refactor, with any existing tests if available

Task
  • Read the function and confirm current behaviour and public interface
  • Refactor for readability and maintainability only
  • Explain each change and why it is safe
  • Point out seams that would make it easier to test
Constraints
  • Public interface must stay unchanged
  • No premature abstraction or new frameworks
  • Every change must be justified, not stylistic preference alone
Output

The refactored code followed by a bullet list mapping each change to its reason.

See example AI output
```python
def process_order(order):
    validate_order(order)
    total = calculate_total(order.items, order.discounts)
    charge = charge_payment(order.customer, total)
    return build_receipt(order, charge)
```

Changes: (1) Extracted validate_order from an inline if-chain - same checks, now reusable and testable in isolation. (2) Split total calculation from payment charging - previously interleaved, which made retry-after-failure impossible; now charge_payment can be retried without recalculating. (3) Renamed proc() to process_order() for clarity. Public signature process_order(order) -> Receipt is unchanged, so callers need no updates.
4

Regex With Test Cases

Role

regex expert

Attach

no file - describe the pattern you need to match and the regex flavour (PCRE, JS, Python re, etc.)

Task
  • Write the regular expression for the described pattern
  • Break down each component and what it matches
  • Provide 2-3 strings that should match and 2-3 that should not
  • Warn about the most common edge case or gotcha for this pattern
Constraints
  • Must state the regex flavour used
  • Keep the pattern as readable as possible (named groups if supported)
  • The edge-case warning must be specific, not generic advice
Output

The regex string, a component-by-component breakdown, and a table of test strings with expected match result.

See example AI output
Flavour: JavaScript.

/^(?:\+?6?01)[0-46-9]-?\d{7,8}$/

Breakdown: \+?6?01 - optional country code +60, then mobile prefix 01; [0-46-9] - second digit excludes 5 (not a valid MY mobile prefix); -?\d{7,8} - optional hyphen then 7-8 digits.

Should match: 0123456789, +60123456789, 019-8765432.
Should not match: 0153456789 (invalid prefix), 012345 (too short).

Edge case: this rejects landlines (03-xxxx) entirely - if you need both, add a separate landline pattern.
5

Pre-Code Implementation Approach

Role

solution architect

Attach

no file - describe the requirement and any known constraints (scale, team size, deadline)

Task
  • Restate the requirement in your own words to confirm understanding
  • Sketch the data model and the main components
  • Present two viable implementation options
  • Recommend one option with the trade-off reasoning, before writing any code
Constraints
  • Prefer boring, proven technology over novel ones
  • Justify any added complexity explicitly
  • No code yet - approach only
Output

A short requirement restatement, the data model, two options with trade-offs, and a clear recommendation.

See example AI output
Requirement: employees submit leave requests, managers approve/reject, HR sees a dashboard.

Data model: LeaveRequest(id, employee_id, dates, status, approver_id), Employee, Manager.

Option A: synchronous REST API with a Postgres status enum and email notification on change - simple, easy to debug, fine under 500 employees.
Option B: event-driven with a queue (SQS) triggering notification workers - scales better but adds infra to operate.

Recommendation: Option A. At your headcount, the queue adds operational cost with no real benefit; revisit only if notification volume becomes a bottleneck.

Debugging

6

Root-Cause Error Diagnosis

Role

debugging expert

Attach

the full error message/stack trace and the relevant code around it

Task
  • Read the stack trace and identify the most likely root cause
  • Propose the fix
  • Explain why the bug happened so it can be avoided next time
  • List what to check next if the first fix doesn't resolve it
Constraints
  • Reason from the actual stack trace, don't guess wildly
  • Distinguish symptom from root cause
  • Keep the fallback list short and actionable
Output

Diagnosis, the fix (code if applicable), and a short fallback checklist.

See example AI output
Diagnosis: TypeError: Cannot read properties of undefined (reading 'email') at sendInvoice.js:42 - customer is undefined because getCustomer(id) returns null for soft-deleted customers, but the code assumes it always returns an object.

Fix: const customer = await getCustomer(id); if (!customer) throw new NotFoundError('Customer not found or deleted'); before accessing .email.

Why: soft-delete was added last sprint without updating this call site.

If it still fails: check whether getCustomer is also being called with a stale cached id from the queue message.
7

Expected vs Actual Behaviour Trace

Role

logic reviewer

Attach

the code plus a description of what it should do vs what it actually does

Task
  • Trace the execution path step by step
  • Identify exactly where behaviour diverges from expectation
  • Give the corrected code
  • Point to the specific line that was wrong
Constraints
  • Explain the faulty assumption that caused the bug
  • Don't rewrite more than necessary to fix it
Output

The bug location and faulty assumption, the corrected code, and a short reasoning note.

See example AI output
Bug: line 17, for i in range(0, total, page_size + 1) - the +1 causes the loop to skip one record per page.

Faulty assumption: the author assumed range needed an offset to avoid duplicate boundary records, but range's stop value is already exclusive, so no adjustment is needed.

Fix: for i in range(0, total, page_size):

Trace: with total=25, page_size=10, the original visits offsets 0, 11, 22 - dropping records 10 and 21. The corrected version visits 0, 10, 20, covering all 25 records across 3 pages.
8

Line-by-Line Unfamiliar Code Walkthrough

Role

code explainer

Attach

the unfamiliar code block, ideally with the surrounding file for context

Task
  • Explain the code line by line in plain language
  • Summarise what it does overall
  • Flag any risk or side effect it has
  • Note anything surprising or non-obvious
Constraints
  • Plain language, avoid restating syntax the reader already knows
  • Be explicit about side effects (mutation, I/O, global state)
Output

An annotated line-by-line walkthrough followed by a short overall summary.

See example AI output
Line 1-2: @lru_cache(maxsize=128) wraps the function so results are cached in memory keyed by arguments. Line 3: function signature takes user_id. Line 4: makes a DB call - this only runs on a cache miss.

Summary: this memoises get_user_profile so repeated calls with the same user_id skip the database after the first hit.

Risk: lru_cache is process-local and never invalidated on user updates - if a profile changes, callers may see stale data for up to 128 cached users. Surprising: this silently breaks in multi-process deployments since each process has its own cache.
9

Intermittent Issue Diagnosis Plan

Role

observability engineer

Attach

no file - describe the intermittent issue, its symptoms and rough frequency

Task
  • Identify exactly what to log at each suspect point
  • Specify which metrics to watch and their thresholds
  • Describe how to reproduce the issue reliably or narrow its trigger
  • Turn this into a step-by-step diagnosis plan
Constraints
  • Keep logging additions minimal and low-noise
  • Every step must be actionable, not generic 'add more logging'
Output

A diagnosis plan listing the specific log points, metrics and a reproduction approach.

See example AI output
Log points: request start/end timestamps with duration at the load balancer, plus connection-pool checkout time in the app layer (pool.checkout_ms).

Metrics to watch: DB connection pool saturation (active/max), p99 latency per endpoint, and upstream timeout count.

Reproduction: run a load test at 150 req/s for 5 minutes - the 502s reportedly start above 120 req/s, matching your pool max of 20 connections at ~6ms average query time.

Plan: 1) add pool metrics, 2) run the load test, 3) correlate 502 timestamps against pool-exhaustion events, 4) confirm by temporarily raising pool size to 40.
10

Breaking-Input Edge Case Review

Role

edge-case hunter

Attach

the function to review, plus its expected input types

Task
  • Review the function against nulls, empty collections and boundary values
  • Consider concurrency and race conditions if applicable
  • Consider unusually large inputs
  • Rank findings by likelihood and impact, with a test for each
Constraints
  • Don't list theoretical cases with near-zero real-world likelihood as top priority
  • Each case needs a concrete test, not just a description
Output

A ranked list of edge cases, each with a one-line test.

See example AI output
1. (High) Empty items list -> calculate_total([]) should return 0, currently throws ZeroDivisionError on the average calc. Test: assert calculate_total([]) == 0.
2. (High) Negative discount value -> currently increases the total instead of erroring. Test: calculate_total(items, discount=-10) should raise ValueError.
3. (Medium) Concurrent calls mutating the shared items list mid-calculation - no lock present. Test: run two threads appending/calculating simultaneously, assert no IndexError.
4. (Low) 100,000-item list - the O(n^2) discount-matching loop will be slow. Test: benchmark at 100k items, assert under 500ms.

Code review

11

Prioritised Pull Request Review

Role

staff engineer doing code review

Attach

the pull request diff or the full changed files

Task
  • Review for correctness bugs first
  • Review for security issues
  • Review for readability and maintainability
  • Prioritise every finding by severity and suggest the fix
Constraints
  • Be specific and kind, not just critical
  • Clearly separate must-fix from nice-to-have
Output

A findings list grouped by severity (must-fix / nice-to-have) with the suggested fix for each.

See example AI output
Must-fix:
1. amount is taken directly from the request body and passed to the payment gateway without validating it's positive - a negative amount could trigger a refund-as-charge. Add if amount <= 0: raise ValidationError.
2. The idempotency key is generated server-side per request, so a network retry double-charges the customer. Accept a client-supplied idempotency key instead.

Nice-to-have:
3. processPayment() is 80 lines - consider extracting the retry logic into withRetry().
4. Variable p on line 34 should be payment for readability.

Overall: solid structure, but the two must-fix items are real money-risk bugs - please address before merge.
12

Vulnerability Findings With Exploits

Role

security reviewer

Attach

the code to audit (endpoint handlers, DB queries, auth logic, etc.)

Task
  • Check for injection, auth, secrets, unsafe deserialisation and SSRF issues
  • For each finding, explain the concrete exploit path
  • Explain the remediation for each
  • Cite the exact line
Constraints
  • No false alarms - only flag genuinely exploitable issues
  • Cite the line number or code fragment for every finding
Output

A findings list ranked by severity, each with exploit, line reference and remediation.

See example AI output
Critical (line 22): db.execute(f"SELECT * FROM users WHERE name = '{q}'") - classic SQL injection. Exploit: q = "' OR '1'='1" returns all users; q="'; DROP TABLE users;--" is destructive. Remediation: use parameterised queries - db.execute("SELECT * FROM users WHERE name = %s", (q,)).

High (line 41): API key hardcoded as SECRET = "sk_live_49fA...". Exploit: anyone with repo read access has production access. Remediation: move to environment variable / secrets manager, rotate the exposed key immediately.
13

Hotspot Performance Analysis

Role

performance engineer

Attach

the function or module to analyse, with typical input sizes if known

Task
  • Identify the performance hotspots
  • Explain the time/space complexity of each
  • Suggest optimisations
  • Note the trade-off (readability, memory) each optimisation introduces
Constraints
  • Don't micro-optimise without evidence it matters
  • State explicitly when an optimisation isn't worth the complexity
Output

The hotspot analysis plus a prioritised list of suggestions with trade-offs.

See example AI output
Hotspot: line 30, nested loop comparing every order against every customer - O(n x m). At 10k orders x 5k customers that's 50M comparisons, matching your reported 8-second runtime.

Suggestion 1: build a customer_id -> customer dict first, reducing lookup to O(1), bringing this to O(n). Trade-off: +5k dict entries in memory, negligible.

Suggestion 2: cache the report if inputs haven't changed in the last hour. Trade-off: adds staleness risk - only worth it if this report is requested more than once per hour, which your logs suggest it is (40 requests/hour).
14

Idiomatic Code Convention Check

Role

best-practices reviewer for [language]

Attach

the code to review

Task
  • Check whether the code follows idiomatic practice for the language
  • Point out anti-patterns
  • Point out naming issues
  • Suggest structural improvements
Constraints
  • Cite the specific convention or style guide being referenced
  • Explain the why behind each suggestion, not just the rule
Output

A review listing each issue with the convention cited and the reasoning.

See example AI output
1. Line 12: bare except: catches everything including KeyboardInterrupt. Python convention: catch specific exceptions (except ValueError:). Why: silent catch-alls hide real bugs and make debugging painful later.
2. Line 8: variable named l (lowercase L) - PEP 8 explicitly discourages this as it's visually ambiguous with 1 and I. Rename to line_count.
3. Class userManager uses camelCase - Python convention is PascalCase for classes (UserManager). Why: consistency lets other Python developers navigate the codebase by convention alone, without reading each file.
15

Teaching-Focused Review Comments

Role

mentor reviewer

Attach

the diff and the junior developer's context (how senior, what they're learning)

Task
  • Write review comments a junior developer will learn from
  • For each comment, explain the underlying principle, not just the fix
  • Keep the tone encouraging
  • Prioritise the comments that teach the most transferable lessons
Constraints
  • Encouraging tone throughout, no harsh language
  • Teach reasoning, don't just hand over the corrected code
Output

A list of review comments, each pairing the fix with the principle behind it.

See example AI output
Nice work getting the integration working end-to-end! A few things to level up:

1. Line 15 - you're calling requests.get() with no timeout. Principle: any network call can hang forever if the remote server doesn't respond; always set a timeout (timeout=5) so your app fails fast instead of freezing. This applies to every external call you'll ever make.
2. Line 28 - retrying immediately in a loop with no delay can hammer a struggling service and make things worse. Try exponential backoff (time.sleep(2 ** attempt)) - it's the industry-standard retry pattern.

Documentation

16

Docstrings With Runnable Example

Role

technical writer

Attach

the function to document, including its signature

Task
  • Write the docstring covering parameters, return value and exceptions
  • Add a runnable usage example
  • Match the language's docstring convention (Google/NumPy/JSDoc/etc.)
  • Keep it concise, not padded
Constraints
  • Follow the target language's standard docstring format
  • Example must actually run as shown
Output

The function with its complete docstring inserted, including the example.

See example AI output
```python
def fetch_with_retry(url: str, attempts: int = 3) -> dict:
    """Fetch JSON from a URL, retrying on failure.

    Args:
        url: The endpoint to fetch.
        attempts: Max retry attempts before giving up. Defaults to 3.

    Returns:
        Parsed JSON response as a dict.

    Raises:
        ConnectionError: If all attempts fail.

    Example:
        >>> fetch_with_retry("https://api.example.com/status")
        {'status': 'ok'}
    """
```
The docstring follows Google style, covers all three required sections, and the example is copy-pasteable to verify behaviour directly in a REPL.
17

New-Developer README Draft

Role

README author

Attach

project details - what it does, tech stack, and how to install/run it locally

Task
  • Describe what the project does and who it's for
  • List prerequisites and installation/setup steps
  • Explain usage and configuration
  • Add a troubleshooting section for common setup failures
Constraints
  • A new developer must be able to get it running from this alone
  • No missing steps assumed as 'obvious'
Output

A complete README in markdown with standard sections (Overview, Prerequisites, Install, Usage, Config, Troubleshooting).

See example AI output
# Invoice Reconciler

Matches bank statement CSVs against outstanding invoices and flags mismatches.

## Prerequisites
- Python 3.11+
- PostgreSQL 14

## Install
```
git clone ...
pip install -r requirements.txt
cp .env.example .env  # fill in DB_URL
```

## Usage
```
python reconcile.py --statement jan.csv --month 2026-01
```

## Configuration
Set MATCH_TOLERANCE in .env (default RM 0.50) for acceptable rounding differences.

## Troubleshooting
- psycopg2.OperationalError: check DB_URL and that Postgres is running on port 5432.
- No matches found: confirm CSV date format is DD/MM/YYYY.
18

Plain-English Business Rules Doc

Role

documentation translator

Attach

the code implementing the business logic to translate

Task
  • Explain what the code does in plain English
  • Describe the inputs and outputs without technical jargon
  • Extract and state the business rules it enforces
  • Verify accuracy against the actual code logic
Constraints
  • No jargon - written for non-technical stakeholders
  • Must be accurate, not simplified to the point of being wrong
Output

A plain-English explanation covering what it does, inputs/outputs, and the business rules.

See example AI output
What it does: decides whether a customer qualifies for the loyalty discount at checkout.

Inputs: the customer's total spend this year, and how many orders they've placed.

Output: either 'no discount', '5% off', or '10% off'.

Business rules: customers get 5% off once they've spent RM 2,000 this year OR placed 10+ orders. They get 10% off once they've spent RM 5,000 this year. New customers (fewer than 3 orders) never qualify for 10%, even if a single large order pushes them over RM 5,000 - this is intentional, to stop one-off bulk buyers gaming the loyalty tier.
19

Copy-Paste API Reference Entry

Role

API-doc writer

Attach

the endpoint implementation or its route definition

Task
  • Document the method, path and parameters
  • Provide an example request and response
  • List the error codes and what triggers each
  • State the authentication requirement
Constraints
  • Must be complete enough to copy-paste and try immediately
  • Every parameter needs its type and whether required
Output

A structured API reference entry: Method/Path, Auth, Parameters, Example Request/Response, Error Codes.

See example AI output
### POST /api/v1/invoices

Auth: Bearer token required.

Parameters:
- customer_id (string, required)
- amount (number, required, in cents)
- due_date (ISO 8601 date, required)

Example request:
{"customer_id": "cus_88f2", "amount": 150000, "due_date": "2026-08-15"}

Example response (201):
{"id": "inv_a91c", "status": "pending"}

Errors:
- 400 - missing or invalid amount
- 401 - missing/expired token
- 404 - customer_id not found
20

Frequency-Ordered Troubleshooting Guide

Role

support-doc author

Attach

no file - describe the system and the common issues reported by users or support tickets

Task
  • List the common issues for this system
  • Order them by frequency reported
  • Give the likely cause for each
  • Give the tested fix for each
Constraints
  • Steps must be practical and tested, not speculative
  • Ordered by frequency, most common first
Output

A troubleshooting guide table: Symptom, Likely Cause, Fix - ordered by frequency.

See example AI output
1. Symptom: 'Connection timed out' (60% of tickets). Cause: corporate firewall blocking UDP 1194. Fix: switch protocol to TCP 443 in client settings.
2. Symptom: 'Authentication failed' (25%). Cause: expired SSO token cached locally. Fix: log out fully, clear the client's token cache folder, log back in.
3. Symptom: Connects but no internal sites load (10%). Cause: split-tunnel DNS not applied. Fix: restart the client after connecting - DNS routes apply on the second handshake.
4. Symptom: Random disconnects every ~30 min (5%). Cause: laptop sleep/wake killing the tunnel. Fix: enable 'Prevent sleep on VPN' in power settings.

Testing

21

Unit Tests With Coverage Notes

Role

test engineer

Attach

the function to test and the testing framework in use

Task
  • Write tests for the happy path
  • Write tests for edge cases and error conditions
  • Use clear test names describing the behaviour under test
  • Note any coverage gaps that remain
Constraints
  • Tests must be independent of each other
  • Avoid over-mocking - test real behaviour where practical
  • Cover boundary values explicitly
Output

A test file in the given framework, plus a short note on coverage gaps.

See example AI output
```js
describe('calculateDiscount', () => {
  test('applies 10% for orders over RM500', () => {
    expect(calculateDiscount(600)).toBe(60);
  });
  test('applies no discount at exactly RM500 boundary', () => {
    expect(calculateDiscount(500)).toBe(0);
  });
  test('throws on negative amount', () => {
    expect(() => calculateDiscount(-10)).toThrow('Invalid amount');
  });
  test('returns 0 discount for amount of 0', () => {
    expect(calculateDiscount(0)).toBe(0);
  });
});
```
Coverage gap: no test for non-numeric input (e.g. calculateDiscount('abc')) - add one if the function is reachable from user-facing forms.
22

Risk-Ranked Test Case Design

Role

QA analyst

Attach

no file - describe the feature and its expected behaviour

Task
  • Design functional test scenarios
  • Design boundary and negative test scenarios
  • Design integration scenarios
  • Include the edge cases people typically forget
Constraints
  • Prioritise by risk, highest first
  • Every case must be independently verifiable
Output

A test-case table with columns: Scenario, Steps, Expected Result - ordered by risk.

See example AI output
| Scenario | Steps | Expected |
|---|---|---|
| Upload valid PDF under 10MB | Select file, click upload | File appears in list, status 'processed' |
| Upload 0-byte file | Select empty file, upload | Error: 'File is empty' |
| Upload file exactly at 10MB limit | Select 10MB file | Uploads successfully (boundary, not rejected) |
| Upload 10.1MB file | Select oversized file | Error: 'File exceeds 10MB limit' |
| Two users upload same filename simultaneously | Concurrent upload | Both succeed, stored with distinct IDs, no overwrite |
| Upload during network drop | Start upload, disconnect wifi | Upload resumes or fails clearly, no corrupt partial file |
23

Failing Test Root-Cause Fix

Role

test debugger

Attach

the failing test code and the exact error/assertion output

Task
  • Read the assertion failure and reason about what it's checking
  • Determine whether the test or the code under test is wrong
  • Give the fix for whichever is wrong
  • Explain the reasoning
Constraints
  • Reason from the actual assertion, not assumptions about intent
  • Don't 'fix' a test by weakening a correct assertion
Output

A diagnosis of test vs. code fault, followed by the corrected code or test.

See example AI output
Assertion: expect(formatDate('2026-01-05')).toBe('05/01/2026') fails, actual output is '01/05/2026'.

Diagnosis: the code is correct - it's US-format (MM/DD/YYYY) by design per the function's JSDoc - but the test assumes DD/MM/YYYY (Malaysian convention). This is a test bug, not a code bug, since the function was never spec'd to be locale-aware.

Fix: expect(formatDate('2026-01-05')).toBe('01/05/2026'). If DD/MM/YYYY is actually the desired behaviour, that's a separate product decision - file it as a feature change, not a test fix, since it changes the function's documented contract.
24

Risk-Based Test Plan

Role

test-strategy lead

Attach

no file - describe the feature, its scope and any known risk areas

Task
  • Define the scope of what is and isn't covered
  • Specify the test levels needed (unit, integration, end-to-end)
  • Identify the key risks to prioritise coverage around
  • Define the data needs and exit criteria
Constraints
  • Risk-based prioritisation, not exhaustive-by-default
  • Exit criteria must be measurable, not vague
Output

A test plan document: Scope, Test Levels, Key Risks, Data Needs, Exit Criteria.

See example AI output
Scope: covers salary calculation and payslip generation; excludes tax-authority API integration (tested separately).

Test levels: unit tests for calculation logic (target 90% coverage), integration tests for DB writes, end-to-end test for one full payroll run.

Key risks: rounding errors in EPF/SOCSO deductions (financial + compliance risk), and duplicate payslip generation on retry (financial risk).

Data needs: 20 synthetic employee records covering full-time, part-time and mid-month joiners.

Exit criteria: zero critical/high bugs open, unit coverage >=90%, one successful full payroll dry-run reconciled manually against a spreadsheet.
25

Realistic Test Dataset With Edge Cases

Role

test-data generator

Attach

no file - describe the scenario/schema the data needs to represent

Task
  • Generate valid representative records
  • Generate boundary-value records
  • Generate deliberately malformed records
  • Note what each group is designed to test
Constraints
  • Data must be representative of real-world patterns
  • Cover the edge cases relevant to this scenario specifically
Output

A dataset in the requested format, grouped by category, with a note on what each group tests.

See example AI output
```json
[
  {"name": "Aisyah Rahman", "email": "aisyah@example.com", "age": 34},
  {"name": "Wei Ming Tan", "email": "wei.ming@example.com", "age": 18},
  {"name": "A", "email": "a@b.co", "age": 120},
  {"name": "", "email": "not-an-email", "age": -5}
]
```
Group 1 (records 1-2): valid, representative signups. Group 2 (record 3): boundary - minimum name length, maximum plausible age. Group 3 (record 4): malformed - empty name, invalid email, negative age, should all be rejected by validation.

DevOps and architecture

26

Config Walkthrough With Fixes

Role

DevOps engineer

Attach

the config or script (Dockerfile, CI YAML, etc.)

Task
  • Explain the config line by line
  • Identify security, caching and reliability risks in the current version
  • Prioritise the fixes by impact
  • Suggest the concrete improvement for each
Constraints
  • Explain the risk of each current line, don't just list improvements
  • Prioritise fixes by impact, not by ease
Output

A line-by-line walkthrough followed by a prioritised improvement list.

See example AI output
Line 1: FROM node:latest - walkthrough: pulls the latest Node image. Risk: 'latest' is unpinned, builds aren't reproducible and can break silently on image updates.
Line 5: COPY . . before npm install - invalidates Docker's layer cache on every source change, forcing every build to reinstall all dependencies.
Line 8: runs as root (no USER directive) - container escape risk if the app is compromised.

Priority fixes: 1) Pin to node:20.11-alpine (reproducibility). 2) Reorder: copy package.json + install first, then copy source (cache). 3) Add USER node before the entrypoint (security).
27

Secure CI/CD Workflow

Role

pipeline author

Attach

no file - describe what the pipeline should do (lint, test, deploy triggers) and the CI tool

Task
  • Write the workflow with each step explained
  • Handle secrets safely (no plaintext, use the platform's secret store)
  • Apply least-privilege permissions to the workflow
  • Cache dependencies to keep runs fast
Constraints
  • Fail fast - stop the pipeline on first failure
  • Least privilege on tokens/permissions
  • Cache dependencies between runs
Output

The complete workflow file with inline comments explaining each step.

See example AI output
```yaml
name: CI
on: [pull_request]
permissions:
  contents: read  # least privilege
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '20', cache: 'npm' }  # caches node_modules
      - run: npm ci
      - run: npm run lint
      - run: npm test -- --ci
```
Secrets: none needed for this lint+test job - the deploy step (separate workflow, main branch only) reads DEPLOY_TOKEN from GitHub encrypted secrets, never logged or echoed.
28

Two-Option Architecture Recommendation

Role

solutions architect

Attach

no file - describe the requirement, expected scale and constraints (budget, team size)

Task
  • Propose two viable architecture options
  • Describe each in a simple diagram-in-words
  • Compare trade-offs: cost, complexity, scale, latency
  • Recommend one option with the reasoning
Constraints
  • Prefer managed and simple over self-hosted and complex
  • Justify any added complexity explicitly
Output

Two options with trade-offs, followed by a clear recommendation.

See example AI output
Option A: Postgres full-text search (tsvector) on the existing DB. Diagram: App -> Postgres (search + storage, one system). Trade-off: near-zero added cost/complexity, but relevance ranking is basic and may slow past 1M documents.

Option B: dedicated search engine (e.g. Meilisearch) alongside Postgres. Diagram: App -> Postgres (source of truth) + Meilisearch (search index, synced via a job). Trade-off: much better relevance and speed at scale, but adds a service to operate and a sync pipeline to maintain.

Recommendation: Option A. At your current ~50k documents, Postgres full-text search is more than adequate - revisit Option B only past ~500k documents or if users complain about relevance.
29

Blameless Post-Mortem Writer

Role

incident scribe

Attach

the incident timeline notes, chat logs or monitoring data from the incident

Task
  • Reconstruct the timeline of the incident
  • Describe the impact (users, duration, revenue if known)
  • Identify the root cause
  • Capture what went well, what didn't, and the action items with owners
Constraints
  • No blame - focus on the system and process, not individuals
  • Every action item needs an owner and is realistically achievable
Output

A post-mortem document: Timeline, Impact, Root Cause, What Went Well/Didn't, Action Items.

See example AI output
Timeline: 14:02 deploy of v2.4.1 shipped; 14:05 checkout error rate rose to 40%; 14:11 alert fired; 14:19 rollback completed; 14:22 error rate normalised.

Impact: ~380 failed checkout attempts over 17 minutes, roughly RM 12,000 in lost transactions.

Root cause: v2.4.1 removed a default value on shipping_method, which the payment step required but never validated against.

Went well: rollback took under 8 minutes once identified.
Didn't: no alert fired until 6 minutes after the error spike began - threshold too high.

Action items: lower checkout error-rate alert threshold to 5% (Owner: Priya); add schema validation to CI (Owner: Faiz).
30

Under-Pressure Operational Runbook

Role

reliability engineer

Attach

no file - describe the operational task (e.g. failing over the database) and the current environment

Task
  • List the pre-checks to confirm before starting
  • Write the steps in exact, unambiguous order
  • Define how to verify each step succeeded
  • Define the rollback procedure if something goes wrong
Constraints
  • Steps must be unambiguous enough to follow under on-call pressure
  • Include a verification step after every risky action
  • Rollback must be safe and tested-quality, not theoretical
Output

A runbook: Pre-checks, Steps, Verification, Rollback.

See example AI output
Pre-checks: confirm replica lag is under 5s (SELECT now() - pg_last_xact_replay_timestamp()); confirm no active migration is running.

Steps: 1) Put app in read-only mode via feature flag MAINTENANCE_MODE=true. 2) Promote replica: pg_ctl promote -D /data/replica. 3) Update DATABASE_URL to the new primary. 4) Redeploy app pods.

Verification: run SELECT pg_is_in_recovery(); on the new primary - must return false. Confirm the app health check returns 200.

Rollback: if promotion fails, revert DATABASE_URL to the original primary and unset MAINTENANCE_MODE - the original primary was never demoted, so this is safe within 10 minutes of starting.

Frequently Asked Questions

Treat it as a draft from a fast but fallible colleague — always read, test and review it before merging. AI can introduce subtle bugs and security issues and does not know your full codebase. Never paste secrets or proprietary code into public consumer tools; use approved enterprise or local tooling. These prompts build in review and testing steps.

Yes — the prompts assume you will paste code, stack traces, configs and diffs. For proprietary code, use your organisation's approved enterprise or self-hosted AI so nothing leaves your control.

For in-editor coding, agentic tools like Claude Code and GitHub Copilot lead; for reasoning, review and design, Claude and ChatGPT are excellent. These prompts work across all of them.

No — it changes the job. Engineers move up toward design, review, orchestration and judgement while AI handles more of the typing. The engineers who thrive are AI-fluent, which is what our AI Engineering course teaches.

Yes. AITraining2U's AI Engineering course is HRD Corp SBL-KHAS claimable for eligible Malaysian employers.

No - treat AI review as a fast first pass, not a replacement. AI catches common bugs, style issues and known vulnerability patterns quickly and consistently, freeing senior engineers to focus on architecture, business-logic correctness and judgement calls AI cannot make. For Malaysian SMEs with lean dev teams, running AI review before a human review shortens review cycles significantly, but a human should still approve before merging to production, especially for anything touching payments, PDPA-covered data or core business logic.

Be cautious. Public consumer tools (free ChatGPT, free Claude.ai) may use conversations to improve their models unless you've opted out, and pasted code could theoretically surface elsewhere. For proprietary or client code, use business/enterprise tiers with data-retention opt-outs, self-hosted models, or tools like GitHub Copilot Enterprise under your organisation's data agreement. Malaysian SMEs handling client IP or PDPA-covered systems should set a written policy on what can and cannot be pasted into AI tools before developers start using them daily.

Yes, and this is one of AI's strongest SME use cases. Paste in legacy code (COBOL, old PHP, VB6, whatever it is) and ask the AI to explain it line by line, generate a plain-English business-rules summary, or draft a README from scratch. It won't know the tribal knowledge behind why a workaround exists, so pair AI-generated docs with a short review from whoever last touched the system. This turns a task engineers avoid for months into a few hours of AI-assisted drafting plus review.

They suit different moments. GitHub Copilot excels at in-editor autocomplete and small in-context suggestions as you type. Claude Code and similar agentic CLI tools are stronger for larger, multi-file tasks - refactors, migrations, writing whole features from a spec, or working autonomously through a backlog. ChatGPT and Claude's chat interfaces are best for reasoning, design discussions and code review outside the editor. Many Malaysian dev teams run Copilot for daily coding plus a chat tool for architecture and review - the tools are complementary, not exclusive.

Yes, if you keep it in a supporting role. AI can quickly summarise error logs, suggest likely root causes from a stack trace, draft the customer-facing status update, and write the post-mortem afterwards - all real time savers during a stressful outage. It should not be given authority to run remediation commands unsupervised or make the final call on rollback vs fix-forward - those decisions need an accountable human, especially for SMEs without a dedicated SRE team to catch a wrong call.

Go beyond prompts — train your team

Prompts are the start. AITraining2U runs hands-on, HRD Corp SBL-KHAS claimable AI training for Malaysian teams — from everyday AI productivity to building agents that run it & software engineering workflows end-to-end.