Skip to content

feat(groq): Calculate fair barter values for common post-apocalypse supplies based on scarcity and utility.#4267

Open
polsala wants to merge 1 commit intomainfrom
ai/groq-20260419-1650
Open

feat(groq): Calculate fair barter values for common post-apocalypse supplies based on scarcity and utility.#4267
polsala wants to merge 1 commit intomainfrom
ai/groq-20260419-1650

Conversation

@polsala
Copy link
Copy Markdown
Owner

@polsala polsala commented Apr 19, 2026

Implementation Summary

  • Utility: nightly-supply-barter-calculator
  • Provider: groq
  • Location: node-utils/nightly-nightly-supply-barter-calcul-3
  • Files Created: 3
  • Description: Calculate fair barter values for common post-apocalypse supplies based on scarcity and utility.

Rationale

  • Automated proposal from the Groq generator delivering a fresh community utility.
  • This utility was generated using the groq AI provider.

Why safe to merge

  • Utility is isolated to node-utils/nightly-nightly-supply-barter-calcul-3.
  • README + tests ship together (see folder contents).
  • No secrets or credentials touched.
  • All changes are additive and self-contained.

Test Plan

  • Follow the instructions in the generated README at node-utils/nightly-nightly-supply-barter-calcul-3/README.md
  • Run tests located in node-utils/nightly-nightly-supply-barter-calcul-3/tests/

Links

  • Generated docs and examples committed alongside this change.

Mock Justification

  • Not applicable; generator did not introduce new mocks.

@polsala
Copy link
Copy Markdown
Owner Author

polsala commented Apr 19, 2026

🤖 Review by GROQ Agent

✅ What's solid

  • Clear, self‑contained utility – the core logic (listItems / getValue) lives in a single module and is exported for reuse, making it easy to test and embed elsewhere.
  • Straight‑forward CLI – the shebang, argument parsing, and usage messages work for the two supported commands (--list and --value).
  • Deterministic calculations – the formula value = base * scarcity * quantity is applied consistently and the rounding is explicit (Math.round).
  • Minimal dependencies – the implementation relies only on Node’s built‑in modules, keeping the package lightweight.
  • Tests run without a framework – a single node test_index.js invocation validates the happy path and error handling.

🧪 Tests

  • Coverage is limited to happy‑path values
    • Action: Add tests for edge‑cases such as:
      // Invalid quantity (NaN, negative, zero)
      assert.throws(() => getValue('water', -1), /Invalid quantity/);
      assert.throws(() => getValue('water', NaN), /Invalid quantity/);
  • Error handling test only checks unknown items
    • Action: Verify that the CLI exits with a non‑zero status when an unknown item is supplied. You can spawn the script with child_process.exec and assert on stderr and code.
  • Testing framework – using a test runner (e.g., Jest, Mocha) would give you:
    • Better reporting (expect syntax, diff output).
    • Automatic test discovery (no need to remember to run the file manually).
    • Setup/teardown hooks if you later need to mock process.argv.
  • Test file location – keep test files under a conventional test/ directory (or configure package.json "test" script accordingly) so that CI tools can locate them automatically.

🔒 Security

  • Input validation for quantity
    • Currently parseInt will return NaN for non‑numeric input, which then propagates to getValue and yields NaN as the result.
    • Action: Guard against this early:
      const qty = Number(args[valueIdx + 2]);
      if (!Number.isInteger(qty) || qty <= 0) {
        console.error('Quantity must be a positive integer');
        process.exit(1);
      }
  • Potential command‑injection surface – the CLI prints directly to stdout/stderr without sanitising the item name. While the item list is hard‑coded, a future change that accepts free‑form strings could become a vector. Consider validating the item against the whitelist before any logging.
  • Shebang & executable flag – the file includes #!/usr/bin/env node but the repository does not set the executable bit (chmod +x). Ensure the file is marked executable in the repo so that npm install -g creates a working binary.

🧩 Docs / Developer Experience

  • README could be richer
    • Add a “Getting Started” section that shows how to install locally (npm link or npm install -g .).
    • Document the scarcity multipliers and the rationale behind the base values so users understand the trade‑off model.
    • Provide a sample output for both commands, e.g.:
      $ supply-barter --list
      Available items:
      - water
      - food
      - medicine
      - ammo
      - fuel
      
      $ supply-barter --value water 3
      3 water => 45 barter points
      
  • CLI help flag – a conventional -h/--help that prints usage would improve discoverability.
  • Package metadata – ensure package.json includes a bin field pointing to src/index.js (e.g., "bin": { "supply-barter": "./src/index.js" }) so that the command is correctly linked when installed globally.
  • Versioning & changelog – consider adding a brief entry to a CHANGELOG.md (or the repo’s main changelog) describing this new utility.

🧱 Mocks / Fakes

  • Not applicable for current scope – the utility does not depend on external services, so no mocks are needed.
  • Future extensibility – if you later introduce dynamic data sources (e.g., fetching scarcity values from an API), start using a thin abstraction layer (e.g., itemProvider.getItems()) that can be stubbed in tests. This will keep the core calculation logic pure and easily testable.

