# Multi-Module Queue Initialization

> **Reference for:** step-01-task.md section 0
> **Purpose:** Initialize multi-module state when 2+ PRD files detected
> **Output:** modules-queue.json with module list and current index

---

## Detection

```javascript
const prdFiles = glob('.ralph/prd-*.json');
const PRD_COUNT = prdFiles.length;

if (PRD_COUNT === 0) {
  {modules_queue} = null;
  {current_module} = null;
  return;  // Single module mode or no PRDs
}

if (PRD_COUNT === 1) {
  // Single module
  {modules_queue} = null;
  {current_module} = null;
  return;  // Use standard mode
}

// PRD_COUNT > 1 → Multi-module detected
```

---

## Module Queue Construction

```javascript
const modules = [];

// Step 1: Get module order from master feature.json
const masterFeature = findFile('docs/business/**/business-analyse/**/feature.json');
let moduleOrder = [];

if (masterFeature) {
  const master = readJSON(masterFeature);
  moduleOrder = master.metadata?.workflow?.moduleOrder || [];
}

// Step 2: Build queue in order
for (const mod of moduleOrder) {
  const prdFile = `.ralph/prd-${mod.code}.json`;
  if (fileExists(prdFile)) {
    modules.push({
      code: mod.code,
      prdFile: prdFile,
      status: 'pending'
    });
  }
}

// Step 3: Fallback to alphabetical if no order from feature.json
if (modules.length === 0) {
  for (const file of prdFiles) {
    const code = file.match(/prd-(.+)\.json$/)[1];
    modules.push({
      code: code,
      prdFile: `.ralph/${file}`,
      status: 'pending'
    });
  }
  modules.sort((a, b) => a.code.localeCompare(b.code));
}

// Step 4: Initialize first module as in-progress
if (modules.length > 0) {
  modules[0].status = 'in-progress';
}
```

---

## Queue State Structure

```javascript
const queue = {
  modules: modules,              // Array of {code, prdFile, status}
  currentIndex: 0,               // Index of currently executing module
  totalModules: modules.length,  // Total count
  completedModules: 0            // Count of completed modules
};

writeJSON('.ralph/modules-queue.json', queue);

{modules_queue} = queue;
{current_module} = modules[0].code;

console.log(`Multi-module: ${modules.length} modules → ${modules.map(m => m.code).join(' → ')}`);
```

---

## Module Transition (Next Iteration)

When calling step-01 after a module completes:

```javascript
// Check for module transition marker
if (fileExists('.ralph/module-changed.json')) {
  const transition = readJSON('.ralph/module-changed.json');
  console.log(`Module transition: ${transition.fromModule} → ${transition.toModule}`);
  deleteFile('.ralph/module-changed.json');

  // PROCEED — this is an exception to the "Read Once" rule
  // Continue to load the new module's PRD
}
```

---

## PRD Loading for Current Module

```javascript
const queuePath = '.ralph/modules-queue.json';
if (fileExists(queuePath)) {
  const queue = readJSON(queuePath);
  const currentModule = queue.modules[queue.currentIndex];

  const currentPrd = readJSON(currentPrdPath);
  if (currentPrd.metadata?.moduleCode !== currentModule.code) {
    // Module has changed — load new PRD
    const modulePrd = readJSON(currentModule.prdFile);

    // v3 FAST PATH
    if (modulePrd.$version === '3.0.0') {
      modulePrd.status = 'in_progress';
      modulePrd.feature = `${modulePrd.project?.module || currentModule.code} (${modulePrd.project?.application || 'app'})`;
      modulePrd.created = modulePrd.created || new Date().toISOString();
      modulePrd.updated_at = new Date().toISOString();
      modulePrd.config = modulePrd.config || {
        max_iterations: {max_iterations},
        completion_promise: "{completion_promise}",
        current_iteration: 1
      };
      modulePrd.metadata.branch = modulePrd.metadata.branch || getCurrentBranch();
      modulePrd.metadata.project_path = modulePrd.metadata.project_path || process.cwd();
      modulePrd.metadata.mcp_servers = modulePrd.metadata.mcp_servers || { smartstack: true, context7: true };
      modulePrd.history = modulePrd.history || [];
      writeJSON(currentModule.prdFile, modulePrd);
    }
    // LEGACY: FORMAT A
    else if (modulePrd.project && modulePrd.requirements && !modulePrd.$version) {
      console.warn('⚠ DEPRECATED: FORMAT A prd.json detected. Re-run `ss business-analyse-handoff` to generate v3 format.');
      writeJSON(currentModule.prdFile, transformPrdJsonToRalphV2(modulePrd, currentModule.code));
    }
    // v2 legacy
    else {
      writeJSON(currentModule.prdFile, modulePrd);
    }
  }

  {current_module} = currentModule.code;
}
```

---

## Single Module Mode

If PRD_COUNT === 0 or 1:
- {modules_queue} = null
- {current_module} = null
- Skip multi-module logic
- Use standard single-module compact loop