Quick win checklist

  • Add validation for non‑numeric / non‑positive quantities.
  • Mark src/index.js as executable (chmod +x).
  • Update package.json with a bin entry.
  • Expand test suite to cover invalid inputs and CLI exit codes (prefer a test runner).
  • Enrich README with usage examples, help flag description, and explanation of the pricing model.

These adjustments will tighten the utility’s robustness, improve the developer experience, and make the package ready for broader consumption.

@polsala
Copy link
Copy Markdown
Owner Author

polsala commented Apr 19, 2026

🤖 Review by GEMINI Agent

✅ What's solid

  • The utility is self-contained and additive, minimizing potential side effects on existing systems.
  • The core logic for calculating barter values (getValue) is clearly defined and follows the described formula.
  • The items data structure is straightforward and easy to extend with new supplies.
  • The CLI interface provides basic list and value commands, making it immediately usable.
  • The use of Math.round for final values ensures consistent integer outputs, which is practical for "barter points".

🧪 Tests

  • The existing tests cover the core functions (listItems, getValue) and edge cases like unknown items.
  • Actionable Feedback:
    • Consider adding tests for the CLI entry point directly. This would involve mocking process.argv and console.log/console.error to verify correct output and exit codes for both successful runs and error conditions (e.g., supply-barter --list, supply-barter --value water 3, supply-barter --value unknown 1, supply-barter --invalid-arg).
    • The current getValue tests directly use Math.round(base * scarcity * qty). While correct, it might be more robust to hardcode expected integer values for a few specific cases to ensure the rounding behavior is stable, especially if the Math.round implementation were to change or if floating point precision issues were to arise in more complex calculations.
    • Add a test case for getValue with a quantity of 0 or a negative quantity to ensure it handles these inputs gracefully (e.g., returns 0 or throws an error if negative quantities are not allowed).

🔒 Security

  • The utility is isolated and does not interact with external systems, databases, or sensitive files, which inherently limits its attack surface.
  • No secrets or credentials are used or exposed.
  • Actionable Feedback:
    • The CLI argument parsing for quantity (parseInt(args[valueIdx + 2], 10)) is basic. While parseInt handles non-numeric input by stopping at the first non-digit, it doesn't explicitly validate if the entire argument is a valid number. Consider adding explicit validation to ensure qty is a positive integer before passing it to getValue.
    • Example of improved validation:
      const qtyStr = args[valueIdx + 2];
      const qty = parseInt(qtyStr, 10);
      if (isNaN(qty) || qty <= 0 || qty.toString() !== qtyStr) {
        console.error('Error: Quantity must be a positive integer.');
        process.exit(1);
      }
      // ... then call getValue(item, qty)

🧩 Docs/DX

  • The README.md is clear, concise, and provides all necessary information for installation and basic usage.
  • The "How it works" section clearly explains the calculation logic.
  • The code itself is well-structured and easy to read, with clear function names and a simple data model.
  • Actionable Feedback:
    • The README.md mentions npm install -g nightly-supply-barter-calculator. However, the utility's directory is node-utils/nightly-nightly-supply-barter-calcul-3. Ensure the package name in package.json (which is not provided in the diff but implied by the npm install command) matches the intended global installation name nightly-supply-barter-calculator and not the internal directory name.
    • For better developer experience, consider adding JSDoc comments to listItems and getValue functions, describing their purpose, parameters, and return values. This would be beneficial for future maintenance and for anyone consuming these functions as a module.
    • The items object is currently hardcoded. While acceptable for a simple utility, for future extensibility or dynamic scenarios, consider documenting how new items could be added or if there's a plan to externalize this data (e.g., via a configuration file).

🧱 Mocks/Fakes

  • The PR states "Not applicable; generator did not introduce new mocks." This is accurate as the utility is self-contained and does not interact with external services that would typically require mocking.
  • Actionable Feedback:
    • While no new mocks are introduced, for testing the CLI directly (as suggested in the 🧪 Tests section), mocking process.argv, console.log, and process.exit would be necessary. This is a common pattern for testing CLI tools and should be considered if more comprehensive CLI tests are added.
    • Example of how process.argv could be mocked for a CLI test:
      const originalArgv = process.argv;
      const originalLog = console.log;
      const originalError = console.error;
      const originalExit = process.exit;
      
      let loggedOutput = '';
      let errorOutput = '';
      let exitCode = 0;
      
      beforeEach(() => {
        loggedOutput = '';
        errorOutput = '';
        exitCode = 0;
        process.argv = ['node', 'src/index.js']; // Base args
        console.log = (msg) => { loggedOutput += msg + '\n'; };
        console.error = (msg) => { errorOutput += msg + '\n'; };
        process.exit = (code) => { exitCode = code; throw new Error('process.exit called'); };
      });
      
      afterEach(() => {
        process.argv = originalArgv;
        console.log = originalLog;
        console.error = originalError;
        process.exit = originalExit;
      });
      
      // Then in a test:
      // process.argv.push('--list');
      // try { require('../src/index'); } catch (e) {}
      // assert.ok(loggedOutput.includes('Available items:'));
      // assert.strictEqual(exitCode, 0);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant