# v2 git bundle
606836cd9329feb85fa0f586348bcf29f201ce26 refs/heads/bundle
606836cd9329feb85fa0f586348bcf29f201ce26 HEAD

PACK      2‘Oxñûtree 09aa9988ba854b221b871fc55a56798185f8ee25
parent 6fe20780a546959bca733350c87038dc666ec53b
author James Maes <james@kof22.com> 1766925507 -0600
committer James Maes <james@kof22.com> 1766925507 -0600
gpgsig -----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCgAdFiEEYoWeir4fwrf8y4kIACF2cFV0Dm0FAmlRJMMACgkQACF2cFV0
 Dm38ExAAp1pbZ/FmVOLvaiMg80ED3WMXjZy5zLlRLasU0iglPB0tQV57DMOvMSGz
 lUmI7aMaxq2trbh5+3LIdgGJYTrddOMikxOL+hpPyqoHaJ7j6OCU2GqJiUazNVAq
 rBgjDu4se7NmY4wwSOl4gSRK2T3ryuaB3P+qBB6x9s33wENmvB36lv3wx1Y+OcZv
 8Ha4Hg9FmqrWr/Ib6IRsidR7mXayHbnuucpVbkaa6H4Dd0jTf1zGLb5R0t34dmm1
 2e1vbpuWKMRgiTHQ94LKMwOCG5UJKzn5s+q/UCEu/b5IeWQeIgwNpvCrs1nham+z
 LiXbk/+fkp84COOJNu+1BTB+r3yQ49ZG5LNw0SE1Wu5mnhWA3uCaKDaF7coHx8P5
 kQwgs5cQft8F/EEGklUvaPRCYfa5IzX3jfvE2V2FGzDjSOmxCL9TrY25bqt5eoOF
 jXkQNBKKcTmDabKo1OaD4rKj8xTiyaaxZaiudcpUNMeHXNkEWKN92snlyid9TTJf
 iVkUbBQ6KtEnCY3dkvq72AB4OkYpYnArOs/I4qiHW6tDJUCqqJFmo6C+epY+vucy
 4Fu4lwjS6a8C0b7mkV/NHxVssJV1z2+ptCs0OkAvoFNMxLdom2UYPdQuSescX0YB
 biKtt9P+cFkhJihy4ba2QP4c5vh/jPF/wlshGEqdYz8Huj9C7X4=
 =jvAW
 -----END PGP SIGNATURE-----

feat: archive with redirect to type-specific templates

Add architecture documentation and redirect README to three new templates:
- qbit-template-extension
- qbit-template-data
- qbit-template-application
êb”Î–Oxö	ûtree 5ed11a38a14b9e75cc6899835e18f816274fae3e
author James Maes <james@kof22.com> 1766801902 -0600
committer James Maes <james@kof22.com> 1766801902 -0600
gpgsig -----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCgAdFiEEYoWeir4fwrf8y4kIACF2cFV0Dm0FAmlPQe4ACgkQACF2cFV0
 Dm1vOg//ROoA0nzafa6A1H/awR+voMW9wvZ35P983QMQcDMuvNHdrw3g0WYAwQAL
 u/OVTbZuHzrT0ETuDC2bwZkBS2XOcAI+POGboqqA0TFS9FDahDdYoTILYzis37II
 X8WEQqzHUwCRb90BQ7DFa9FJM+s2ZUt9Zs4684PbpSdXIC1R8kbZpu+Qx7wrgvfg
 H+hie8MkrMft2CrzzJpymUdYtIiABabzSEw2onGisJYmpF/Otv2iHRB6gEa9XG0R
 XcsJcTOEXC7EKbQr75oCBPuaB8Mr4ZUsXFJg4PGDPhJK/peUkMm05rZcCmrhHWAa
 YoWdwjo2ejfZtazfu71iOS+3AA/kFHx7KibgOJdV0z90auBE/e+/UvR1C2VBGQPd
 No6NYE9F2eisGKJOdyXuADsYy+ovW7RCW4Mo73x9yLZfWfp9T5pU3YSlETM9Wbs3
 ZkWZOIdf3VXCji4bWkDNfMizo/gw1if//ytj4Q7kecfJNA0kyDE+hvDXjL+DypGG
 l4Y0SA5hQc7Yvir66jitxr+OY0XgIv7G96XnqrLsjZVccHe7zRNYZnVC8lO8prPT
 88/iuP636hHF4ahkSzQRNTlWT55DNqT7xoLSYiOmrCWnbG7tx+M/fiMBMTU9MXtd
 lpUOeDaPA7fdQZjwyjMBInWXwsaW5Yja6HbxukufzoJXrdm9Zk0=
 =6Ctk
 -----END PGP SIGNATURE-----

feat: initial QBit template repository

Template for building QQQ framework QBits with docs covering:
- Extension patterns (audit hooks, permissions, PHI masking)
- Data QBits (reference data, seed patterns)
- Application QBits (entities, processes, widgets)
“—Ž¢xâþ40000 .circleci ×XY¿ˆ.Ç%UH) úl&+p100644 .gitignore Âfœ@º­à¿ÑîSÚZj%100644 CODE_OF_CONDUCT.md Àyâ¹ðð–­±çù¿f^—p8 H100644 CODE_STYLE.md ¡Ï˜1[7s°=€I¢:T®»100644 CONTRIBUTING.md Gr¾r•ÂÕ4ªÉo@æà†`(W100644 LICENSE ¿ ES�ZHWš|gN´ò§ºs€ 100644 README.md Ý×j5¹Íh2ƒfßÐv7Ó
9�Ñz100644 SECURITY.md Dãç½5–€÷ú„îÒÇÎ·Ó€40000 checkstyle »+&F?Ñ£ä²Nïn;Ù�c40000 docs %°pºíú–cöZë^Y´{100644 pom.xml rÙbV0×¥íhÊ’c÷ ¿´£40000 scripts qö±ÍbÓEjËP‹4É
õ*£½40000 src Õè–¤i0Áß­Ä“Ÿ„ÒO‚x»ïžùl¼0ë‚ox‹ tÿâ“�6´@¶ŽrC¹�­®û}G×OšBRˆ‘J¬OQBIT_TYPE_TAXONOMY.md Æ%ñ	76ÎŸ¦Šî}/¸ë7100644 README.md ^ê´&ws‹ (¡ w)*z“WˆaÜkûDÍ·õqÇñFÈÝwšö…­“cÖ8×¦x& Ùÿ100644 config.yml {Î&t ÑMÒ(·¾ˆ�§Šw!Úï³”°Sx0Ïúversion: 2.1

orbs:
  qqq-orb: kingsrook/qqq-orb@0.3.8

workflows:

  test_only:
    jobs:
      - qqq-orb/mvn_test_only:
          context: [ qqq-maven-registry-credentials ]
          filters:
            branches:
              ignore: /(develop|main|release/.*|hotfix/.*|integration.*)/
            tags:
              only: []  

  publish_snapshot:
    jobs:
      - qqq-orb/mvn_publish:
          context: [ qqq-maven-registry-credentials ]
          branch_type: snapshot
          filters:
            branches:
              only:
                - develop

  publish_release_candidate:
    jobs:
      - qqq-orb/mvn_publish:
          context: [ qqq-maven-registry-credentials ]
          branch_type: release_candidate
          filters:
            branches:
              only:
                - /release\/.*/

  publish_release:
    jobs:
      - qqq-orb/mvn_publish:
          context: [ qqq-maven-registry-credentials ]
          branch_type: release
          filters:
            branches:
              only: [ main ]
            tags:
              only: [ /v.*/ ]

  publish_hotfix_release:
    jobs:
      - qqq-orb/mvn_publish:
          context: [ qqq-maven-registry-credentials ]
          branch_type: hotfix
          filters:
            branches:
              only:
                - /hotfix\/.*/
P±sw³x³ Lÿtarget/
.env
.idea
*.iml
*.class
*.log
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
hs_err_pid*
.DS_Store
*.sw*
.flattened-pom.xml
dependency-reduced-pom.xml
/.env.local
/.cache/
gÌ8ñà€@x ïÿ³¼�³	.claude/
3Ï“»x{ „ÿ# Code of Conduct
 

See Project level [Code of Conduct](https://github.com/Kingsrook/qqq/blob/develop/CODE_OF_CONDUCT.md)
ø½)|³xs Œÿ# Code Style Guide
 
* See Project [Code Style Guide](https://github.com/Kingsrook/qqq/blob/develop/CODE_STYLE.md)
¤Ë&Å»x‹ tÿ# Contributing to QBit User Role Permissions

* See Project [Contributing](https://github.com/Kingsrook/qqq/blob/develop/CONTRIBUTING.md)

vç0x°£x0ŠÏuQQQ - Low-code Application Framework for Engineers
Copyright (C) 2021-2025 QRun-IO, LLC
https://www.qrun.io | https://github.com/QRun-IO

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

--------------------------------------------------------------------------------

                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
Ñý»—³ªx£B\½# QBit Type Taxonomy and MCP RAG Plan

## Executive Summary

This document formalizes three distinct QBit types and outlines how the MCP RAG should support designing and creating new QBits. The goal is to enable AI-assisted QBit development with type-aware templates, validation, and guidance.

---

## QBit Type Taxonomy

### Type 1: Extension QBits

**Purpose:** Extend or enhance how QQQ operates at the infrastructure/framework level.

**Characteristics:**
- Provide new backend implementations, authentication mechanisms, or audit capabilities
- Minimal to no user-facing tables (purely operational)
- Often require specific infrastructure (databases, external services)
- Define new QQQ behaviors, validators, or action handlers
- Configuration-heavy; no `QAppSection`

**Examples:**
- RDBMS backend modules (MySQL, PostgreSQL, Aurora)
- HIPAA Audit WORM storage compliance
- SSO/SAML authentication providers
- Encryption-at-rest modules
- Custom logging/telemetry exporters

---

### Type 2: Data QBits

**Purpose:** Provide reusable reference data sets that applications can consume.

**Characteristics:**
- Primarily read-only or periodically-updated tables
- Include ETL processes for data refresh/sync
- Provide PossibleValueSources for lookups
- Tables are joined/referenced by application tables
- May include data versioning/timestamping
- Optional admin UI for data management

**Examples:**
- Geographic data (countries, states, cities, zip codes)
- Industry standard codes (SIC, NAICS, HS codes)
- Currency and exchange rate data
- Time zones and holiday calendars
- Product categorization taxonomies (UNSPSC)

---

### Type 3: Application QBits

**Purpose:** Provide complete, self-contained applications or major functional modules.

**Characteristics:**
- Multiple interconnected tables, processes, and widgets
- Full CRUD operations with business logic
- Include `QAppSection` for UI navigation
- Own security/permission model
- Designed to run standalone OR integrate with other QBits
- Composable (e.g., WMS + OMS integration points)

**Examples:**
- Warehouse Management System (WMS)
- Order Management System (OMS)
- Transportation Management System (TMS)
- Customer Relationship Management (CRM)
- Content Management System (CMS)
- Inventory Management
- Workflows/BPM engine (existing: `qbit-workflows`)

---

## QBit Composition Patterns

| Pattern | Description | Example |
|---------|-------------|---------|
| QBit depends on QBit | One QBit references tables from another | OMS uses WMS inventory tables |
| Application uses Data | App QBit references data QBit for lookups | CRM uses geographic data for addresses |
| Extension enhances Application | Extension wraps app tables with new behavior | HIPAA audit wraps patient tables |

---

## Architecture Patterns

### Table Prefixing Strategy

Data and Application QBits support table prefixing for multi-instance deployment. When an application needs the same QBit data for different purposes (shipping addresses vs billing addresses), each instance uses a unique prefix.

**Implementation:**
```java
// QBitConfig stores prefix
private String tableNamePrefix;  // e.g., "shipping" or "billing"

public String applyPrefix(String tableName)
{
   if(StringUtils.hasContent(tableNamePrefix))
   {
      return tableNamePrefix + "_" + tableName;
   }
   return tableName;
}
```

**Result:**
- No prefix: `country`, `state_province`, `city`
- With "shipping" prefix: `shipping_country`, `shipping_state_province`, `shipping_city`
- With "billing" prefix: `billing_country`, `billing_state_province`, `billing_city`

**Prefix application points:**
1. Table name in `QTableMetaData`
2. Foreign key references between tables
3. PossibleValueSource names (auto-generated)
4. Process names (if table-specific)

---

### Scope Tracking via SourceQBitAware

QQQ tracks which QBit produced each piece of metadata using the `SourceQBitAware` interface. This enables:
- Admin UI filtering by QBit
- Dependency analysis between QBits
- Scoped queries within a QBit's tables

**Implementation in Producer:**
```java
for(MetaDataProducerInterface<?> producer : producers)
{
   MetaDataProducerOutput output = producer.produce(qInstance);

   // Mark output with source QBit
   if(output instanceof SourceQBitAware sqa)
   {
      sqa.setSourceQBitName(qBitMetaData.getName());
   }

   output.addSelfToInstance(qInstance);
}
```

**What implements SourceQBitAware:**
- `QTableMetaData`
- `QProcessMetaData`
- `QPossibleValueSource`
- `QWidgetMetaData`

---

### Multi-Instance Usage Pattern

A single QBit can be instantiated multiple times with different configurations:

```java
// Instance 1: Shipping addresses
new GeoDataQBitProducer()
   .withConfig(new GeoDataQBitConfig()
      .withBackendName("rdbms")
      .withTableNamePrefix("shipping"))
   .produce(qInstance, "shipping-geo");

// Instance 2: Billing addresses
new GeoDataQBitProducer()
   .withConfig(new GeoDataQBitConfig()
      .withBackendName("rdbms")
      .withTableNamePrefix("billing"))
   .produce(qInstance, "billing-geo");

// Instance 3: Warehouse locations
new GeoDataQBitProducer()
   .withConfig(new GeoDataQBitConfig()
      .withBackendName("rdbms")
      .withTableNamePrefix("warehouse"))
   .produce(qInstance, "warehouse-geo");
```

**Key requirements for multi-instance support:**
1. All table/process/PVS names must use the prefix
2. Each instance must have a unique namespace
3. Cross-instance references require explicit configuration

---

### Data Sync Process Architecture

Data QBits include a sync process for loading/updating reference data. The process uses natural key matching for upsert operations.

**Pattern:**
```java
public class GeoDataSyncStep extends AbstractTransformStep
{
   @Override
   public void run(RunBackendStepInput input, RunBackendStepOutput output)
   {
      String prefix = getPrefix(input);

      // 1. Load embedded JSON data
      List<QRecord> sourceRecords = loadFromClasspath("/data/countries.json");

      // 2. Query existing by natural key
      Map<String, QRecord> existingByKey = queryExistingRecords(
         input, prefix + "_country", "alpha2Code");

      // 3. Categorize: insert, update, deactivate
      for(QRecord source : sourceRecords)
      {
         String key = source.getValueString("alpha2Code");
         QRecord existing = existingByKey.get(key);

         if(existing == null)
         {
            // Insert new record
            insertRecords.add(source);
         }
         else if(hasChanges(source, existing))
         {
            // Update changed record
            source.setValue("id", existing.getValue("id"));
            updateRecords.add(source);
         }
         existingByKey.remove(key);
      }

      // 4. Remaining in map are no longer in source - deactivate
      for(QRecord orphan : existingByKey.values())
      {
         orphan.setValue("isActive", false);
         deactivateRecords.add(orphan);
      }

      // 5. Execute operations
      insertRecords(insertRecords);
      updateRecords(updateRecords);
      updateRecords(deactivateRecords);

      // 6. Log summary
      LOG.info("Sync complete",
         logPair("inserted", insertRecords.size()),
         logPair("updated", updateRecords.size()),
         logPair("deactivated", deactivateRecords.size()));
   }
}
```

**Natural key design:**
| Table | Natural Key | Notes |
|-------|-------------|-------|
| country | `alpha2Code` | ISO 3166-1 alpha-2 |
| stateProvince | `countryId` + `code` | Composite key |
| city | `stateProvinceId` + `name` | May have duplicates across states |

---

### Liquibase Generation Pattern

Data QBits provide a Liquibase changelog generator that respects configuration (prefix, enabled tables).

**Template approach:**
1. Ship `changelog-template.xml` with placeholder tokens
2. Generator reads template, substitutes values, outputs final changelog
3. Host application includes generated changelog in their master changelog

**Template example:**
```xml
<changeSet id="${prefix}-create-country" author="geo-qbit">
   <createTable tableName="${prefix}_country">
      <column name="id" type="INT" autoIncrement="true">
         <constraints primaryKey="true"/>
      </column>
      <column name="alpha2_code" type="VARCHAR(2)">
         <constraints nullable="false" unique="true"/>
      </column>
      <column name="name" type="VARCHAR(100)"/>
      <column name="is_active" type="BOOLEAN" defaultValueBoolean="true"/>
   </createTable>
</changeSet>
```

**Generator:**
```java
public class GeoLiquibaseGenerator
{
   public static void generate(GeoDataQBitConfig config, Path outputPath)
   {
      String template = readResource("/db/changelog-template.xml");
      String prefix = config.getTableNamePrefix();

      // Substitute prefix
      String changelog = template.replace("${prefix}",
         prefix != null ? prefix : "geo");

      // Remove disabled table sections
      if(!config.isEnableCities())
      {
         changelog = removeSection(changelog, "city");
      }

      Files.writeString(outputPath, changelog);
   }
}
```

**Usage in host application:**
```xml
<!-- master-changelog.xml -->
<include file="generated/geo-shipping-changelog.xml"/>
<include file="generated/geo-billing-changelog.xml"/>
```

---

## MCP RAG Enhancement Plan

### Phase 1: Type-Aware Search and Discovery

**Goal:** MCP should understand QBit types and guide users to appropriate patterns.

**Actions:**
- Add `qbit_type` metadata field to indexed QBit chunks (extension/data/application)
- Update `search_qqq` to filter by QBit type
- Update `find_qbit` to return type classification
- Add `list_qbits_by_type` action

---

### Phase 2: QBit Creation Guidance

**Goal:** Provide step-by-step guidance for creating new QBits based on type.

**New MCP Actions:**

| Action | Purpose |
|--------|---------|
| `guide_qbit_creation` | Interactive wizard that asks clarifying questions and recommends type |
| `get_qbit_checklist` | Returns required/optional components for a given QBit type |
| `validate_qbit_design` | Validates proposed QBit structure against type requirements |

---

### Phase 3: Template Patterns

**Goal:** Store curated patterns for each QBit type that MCP can retrieve and adapt.

**Pattern Categories:**
- `extension-qbit-pattern` - Base structure for extension QBits
- `data-qbit-pattern` - Base structure with sync process and PVS
- `application-qbit-pattern` - Full app with sections, tables, processes
- `qbit-table-pattern` - How to add tables to any QBit type
- `qbit-process-pattern` - How to add processes to any QBit type
- `qbit-integration-pattern` - How to integrate multiple QBits

---

### Phase 4: Scaffolding Support

**Goal:** Generate boilerplate code for new QBits.

**Approach Options:**
1. **MCP-generated templates** - MCP returns template code with placeholders
2. **qctl integration** - `qctl qbit create --type=application --name=my-app`
3. **Hybrid** - MCP guides, qctl generates

**Key Decisions Needed:**
- Where do templates live? (MCP server, separate repo, qctl)
- How are templates versioned with QQQ versions?
- How do we handle type-specific variations?

---

## Type-Specific Requirements

### Extension QBit Requirements

| Requirement | Status |
|-------------|--------|
| No QAppSection | Enforced |
| Config validation for infrastructure | Required |
| May extend QQQ interfaces | Optional |
| Tests for backend integration | Required |

### Data QBit Requirements

| Requirement | Status |
|-------------|--------|
| Backend name configuration | Required |
| Sync scheduler configuration | Optional |
| PossibleValueSource registration | Recommended |
| Data versioning fields | Recommended |
| Admin UI toggle | Optional |

### Application QBit Requirements

| Requirement | Status |
|-------------|--------|
| QAppSection with navigation | Required |
| At least one table | Required |
| Security lock support | Recommended |
| Integration point configuration | Recommended |
| Feature toggles | Recommended |

---

## Open Questions and Discussion

### 1. Type Enforcement

**Question:** Should we add a formal `QBitType` enum to the framework, or keep types as documentation/convention?

| Approach | Pros | Cons |
|----------|------|------|
| **Formal enum** | Framework can validate, MCP can query type directly, enforces consistency | Requires QQQ core changes, may be too rigid for edge cases |
| **Convention only** | Flexible, no core changes needed, types can evolve | No compile-time enforcement, relies on documentation |
| **Hybrid** | Optional `getQBitType()` method on `QBitMetaDataProducer` with default | Best of both - opt-in typing with flexibility |

**Recommendation:** Hybrid approach - add an optional method to `QBitMetaDataProducer` that returns a type, defaulting to `UNSPECIFIED`. Enables classification without forcing it.

---

### 2. Inter-QBit Dependencies

**Question:** How do we formally declare that one QBit depends on another?

**Current state:** Maven `<dependency>` handles classpath, but nothing at metadata level.

| Approach | What it enables |
|----------|-----------------|
| **Maven only** | Simple, already works, but no runtime awareness |
| **Metadata declaration** | `QBitMetaData.withDependsOn("com.kingsrook.qbits:geo-data")` - runtime validation, dependency graph |
| **Config validation** | QBitConfig validates that required tables/PVS exist in QInstance |

**Recommendation:** Config validation is already the pattern (see `UserRolePermissionsQBitConfig` validating user table exists). Formal dependency declaration could be additive for tooling/documentation but not strictly required.

---

### 3. Namespace Conventions

**Question:** Should Data QBits use a `data:` namespace prefix? Application QBits use their name?

**Context:** QBits can optionally namespace their metadata (e.g., `workflows:workflowStep` vs just `workflowStep`).

| Approach | Example table names |
|----------|---------------------|
| **No namespace** | `country`, `order`, `inventoryItem` |
| **Type-based prefix** | `data:country`, `app:order`, `ext:auditLog` |
| **QBit name prefix** | `geoData:country`, `oms:order`, `wms:inventoryItem` |
| **Optional/configurable** | User chooses via config whether to namespace |

**Recommendation:** QBit name prefix - it's clear where things come from without imposing artificial categories. Keep it optional via configuration.

---

### 4. Data Versioning

**Question:** How do Data QBits handle versioned reference data?

**Examples:**
- Country names change (Burma to Myanmar)
- ZIP codes get reassigned
- Currency codes deprecated (EUR replaced national currencies)

| Approach | Description |
|----------|-------------|
| **Effective dating** | `effectiveDate`/`expirationDate` fields, queries filter by current date |
| **Snapshot tables** | `country_v2024`, `country_v2025` - separate tables per version |
| **Replace-in-place** | Just update records, no history |
| **SCD Type 2** | Slowly changing dimension pattern with `isCurrent` flag |

**Recommendation:** Effective dating as the recommended pattern for Data QBits, but not enforced. Some reference data (like ZIP codes) may just replace-in-place depending on use case.

---

### 5. Testing Patterns

**Question:** What are the minimum test requirements per type?

**Current QQQ standard:** 70% instruction coverage, 90% class coverage.

**Type-specific considerations:**

| Type | Special testing needs |
|------|----------------------|
| **Extension** | Backend integration tests, mock infrastructure |
| **Data** | Sync process tests, data validation, PVS lookup tests |
| **Application** | End-to-end workflows, security lock tests, UI navigation |

**Recommendation:** Keep existing coverage requirements. Add recommended test patterns per type in documentation, but don't enforce type-specific minimums.

---

## Next Steps

1. **Validate taxonomy** - Review with team, confirm the three types cover all use cases
2. **Add type metadata** - Update MCP indexing to classify existing QBits
3. **Create patterns** - Write pattern documents for each type
4. **Build guidance actions** - Implement `guide_qbit_creation` and `get_qbit_checklist`
5. **Decide on scaffolding** - Choose template storage and generation approach

---

## Appendix: Current QBit Inventory

| QBit | Type | Notes |
|------|------|-------|
| qbit-workflows | Application | Full workflow engine |
| qbit-webhooks | Application | Webhook subscription/delivery |
| qbit-user-role-permissions | Extension | Auth/permission system |
| qbit-standard-process-trace | Extension | Process audit logging |
| qbit-customizable-table-views | Extension | UI personalization |
| qbit-sftp-data-integration | Extension | SFTP import/export |

*No pure Data QBits exist yet - geographic/reference data would be first.*

---

| Date | Version | Notes |
|------|---------|-------|
| 2025-12-25 | 0.1.0 | Initial taxonomy and plan |
| 2025-12-27 | 0.2.0 | Added Architecture Patterns: prefixing, scope, multi-instance, sync, Liquibase |
''‚n³`xüù# QBit Template (Archived)

[![License](https://img.shields.io/badge/license-GNU%20Affero%20GPL%20v3-green.svg)](https://www.gnu.org/licenses/agpl-3.0.en.html)

> **This repository has been superseded by type-specific templates.**

## Use the Right Template

Choose the template that matches your QBit type:

| Template | Use When |
|----------|----------|
| **[qbit-template-extension](https://github.com/QRun-IO/qbit-template-extension)** | Extending QQQ infrastructure (auth, audit, customizers) |
| **[qbit-template-data](https://github.com/QRun-IO/qbit-template-data)** | Providing reference data (countries, currencies, codes) |
| **[qbit-template-application](https://github.com/QRun-IO/qbit-template-application)** | Building complete applications (WMS, CRM, inventory) |

## Why Three Templates?

Each QBit type has distinct patterns:

- **Extension QBits** - No tables, hooks into existing QQQ behavior
- **Data QBits** - Table prefixing, sync processes, Liquibase generators
- **Application QBits** - QAppSection (required), widgets, processes

Type-specific templates provide the right structure and documentation for each use case.

## Documentation

Architecture documentation remains available in this repo:

- [QBit Basics](docs/01-qbit-basics.md) - Core concepts
- [Architecture](docs/ARCHITECTURE.md) - Base classes and patterns
- [Type Taxonomy](QBIT_TYPE_TAXONOMY.md) - Type definitions and guidance

## Resources

- [QQQ Framework](https://github.com/Kingsrook/qqq)
- [QQQ Wiki](https://github.com/Kingsrook/qqq/wiki)
Nóo°xp �ÿ# Security Policy
 
 * See Project [Security Policy](https://github.com/Kingsrook/qqq/blob/develop/SECURITY.md)
x
&®­xM ²ÿ100644 config.xml xÂô™¹ZÎ]‘Ø ù7âV�Ç’s100644 license.txt )žh*094!´´FÏe°x¿ÅƒW<¶àx.ùÑ<?xml version="1.0"?>
<!--
  ~ QQQ - Low-code Application Framework for Engineers.
  ~ Copyright (C) 2021-2022.  Kingsrook, LLC
  ~ 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
  ~ contact@kingsrook.com
  ~ https://github.com/Kingsrook/
  ~
  ~ This program is free software: you can redistribute it and/or modify
  ~ it under the terms of the GNU Affero General Public License as
  ~ published by the Free Software Foundation, either version 3 of the
  ~ License, or (at your option) any later version.
  ~
  ~ This program is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
  ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  ~ GNU Affero General Public License for more details.
  ~
  ~ You should have received a copy of the GNU Affero General Public License
  ~ along with this program.  If not, see <https://www.gnu.org/licenses/>.
  -->

<!DOCTYPE module PUBLIC
        "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
        "http://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd">
<!--
   See reference at https://checkstyle.sourceforge.io/checks.html
-->
<module name = "Checker">
   <property name="charset" value="UTF-8"/>

   <property name="severity" value="warning"/>

   <property name="fileExtensions" value="java, properties, xml"/>
   <!-- Checks for whitespace                        -->
   <!-- See http://checkstyle.sf.net/config_whitespace.html -->
   <module name="FileTabCharacter">
      <property name="eachLine" value="true"/>
   </module>

   <!--
   <module name="LineLength">
      <property name="max" value="100"/>
      <property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
   </module>
   -->

   <module name="TreeWalker">
      <module name="SuppressWarningsHolder"/>
      <module name="OuterTypeFilename"/>
      <module name="IllegalTokenText">
         <property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
         <property name="format" value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
         <property name="message" value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
      </module>
      <module name="AvoidEscapedUnicodeCharacters">
         <property name="allowEscapesForControlCharacters" value="true"/>
         <property name="allowByTailComment" value="true"/>
         <property name="allowNonPrintableEscapes" value="true"/>
      </module>
      <module name="AvoidStarImport"/>
      <module name="OneTopLevelClass"/>
      <module name="NoLineWrap"/>
      <module name="EmptyBlock">
         <property name="option" value="TEXT"/>
         <property name="tokens" value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
      </module>
      <module name="NeedBraces"/>
      <module name="LeftCurly">
         <property name="option" value="nl"/>
      </module>
      <module name="RightCurly">
         <property name="option" value="alone"/>
      </module>
      <!--
      <module name="WhitespaceAround">
         <property name="allowEmptyConstructors" value="true"/>
         <property name="allowEmptyMethods" value="true"/>
         <property name="allowEmptyTypes" value="true"/>
         <property name="allowEmptyLoops" value="true"/>
         <message key="ws.notFollowed"
          value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
          <message key="ws.notPreceded"
          value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
      </module>
      -->
      <module name="OneStatementPerLine"/>
      <module name="MultipleVariableDeclarations"/>
      <module name="ArrayTypeStyle"/>
      <module name="MissingSwitchDefault"/>
      <module name="FallThrough"/>
      <module name="UpperEll"/>
      <module name="ModifierOrder"/>
      <module name="EmptyLineSeparator">
         <property name="allowNoEmptyLineBetweenFields" value="true"/>
      </module>
      <module name="SeparatorWrap">
         <property name="id" value="SeparatorWrapDot"/>
         <property name="tokens" value="DOT"/>
         <property name="option" value="nl"/>
      </module>
      <module name="SeparatorWrap">
         <property name="id" value="SeparatorWrapComma"/>
         <property name="tokens" value="COMMA"/>
         <property name="option" value="EOL"/>
      </module>
      <module name="SeparatorWrap">
         <!-- ELLIPSIS is EOL until https://github.com/google/styleguide/issues/258 -->
         <property name="id" value="SeparatorWrapEllipsis"/>
         <property name="tokens" value="ELLIPSIS"/>
         <property name="option" value="EOL"/>
      </module>
      <module name="SeparatorWrap">
         <!-- ARRAY_DECLARATOR is EOL until https://github.com/google/styleguide/issues/259 -->
         <property name="id" value="SeparatorWrapArrayDeclarator"/>
         <property name="tokens" value="ARRAY_DECLARATOR"/>
         <property name="option" value="EOL"/>
      </module>
      <module name="SeparatorWrap">
         <property name="id" value="SeparatorWrapMethodRef"/>
         <property name="tokens" value="METHOD_REF"/>
         <property name="option" value="nl"/>
      </module>
      <module name="PackageName">
         <property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
         <message key="name.invalidPattern"
          value="Package name ''{0}'' must match pattern ''{1}''."/>
      </module>
      <module name="TypeName">
         <message key="name.invalidPattern"
          value="Type name ''{0}'' must match pattern ''{1}''."/>
      </module>
      <module name="MemberName">
         <property name="format" value="^[_a-zA-Z]([a-z0-9A-Z][a-zA-Z0-9]*)?$"/>
         <message key="name.invalidPattern" value="Member name ''{0}'' must match pattern ''{1}''."/>
      </module>
      <module name="ParameterName">
         <property name="format" value="^[a-zA-Z]([a-z0-9A-Z][a-zA-Z0-9]*)?$"/>
         <message key="name.invalidPattern" value="Parameter name ''{0}'' must match pattern ''{1}''."/>
      </module>
      <module name="CatchParameterName">
         <property name="format" value="^[a-zA-Z]([a-z0-9A-Z][a-zA-Z0-9]*)?$"/>
         <message key="name.invalidPattern" value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
      </module>
      <module name="LocalVariableName">
         <property name="tokens" value="VARIABLE_DEF"/>
         <property name="format" value="^[a-zA-Z]([a-z0-9A-Z][a-zA-Z0-9]*)?$"/>
         <message key="name.invalidPattern" value="Local variable name ''{0}'' must match pattern ''{1}''."/>
      </module>
      <module name="ClassTypeParameterName">
         <property name="format" value="(^[A-Z][0-9]?)$|([A-Z][_A-Z0-9]*$)"/>
         <message key="name.invalidPattern" value="Class type name ''{0}'' must match pattern ''{1}''."/>
      </module>
      <module name="MethodTypeParameterName">
         <property name="format" value="(^[A-Z][0-9]?)$|([A-Z][_A-Z0-9]*$)"/>
         <message key="name.invalidPattern" value="Method type name ''{0}'' must match pattern ''{1}''."/>
      </module>
      <module name="InterfaceTypeParameterName">
         <property name="format" value="(^[A-Z][0-9]?)$|([A-Z][_A-Z0-9]*$)"/>
         <message key="name.invalidPattern" value="Interface type name ''{0}'' must match pattern ''{1}''."/>
      </module>
      <module name="NoFinalizer"/>
      <module name="GenericWhitespace">
         <message key="ws.followed" value="GenericWhitespace ''{0}'' is followed by whitespace."/>
         <message key="ws.preceded" value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
         <message key="ws.illegalFollow" value="GenericWhitespace ''{0}'' should followed by whitespace."/>
         <message key="ws.notPreceded" value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
      </module>
      <module name="Indentation">
         <property name="basicOffset" value="3"/>
         <property name="braceAdjustment" value="0"/>
         <property name="caseIndent" value="3"/>
         <property name="throwsIndent" value="6"/>
         <property name="lineWrappingIndentation" value="3"/>
         <property name="arrayInitIndent" value="6"/>
      </module>
      <!--
      <module name="AbbreviationAsWordInName">
         <property name="ignoreFinal" value="false"/>
         <property name="allowedAbbreviationLength" value="1"/>
      </module>
      <module name="OverloadMethodsDeclarationOrder"/>
      <module name="VariableDeclarationUsageDistance"/>
      <module name="CustomImportOrder">
         <property name="sortImportsInGroupAlphabetically" value="true"/>
         <property name="separateLineBetweenGroups" value="true"/>
         <property name="customImportOrderRules" value="STATIC###THIRD_PARTY_PACKAGE"/>
      </module>
      -->
      <module name="CustomImportOrder">
         <property name="customImportOrderRules" value="SPECIAL_IMPORTS###STANDARD_JAVA_PACKAGE###THIRD_PARTY_PACKAGE###STATIC"/>
         <property name="specialImportsRegExp" value="^javax\."/>
         <property name="standardPackageRegExp" value="^java\."/>
         <property name="sortImportsInGroupAlphabetically" value="true"/>
         <property name="separateLineBetweenGroups" value="false"/>
      </module>
      <module name="MethodParamPad"/>
      <module name="NoWhitespaceBefore">
         <property name="tokens" value="COMMA, SEMI, POST_INC, POST_DEC, DOT, ELLIPSIS, METHOD_REF"/>
         <property name="allowLineBreaks" value="true"/>
      </module>
      <module name="ParenPad"/>
      <module name="OperatorWrap">
         <property name="option" value="NL"/>
         <property name="tokens" value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR, METHOD_REF "/>
      </module>
      <module name="AnnotationLocation">
         <property name="id" value="AnnotationLocationMostCases"/>
         <property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
      </module>
      <module name="AnnotationLocation">
         <property name="id" value="AnnotationLocationVariables"/>
         <property name="tokens" value="VARIABLE_DEF"/>
         <property name="allowSamelineMultipleAnnotations" value="true"/>
      </module>
      <module name="JavadocMethod">
         <property name="allowMissingParamTags" value="true"/>
         <property name="allowMissingReturnTag" value="true"/>
         <property name="allowedAnnotations" value="Override, Test"/>
      </module>
      <module name="MissingJavadocMethod">
         <property name="scope" value="private"/>
      </module>
      <module name="MissingJavadocType">
         <property name="scope" value="private"/>
      </module>
      <module name="MethodName">
         <property name="format" value="^[a-z][a-zA-Z0-9_]*$"/>
         <message key="name.invalidPattern"
          value="Method name ''{0}'' must match pattern ''{1}''."/>
      </module>
      <module name="EmptyCatchBlock">
         <property name="exceptionVariableName" value="expected"/>
      </module>
      <module name="CommentsIndentation"/>

      <!-- this would be nice, but requires the the @inheritDoc javadoc tag... -->
      <module name="MissingOverride"/>

   </module>
   <module name="Header">
     <property name="headerFile" value="checkstyle/license.txt"/>
     <property name="fileExtensions" value="java"/>
     <property name="ignoreLines" value="3"/>
   </module>
   <module name="SuppressWarningsFilter"/>
</module>
ÒþAÓº8xŠuü/*
 * QQQ - Low-code Application Framework for Engineers.
 * Copyright (C) 2021-2022.  Kingsrook, LLC
 * 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
 * contact@kingsrook.com
 * https://github.com/Kingsrook/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
m&ô¬x,Óþ100644 00-getting-started.md 3Ë±¶•V[‚6\AÃE‹Ž¶¯é100644 01-qbit-basics.md ®¿ÒiŠVÓ}Ý~�SæÁŸ@ö$100644 02-extension-patterns.md -_¶ˆu¤%aHc~†ÓÈ;<100644 03-data-qbits.md �\"'dûqì·à’„¿œI100644 04-application-qbits.md GÜK1wß²`cXdÎ0©­7M„$100644 05-existing-extension-points.md —Øø½.:wðßÌ[ÈfÓ&è–ø:‘-…q±ê�9xJ µÿ¬×�ªS•ž„qá×'_ä¹u_ã‹iÈ¸‘¾n+100644 ARCHITECTURE.md ·¹­zÒÜI^W~5íuéÄÁ¢T¢þ !»mxÛ$ù# Getting Started with QBit Development

## Quick Start

### 1. Use This Template

Click "Use this template" on GitHub to create a new repository from this template.

Or clone directly:

```bash
git clone https://github.com/qrun-io/qbit-template.git qbit-my-feature
cd qbit-my-feature
rm -rf .git
git init
```

### 2. Customize the Template

Run the customization script to rename packages and classes:

```bash
python3 scripts/customize_template.py
```

The script will prompt for:
- **QBit name**: Your QBit's name (e.g., "my-feature" or "MyFeature")
- **Maven groupId**: Usually `com.kingsrook.qbits` or your organization's groupId
- **Maven artifactId**: Usually `qbit-{your-name}`
- **GitHub organization**: Where you'll push the repo

### 3. Build and Test

```bash
mvn clean package
```

### 4. Push to Your Repository

```bash
git add .
git commit -m "Initial QBit setup"
git remote add origin git@github.com:your-org/qbit-your-name.git
git push -u origin main
```

## Project Structure

```
qbit-your-name/
â”œâ”€â”€ src/main/java/com/kingsrook/qbits/yourname/
â”‚   â”œâ”€â”€ YourNameQBitConfig.java    # Configuration class
â”‚   â””â”€â”€ YourNameQBitProducer.java  # Producer (entry point)
â”œâ”€â”€ src/test/java/.../
â”‚   â””â”€â”€ BaseTest.java              # Test base class
â”œâ”€â”€ docs/                          # Documentation
â”œâ”€â”€ pom.xml                        # Maven configuration
â””â”€â”€ scripts/customize_template.py  # One-time setup script
```

## Next Steps

1. Read [01-qbit-basics.md](01-qbit-basics.md) to understand QBit architecture
2. Read [02-extension-patterns.md](02-extension-patterns.md) to learn how to extend QQQ
3. Add your entities, processes, or extension hooks
4. Write tests for your functionality
™e°ñxïð# QBit Basics

## What is a QBit?

A QBit is a modular, reusable component for the QQQ framework. QBits can provide:
- **Tables and entities** for data storage
- **Processes** for business logic
- **Extension hooks** that modify QQQ behavior
- **Complete applications** that combine all of the above

## Core Components

### QBitProducer

The producer is the entry point for your QBit. Applications use it to add your QBit to their QInstance:

```java
new MyQBitProducer()
   .withMyQBitConfig(new MyQBitConfig()
      .withBackendName("myBackend")
      .withSomeOption(true))
   .produce(qInstance);
```

Key responsibilities:
1. Create `QBitMetaData` with Maven-style identification
2. Register the QBit with the QInstance
3. Discover and produce all component metadata
4. Apply configuration and customizations

### QBitConfig

The config class holds configuration options that control how your QBit behaves:

```java
public class MyQBitConfig implements QBitConfig
{
   private String backendName;
   private Boolean someFeatureEnabled = true;

   @Override
   public void validate(QInstance qInstance, List<String> errors)
   {
      // Validate configuration before QBit is produced
      if(backendName == null)
      {
         errors.add("backendName is required");
      }
   }

   // Getters, setters, fluent setters...
}
```

### QBitMetaData

Identifies your QBit using Maven-style coordinates:

```java
QBitMetaData qBitMetaData = new QBitMetaData()
   .withGroupId("com.kingsrook.qbits")
   .withArtifactId("my-feature")
   .withVersion("1.0.0")
   .withNamespace(namespace)  // Optional: allows multiple instances
   .withConfig(myConfig);
```

## Adding Entities

Use `@QMetaDataProducingEntity` to automatically generate table metadata:

```java
@QMetaDataProducingEntity(producePossibleValueSource = true)
public class MyEntity extends QRecordEntity
{
   public static final String TABLE_NAME = "myEntity";

   @QField(isPrimaryKey = true)
   private Integer id;

   @QField(isRequired = true, maxLength = 100)
   private String name;

   // Getters, setters, fluent setters...
}
```

The entity will be automatically discovered and produced when your QBit is produced.

## Adding Processes

Create a metadata producer for your process:

```java
public class MyProcessMetaDataProducer implements MetaDataProducerInterface<QProcessMetaData>
{
   @Override
   public QProcessMetaData produce(QInstance qInstance)
   {
      return new QProcessMetaData()
         .withName("myProcess")
         .withLabel("My Process")
         .withStepList(List.of(
            new QBackendStepMetaData()
               .withName("step1")
               .withCode(new QCodeReference(MyProcessStep.class))
         ));
   }
}
```

## Package Structure

Organize your QBit code:

```
com.kingsrook.qbits.myfeature/
â”œâ”€â”€ MyFeatureQBitConfig.java
â”œâ”€â”€ MyFeatureQBitProducer.java
â”œâ”€â”€ model/
â”‚   â””â”€â”€ MyEntity.java
â”œâ”€â”€ processes/
â”‚   â”œâ”€â”€ MyProcessMetaDataProducer.java
â”‚   â””â”€â”€ MyProcessStep.java
â”œâ”€â”€ actions/
â”‚   â””â”€â”€ MyCustomAction.java
â””â”€â”€ customizers/
    â””â”€â”€ MyTableCustomizer.java
```

## Testing

Extend `BaseTest` to get a configured QInstance:

```java
class MyEntityTest extends BaseTest
{
   @Test
   void testInsert() throws QException
   {
      InsertInput input = new InsertInput();
      input.setTableName(MyEntity.TABLE_NAME);
      input.setRecords(List.of(new QRecord().withValue("name", "Test")));

      InsertOutput output = new InsertAction().execute(input);
      assertThat(output.getRecords()).hasSize(1);
   }
}
```

## Next Steps

- [02-extension-patterns.md](02-extension-patterns.md) - Extend QQQ functionality
- [03-data-qbits.md](03-data-qbits.md) - Provide reference data
- [04-application-qbits.md](04-application-qbits.md) - Build complete applications
xÃ&�¹–xi–æ# Extension Patterns

QBits can extend QQQ functionality by implementing existing extension point interfaces. This document covers the available hooks and how to use them.

## Extension Points Overview

| Extension Point | Interface | Registration | Use Case |
|-----------------|-----------|--------------|----------|
| Audit customization | `AuditActionCustomizerInterface` | `SupplementalCustomizer` | Modify audit records, mask sensitive data |
| Custom permissions | `CustomPermissionChecker` | `QPermissionRules` | AWS IAM-style policies, custom auth logic |
| Table CRUD hooks | `TableCustomizerInterface` | Per-table metadata | Validate, transform, trigger actions |
| Instance enrichment | `QInstanceEnricherPluginInterface` | Plugin discovery | Add computed metadata |
| Instance validation | `QInstanceValidatorPluginInterface` | Plugin discovery | Custom validation rules |
| Field metadata | `QSupplementalFieldMetaData` | Per-field | PHI flags, custom field properties |
| Table metadata | `QSupplementalTableMetaData` | Per-table | Custom table properties |

## Example: PHI Field Masking

This example shows how to build a HIPAA/PHI QBit that masks sensitive fields in audit logs.

### 1. Define Supplemental Field Metadata

```java
public class PhiFieldMetaData extends QSupplementalFieldMetaData
{
   public static final String TYPE = "phi";

   private Boolean maskInAudit = true;
   private Boolean maskInLogs = true;
   private String maskValue = "[PHI REDACTED]";

   @Override
   public String getType()
   {
      return TYPE;
   }

   // Getters, setters, fluent setters...
}
```

### 2. Implement Audit Customizer

```java
public class PhiAuditMasker implements AuditActionCustomizerInterface
{
   @Override
   public void customizeInput(AuditSingleInput input)
   {
      QTableMetaData table = QContext.getQInstance().getTable(input.getTableName());
      if(table == null)
      {
         return;
      }

      for(QRecord detail : input.getDetails())
      {
         String fieldName = detail.getValueString("fieldName");
         QFieldMetaData field = table.getField(fieldName);
         if(field == null)
         {
            continue;
         }

         PhiFieldMetaData phi = (PhiFieldMetaData) field.getSupplementalMetaData(PhiFieldMetaData.TYPE);
         if(phi != null && Boolean.TRUE.equals(phi.getMaskInAudit()))
         {
            detail.setValue("oldValue", phi.getMaskValue());
            detail.setValue("newValue", phi.getMaskValue());
         }
      }
   }
}
```

### 3. Register in Producer

```java
@Override
public void produce(QInstance qInstance, String namespace) throws QException
{
   // ... create QBitMetaData ...

   // Register the audit customizer
   qInstance.addSupplementalCustomizer(
      AuditActionCustomizerInterface.CUSTOMIZER_TYPE,
      new QCodeReference(PhiAuditMasker.class));

   // ... finish producing ...
}
```

### 4. Application Usage

Applications mark fields as PHI when defining their entities:

```java
new QFieldMetaData("ssn", QFieldType.STRING)
   .withLabel("Social Security Number")
   .withSupplementalMetaData(new PhiFieldMetaData()
      .withMaskInAudit(true)
      .withMaskInLogs(true));
```

## Example: Custom Permission Checker

Implement AWS IAM-style policy evaluation:

```java
public class PolicyPermissionChecker extends CustomPermissionChecker
{
   @Override
   public void checkPermissionsThrowing(AbstractActionInput input,
                                        MetaDataWithPermissionRules metaData)
      throws QPermissionDeniedException
   {
      QSession session = QContext.getQSession();

      // Get policies attached to user
      List<Policy> policies = loadUserPolicies(session.getUser().getIdReference());

      // Evaluate policies against requested action
      String action = deriveAction(input, metaData);
      String resource = deriveResource(input, metaData);

      PolicyEvaluationResult result = evaluatePolicies(policies, action, resource);

      if(result.isDenied())
      {
         throw new QPermissionDeniedException("Access denied by policy: " + result.getReason());
      }
   }
}
```

Register on tables or globally:

```java
// Per-table
table.withPermissionRules(new QPermissionRules()
   .withCustomPermissionChecker(new QCodeReference(PolicyPermissionChecker.class)));

// Or register in QBit producer for all tables
```

## Example: Table CRUD Hooks

Add validation or side effects to table operations:

```java
public class OrderTableCustomizer implements TableCustomizerInterface
{
   @Override
   public List<QRecord> preInsert(InsertInput input, List<QRecord> records, boolean isPreview)
   {
      for(QRecord record : records)
      {
         // Auto-generate order number
         if(record.getValue("orderNumber") == null)
         {
            record.setValue("orderNumber", generateOrderNumber());
         }

         // Validate total
         BigDecimal total = record.getValueBigDecimal("total");
         if(total != null && total.compareTo(BigDecimal.ZERO) < 0)
         {
            record.addError(new BadInputStatusMessage("Total cannot be negative"));
         }
      }
      return records;
   }

   @Override
   public List<QRecord> postInsert(InsertInput input, List<QRecord> records)
   {
      // Send notification for new orders
      for(QRecord record : records)
      {
         sendOrderConfirmation(record);
      }
      return records;
   }
}
```

## Extension Point Reference

### AuditActionCustomizerInterface

- `customizeInput(AuditSingleInput)` - Modify before audit record created
- `customizeRecord(QRecord, AuditSingleInput)` - Modify audit record before insert

### CustomPermissionChecker

- `checkPermissionsThrowing(AbstractActionInput, MetaDataWithPermissionRules)` - Throw if denied
- `handlesBuildAvailablePermission()` - Return true if you provide custom permissions
- `buildAvailablePermission()` - Return custom AvailablePermission objects

### TableCustomizerInterface

- `preInsert/postInsert` - Before/after insert
- `preUpdate/postUpdate` - Before/after update (with old record access)
- `preDelete/postDelete` - Before/after delete
- `postQuery` - After query results returned

### QSupplementalFieldMetaData

- `getType()` - Unique identifier for your metadata type
- `includeInFrontendMetaData()` - Whether to send to frontend
- `enrich(QInstance, QFieldMetaData)` - Enrich during instance setup
- `validate(QInstance, QFieldMetaData, QInstanceValidator)` - Validate field config
Künƒ»�xÛ)$Ö# Data QBits

Data QBits provide reusable reference data sets that applications consume. They support multi-instance deployment with table prefixing, natural key-based sync for updates, and Liquibase changelog generation.

## Key Characteristics

| Feature | Description |
|---------|-------------|
| Table prefixing | Each instance uses configurable prefix (`shipping_country`, `billing_country`) |
| Multi-instance | Same QBit deployed multiple times in one app |
| Sync process | Upsert by natural key (insert new, update changed, deactivate removed) |
| Liquibase generator | Template-based changelog respecting prefix and enabled tables |
| PossibleValueSources | Auto-generated, prefix-aware |

---

## Structure

```
com.kingsrook.qbits.geodata/
â”œâ”€â”€ GeoDataQBitConfig.java          # Extends AbstractDataQBitConfig
â”œâ”€â”€ GeoDataQBitProducer.java        # Extends AbstractDataQBitProducer
â”œâ”€â”€ model/
â”‚   â”œâ”€â”€ Country.java
â”‚   â”œâ”€â”€ StateProvince.java
â”‚   â””â”€â”€ City.java
â”œâ”€â”€ sync/
â”‚   â””â”€â”€ GeoDataSyncProcess.java     # Upsert by natural key
â”œâ”€â”€ liquibase/
â”‚   â””â”€â”€ GeoLiquibaseGenerator.java
â””â”€â”€ resources/
    â”œâ”€â”€ data/
    â”‚   â”œâ”€â”€ countries.json
    â”‚   â”œâ”€â”€ state-provinces.json
    â”‚   â””â”€â”€ cities.json
    â””â”€â”€ db/
        â””â”€â”€ changelog-template.xml
```

---

## Table Prefixing

### Configuration

```java
public class GeoDataQBitConfig extends AbstractDataQBitConfig
{
   private Boolean enableCountries = true;
   private Boolean enableStateProvinces = true;
   private Boolean enableCities = true;
   private List<String> countryFilter;  // Limit to specific alpha2 codes

   @Override
   public List<String> getEnabledTableNames()
   {
      List<String> tables = new ArrayList<>();
      if(Boolean.TRUE.equals(enableCountries))
      {
         tables.add(Country.TABLE_NAME);
      }
      if(Boolean.TRUE.equals(enableStateProvinces))
      {
         tables.add(StateProvince.TABLE_NAME);
      }
      if(Boolean.TRUE.equals(enableCities))
      {
         tables.add(City.TABLE_NAME);
      }
      return tables;
   }
}
```

### Usage

```java
// Single instance, no prefix
new GeoDataQBitProducer()
   .withConfig(new GeoDataQBitConfig()
      .withBackendName("rdbms"))
   .produce(qInstance, "geo");
// Tables: country, state_province, city

// Multi-instance with prefixes
new GeoDataQBitProducer()
   .withConfig(new GeoDataQBitConfig()
      .withBackendName("rdbms")
      .withTableNamePrefix("shipping"))
   .produce(qInstance, "shipping-geo");
// Tables: shipping_country, shipping_state_province, shipping_city

new GeoDataQBitProducer()
   .withConfig(new GeoDataQBitConfig()
      .withBackendName("rdbms")
      .withTableNamePrefix("billing")
      .withEnableCities(false))  // Skip cities for billing
   .produce(qInstance, "billing-geo");
// Tables: billing_country, billing_state_province (no cities)
```

---

## Natural Key Design

Each table defines a natural key for upsert matching:

| Table | Natural Key Fields | Example |
|-------|-------------------|---------|
| country | `alpha2Code` | "US", "CA", "MX" |
| stateProvince | `countryId`, `code` | (1, "CA"), (1, "TX") |
| city | `stateProvinceId`, `name` | (5, "Los Angeles") |

### Entity with Natural Key

```java
@QMetaDataProducingEntity(producePossibleValueSource = true)
public class Country extends QRecordEntity
{
   public static final String TABLE_NAME = "country";

   @QField(isPrimaryKey = true)
   private Integer id;

   @QField(isRequired = true, maxLength = 2)
   private String alpha2Code;  // Natural key

   @QField(maxLength = 3)
   private String alpha3Code;

   @QField(isRequired = true, maxLength = 100)
   private String name;

   @QField
   private Boolean isActive = true;  // Soft delete flag

   // Fluent setters...
}
```

---

## Sync Process

The sync process loads embedded JSON and performs upsert by natural key:

```java
public class GeoDataSyncStep extends AbstractTransformStep
{
   private static final QLogger LOG = QLogger.getLogger(GeoDataSyncStep.class);

   @Override
   public void run(RunBackendStepInput input, RunBackendStepOutput output)
      throws QException
   {
      String tableName = input.getValueString("tableName");
      String naturalKeyField = input.getValueString("naturalKeyField");

      // 1. Load source data from classpath
      List<QRecord> sourceRecords = loadJsonData(tableName);

      // 2. Query existing by natural key
      Map<String, QRecord> existingByKey = queryExisting(input, tableName, naturalKeyField);

      // 3. Categorize records
      List<QRecord> toInsert = new ArrayList<>();
      List<QRecord> toUpdate = new ArrayList<>();
      List<QRecord> toDeactivate = new ArrayList<>();

      for(QRecord source : sourceRecords)
      {
         String key = source.getValueString(naturalKeyField);
         QRecord existing = existingByKey.remove(key);

         if(existing == null)
         {
            toInsert.add(source);
         }
         else if(hasChanges(source, existing))
         {
            source.setValue("id", existing.getValue("id"));
            toUpdate.add(source);
         }
      }

      // Remaining records no longer in source
      for(QRecord orphan : existingByKey.values())
      {
         orphan.setValue("isActive", false);
         toDeactivate.add(orphan);
      }

      // 4. Execute operations
      insertRecords(input, tableName, toInsert);
      updateRecords(input, tableName, toUpdate);
      updateRecords(input, tableName, toDeactivate);

      // 5. Log summary
      LOG.info("Sync complete",
         logPair("table", tableName),
         logPair("inserted", toInsert.size()),
         logPair("updated", toUpdate.size()),
         logPair("deactivated", toDeactivate.size()));
   }
}
```

### Data File Format

```json
[
   {
      "alpha2Code": "US",
      "alpha3Code": "USA",
      "name": "United States",
      "numericCode": 840
   },
   {
      "alpha2Code": "CA",
      "alpha3Code": "CAN",
      "name": "Canada",
      "numericCode": 124
   }
]
```

---

## Liquibase Generation

### Template File

Ship `src/main/resources/db/changelog-template.xml`:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
   http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.20.xsd">

   <!-- SECTION: country -->
   <changeSet id="${prefix}-create-country-v1" author="geo-qbit">
      <createTable tableName="${prefix}_country">
         <column name="id" type="INT" autoIncrement="true">
            <constraints primaryKey="true"/>
         </column>
         <column name="alpha2_code" type="VARCHAR(2)">
            <constraints nullable="false" unique="true"/>
         </column>
         <column name="alpha3_code" type="VARCHAR(3)"/>
         <column name="name" type="VARCHAR(100)">
            <constraints nullable="false"/>
         </column>
         <column name="is_active" type="BOOLEAN" defaultValueBoolean="true"/>
      </createTable>
   </changeSet>
   <!-- END SECTION: country -->

   <!-- SECTION: stateProvince -->
   <changeSet id="${prefix}-create-state-province-v1" author="geo-qbit">
      <createTable tableName="${prefix}_state_province">
         <column name="id" type="INT" autoIncrement="true">
            <constraints primaryKey="true"/>
         </column>
         <column name="country_id" type="INT">
            <constraints nullable="false"/>
         </column>
         <column name="code" type="VARCHAR(10)">
            <constraints nullable="false"/>
         </column>
         <column name="name" type="VARCHAR(100)">
            <constraints nullable="false"/>
         </column>
         <column name="is_active" type="BOOLEAN" defaultValueBoolean="true"/>
      </createTable>
      <addForeignKeyConstraint
         baseTableName="${prefix}_state_province"
         baseColumnNames="country_id"
         referencedTableName="${prefix}_country"
         referencedColumnNames="id"
         constraintName="${prefix}_fk_sp_country"/>
   </changeSet>
   <!-- END SECTION: stateProvince -->

</databaseChangeLog>
```

### Generator

```java
public class GeoLiquibaseGenerator
{
   public static void generate(GeoDataQBitConfig config, Path outputPath)
      throws IOException
   {
      String template = readResource("/db/changelog-template.xml");
      String prefix = config.getTableNamePrefix();

      if(prefix == null)
      {
         prefix = "geo";
      }

      // Substitute prefix
      String changelog = template.replace("${prefix}", prefix);

      // Remove disabled sections
      if(!Boolean.TRUE.equals(config.getEnableStateProvinces()))
      {
         changelog = removeSection(changelog, "stateProvince");
      }
      if(!Boolean.TRUE.equals(config.getEnableCities()))
      {
         changelog = removeSection(changelog, "city");
      }

      Files.writeString(outputPath, changelog);
   }

   private static String removeSection(String content, String sectionName)
   {
      String startMarker = "<!-- SECTION: " + sectionName + " -->";
      String endMarker = "<!-- END SECTION: " + sectionName + " -->";
      // Remove content between markers
      return content.replaceAll(
         "(?s)" + Pattern.quote(startMarker) + ".*?" + Pattern.quote(endMarker),
         "");
   }
}
```

### Host Application Integration

```java
// Generate changelog during build or setup
GeoLiquibaseGenerator.generate(
   new GeoDataQBitConfig()
      .withTableNamePrefix("shipping")
      .withEnableCities(true),
   Path.of("src/main/resources/db/generated/shipping-geo-changelog.xml"));
```

```xml
<!-- Host app's master-changelog.xml -->
<databaseChangeLog>
   <include file="db/app-changelog.xml"/>
   <include file="db/generated/shipping-geo-changelog.xml"/>
   <include file="db/generated/billing-geo-changelog.xml"/>
</databaseChangeLog>
```

---

## Best Practices

1. **Always use natural keys** for sync - enables upsert without duplicates
2. **Include `isActive` field** for soft deletes during sync
3. **Use table prefixes** when multi-instance is possible
4. **Ship changelog template** not final changelog
5. **Make cities optional** (large dataset ~150k records)
6. **Filter by country** for regional deployments
7. **Version data files** for reproducible syncs

---

## See Also

- [ARCHITECTURE.md](ARCHITECTURE.md) - Base class hierarchy and patterns
- [QBIT_TYPE_TAXONOMY.md](../QBIT_TYPE_TAXONOMY.md) - Type taxonomy
- [01-qbit-basics.md](01-qbit-basics.md) - Core QBit concepts
S½xsµæxešé# Application QBits

Application QBits are complete mini-applications that can be composed to build larger systems. Examples include WMS (Warehouse Management), CRM, Shipping, Inventory, and Newsletter systems.

## Structure

An application QBit includes:
- Multiple related entities
- Business processes
- Widgets and dashboards
- API endpoints (optional)
- Configuration options for customization

```
com.kingsrook.qbits.inventory/
â”œâ”€â”€ InventoryQBitConfig.java
â”œâ”€â”€ InventoryQBitProducer.java
â”œâ”€â”€ model/
â”‚   â”œâ”€â”€ Warehouse.java
â”‚   â”œâ”€â”€ Location.java
â”‚   â”œâ”€â”€ Item.java
â”‚   â”œâ”€â”€ StockLevel.java
â”‚   â””â”€â”€ StockMovement.java
â”œâ”€â”€ processes/
â”‚   â”œâ”€â”€ ReceiveStockProcessMetaDataProducer.java
â”‚   â”œâ”€â”€ ReceiveStockTransformStep.java
â”‚   â”œâ”€â”€ TransferStockProcessMetaDataProducer.java
â”‚   â””â”€â”€ TransferStockTransformStep.java
â”œâ”€â”€ widgets/
â”‚   â”œâ”€â”€ StockLevelWidgetMetaDataProducer.java
â”‚   â””â”€â”€ LowStockAlertWidgetMetaDataProducer.java
â”œâ”€â”€ customizers/
â”‚   â””â”€â”€ StockMovementTableCustomizer.java
â””â”€â”€ api/
    â””â”€â”€ InventoryApiMetaDataProducer.java
```

## Entity Relationships

Define parent-child relationships using annotations:

```java
@QMetaDataProducingEntity(
   producePossibleValueSource = true,
   childTables = {
      @ChildTable(
         childTableEntityClass = Location.class,
         joinFieldName = "warehouseId",
         childJoin = @ChildJoin(enabled = true)
      )
   }
)
public class Warehouse extends QRecordEntity
{
   public static final String TABLE_NAME = "warehouse";

   @QField(isPrimaryKey = true)
   private Integer id;

   @QField(isRequired = true, maxLength = 100)
   private String name;

   @QField(maxLength = 50)
   private String code;

   // Getters, setters, fluent setters...
}
```

## Processes

Create processes for business operations:

```java
public class ReceiveStockProcessMetaDataProducer implements MetaDataProducerInterface<QProcessMetaData>
{
   @Override
   public QProcessMetaData produce(QInstance qInstance)
   {
      return new QProcessMetaData()
         .withName("receiveStock")
         .withLabel("Receive Stock")
         .withTableName(StockMovement.TABLE_NAME)
         .withStepList(List.of(
            new QFrontendStepMetaData()
               .withName("input")
               .withLabel("Enter Receipt Details")
               .withFormFields(List.of("itemId", "locationId", "quantity")),
            new QBackendStepMetaData()
               .withName("process")
               .withCode(new QCodeReference(ReceiveStockTransformStep.class))
         ));
   }
}
```

## Configuration for Extensibility

Allow applications to customize behavior:

```java
public class InventoryQBitConfig implements QBitConfig
{
   private String backendName;

   // Feature flags
   private Boolean enableMultiWarehouse = true;
   private Boolean enableSerialNumbers = false;
   private Boolean enableBatchTracking = false;

   // Integration hooks
   private QCodeReference onStockReceived;
   private QCodeReference onStockTransferred;
   private QCodeReference onLowStockAlert;

   // Thresholds
   private Integer lowStockThreshold = 10;

   @Override
   public void validate(QInstance qInstance, List<String> errors)
   {
      if(backendName == null)
      {
         errors.add("backendName is required");
      }
   }

   // Getters, setters, fluent setters...
}
```

## Producer with Feature Flags

```java
@Override
public void produce(QInstance qInstance, String namespace) throws QException
{
   QBitMetaData qBitMetaData = new QBitMetaData()
      .withGroupId(GROUP_ID)
      .withArtifactId(ARTIFACT_ID)
      .withVersion(VERSION)
      .withNamespace(namespace)
      .withConfig(inventoryQBitConfig);

   qInstance.addQBit(qBitMetaData);

   List<MetaDataProducerInterface<?>> producers = MetaDataProducerHelper.findProducers(getClass().getPackageName());

   // Filter based on configuration
   if(!Boolean.TRUE.equals(inventoryQBitConfig.getEnableMultiWarehouse()))
   {
      producers.removeIf(p -> p.getSourceClass().equals(Warehouse.class));
   }

   if(!Boolean.TRUE.equals(inventoryQBitConfig.getEnableSerialNumbers()))
   {
      producers.removeIf(p -> p.getSourceClass().equals(SerialNumber.class));
   }

   finishProducing(qInstance, qBitMetaData, inventoryQBitConfig, producers);
}
```

## Application Usage

```java
// Basic usage
new InventoryQBitProducer()
   .withInventoryQBitConfig(new InventoryQBitConfig()
      .withBackendName("myBackend"))
   .produce(qInstance);

// Advanced usage with customization
new InventoryQBitProducer()
   .withInventoryQBitConfig(new InventoryQBitConfig()
      .withBackendName("myBackend")
      .withEnableSerialNumbers(true)
      .withEnableBatchTracking(true)
      .withLowStockThreshold(25)
      .withOnLowStockAlert(new QCodeReference(MyLowStockHandler.class)))
   .produce(qInstance);
```

## Composing Multiple QBits

Application QBits can be composed:

```java
// Build a complete system from QBits
new InventoryQBitProducer()
   .withInventoryQBitConfig(inventoryConfig)
   .produce(qInstance);

new ShippingQBitProducer()
   .withShippingQBitConfig(shippingConfig)
   .produce(qInstance);

new OrdersQBitProducer()
   .withOrdersQBitConfig(ordersConfig)
   .produce(qInstance);
```

## Best Practices

1. **Keep entities cohesive** - Group related entities in one QBit
2. **Use feature flags** - Allow applications to enable/disable features
3. **Provide extension hooks** - Let applications inject custom behavior
4. **Document dependencies** - If your QBit depends on another, document it
5. **Design for composition** - QBits should work together seamlessly
ö½¢³µxS¬ä# QQQ Extension Points Reference

This document provides a complete reference of QQQ's extension point interfaces that QBits can implement.

## Audit System

### AuditActionCustomizerInterface

**Location:** `com.kingsrook.qqq.backend.core.actions.audits`

**Registration:** Via `QInstance.addSupplementalCustomizer()`

```java
qInstance.addSupplementalCustomizer(
   AuditActionCustomizerInterface.CUSTOMIZER_TYPE,
   new QCodeReference(MyAuditCustomizer.class));
```

**Methods:**

| Method | Description |
|--------|-------------|
| `customizeInput(AuditSingleInput)` | Modify audit input before record creation |
| `customizeRecord(QRecord, AuditSingleInput)` | Modify audit record before insert |

**Use Cases:**
- Mask sensitive field values (PHI, PII)
- Add additional audit context
- Filter which changes are audited
- Route audits to external systems

## Security & Permissions

### CustomPermissionChecker

**Location:** `com.kingsrook.qqq.backend.core.actions.permissions`

**Registration:** Via `QPermissionRules.withCustomPermissionChecker()`

```java
table.withPermissionRules(new QPermissionRules()
   .withCustomPermissionChecker(new QCodeReference(MyChecker.class)));
```

**Methods:**

| Method | Description |
|--------|-------------|
| `checkPermissionsThrowing(AbstractActionInput, MetaDataWithPermissionRules)` | Throw if denied |
| `handlesBuildAvailablePermission()` | Return true if providing custom permissions |
| `buildAvailablePermission()` | Return AvailablePermission objects |

**Use Cases:**
- AWS IAM-style policy evaluation
- Attribute-based access control (ABAC)
- Dynamic permissions based on record data
- Integration with external auth systems

## Table Operations

### TableCustomizerInterface

**Location:** `com.kingsrook.qqq.backend.core.actions.customizers`

**Registration:** Per-table via metadata

```java
table.withCustomizer(TableCustomizerInterface.class,
   new QCodeReference(MyTableCustomizer.class));
```

**Methods:**

| Method | Description |
|--------|-------------|
| `postQuery(QueryOrGetInputInterface, List<QRecord>)` | After query results |
| `preInsert(InsertInput, List<QRecord>, boolean)` | Before insert |
| `postInsert(InsertInput, List<QRecord>)` | After insert |
| `preUpdate(UpdateInput, List<QRecord>, boolean, Optional<List<QRecord>>)` | Before update |
| `postUpdate(UpdateInput, List<QRecord>, Optional<List<QRecord>>)` | After update |
| `preDelete(DeleteInput, List<QRecord>, boolean)` | Before delete |
| `postDelete(DeleteInput, List<QRecord>)` | After delete |
| `whenToRunPreInsert()` | Control timing (default: AFTER_ALL_VALIDATIONS) |

**Use Cases:**
- Field validation beyond basic rules
- Auto-populate fields
- Trigger side effects (notifications, logging)
- Cascade operations to related records

## Instance Enrichment & Validation

### QInstanceEnricherPluginInterface

**Location:** `com.kingsrook.qqq.backend.core.instances`

**Registration:** Discovered automatically via classpath scanning

**Methods:**

| Method | Description |
|--------|-------------|
| `enrich(T object, QInstance)` | Add/modify metadata |
| `isEnabled()` | Whether plugin is active |
| `getPluginIdentifier()` | Unique identifier |

**Use Cases:**
- Add computed metadata based on configuration
- Inject default values into tables/fields
- Cross-reference validation

### QInstanceValidatorPluginInterface

**Location:** `com.kingsrook.qqq.backend.core.instances`

**Registration:** Discovered automatically via classpath scanning

**Methods:**

| Method | Description |
|--------|-------------|
| `validate(T object, QInstance, QInstanceValidator)` | Validate metadata |
| `isEnabled()` | Whether plugin is active |
| `getPluginIdentifier()` | Unique identifier |

**Use Cases:**
- Custom validation rules for your QBit's metadata
- Cross-QBit dependency validation
- Configuration consistency checks

## Supplemental Metadata

### QSupplementalFieldMetaData

**Location:** `com.kingsrook.qqq.backend.core.model.metadata.fields`

**Registration:** Per-field via `withSupplementalMetaData()`

```java
field.withSupplementalMetaData(new MyFieldMetaData().withOption(true));
```

**Abstract Methods:**

| Method | Description |
|--------|-------------|
| `getType()` | Unique identifier for this metadata type |

**Optional Override Methods:**

| Method | Description |
|--------|-------------|
| `includeInFrontendMetaData()` | Whether to send to frontend (default: false) |
| `enrich(QInstance, QFieldMetaData)` | Enrich during instance setup |
| `validate(QInstance, QFieldMetaData, QInstanceValidator)` | Validate configuration |

**Use Cases:**
- PHI/PII field marking
- Custom display options
- Field-level feature flags
- Integration metadata

### QSupplementalTableMetaData

**Location:** `com.kingsrook.qqq.backend.core.model.metadata.tables`

Similar pattern to QSupplementalFieldMetaData but for tables.

**Use Cases:**
- Table-level feature flags
- Custom caching configuration
- Integration settings

## Backend Modules

### QBackendModuleInterface

**Location:** `com.kingsrook.qqq.backend.core.modules`

**Registration:** Via QInstance backend configuration

**Methods:**

| Method | Description |
|--------|-------------|
| `getBackendType()` | Unique backend type name |
| `getQueryInterface()` | Query operation support |
| `getInsertInterface()` | Insert operation support |
| `getUpdateInterface()` | Update operation support |
| `getDeleteInterface()` | Delete operation support |
| `openTransaction()` | Transaction support |

**Use Cases:**
- Custom storage backends
- External API integrations
- Specialized data sources

## Metadata Production

### MetaDataProducerInterface<T>

**Location:** `com.kingsrook.qqq.backend.core.model.metadata`

**Registration:** Automatic via classpath scanning in QBit's package

**Methods:**

| Method | Description |
|--------|-------------|
| `T produce(QInstance)` | Produce metadata object |
| `getSortOrder()` | Production order (lower = earlier) |
| `isEnabled()` | Whether to produce |

**Use Cases:**
- Produce tables, processes, widgets, reports
- Dynamic metadata generation

### MetaDataCustomizerInterface<T>

**Location:** `com.kingsrook.qqq.backend.core.model.metadata`

**Registration:** Via QBitConfig or per-producer

**Methods:**

| Method | Description |
|--------|-------------|
| `T customizeMetaData(QInstance, T)` | Modify metadata after production |

**Use Cases:**
- Apply backend-specific settings
- Override default values
- Add security rules

## QBit-Specific

### QBitComponentMetaDataProducerInterface<T, C>

**Location:** `com.kingsrook.qqq.backend.core.model.metadata.qbits`

Extends MetaDataProducerInterface with QBitConfig access.

**Additional Methods:**

| Method | Description |
|--------|-------------|
| `C getQBitConfig()` | Access QBit configuration |
| `void setQBitConfig(C)` | Set configuration (called by framework) |

**Use Cases:**
- Access QBit config during metadata production
- Conditional metadata based on configuration
¸¾n®µ‚x% Úß# QBit Architecture

This document covers the core architecture patterns shared across all QBit types. For type-specific guidance, see the individual type documents.

## Base Class Hierarchy

### QBitConfig and QBitProducer

Every QBit has two core components:

| Component | Purpose |
|-----------|---------|
| `QBitConfig` | Holds configuration options; validates before production |
| `QBitProducer` | Entry point; produces metadata into QInstance |

```java
// Config validates and stores options
public class MyQBitConfig implements QBitConfig
{
   private String backendName;

   @Override
   public void validate(QInstance qInstance, List<String> errors) { ... }
}

// Producer creates and registers metadata
public class MyQBitProducer implements QBitProducer
{
   @Override
   public void produce(QInstance qInstance, String namespace) { ... }
}
```

### AbstractDataQBitConfig (Data QBits)

Base class for Data QBits providing prefix and backend management:

```java
public abstract class AbstractDataQBitConfig implements QBitConfig
{
   private String backendName;           // Required: target backend
   private String tableNamePrefix;       // Optional: "geo" -> "geo_country"

   public abstract List<String> getEnabledTableNames();

   @Override
   public String getDefaultBackendNameForTables()
   {
      return backendName;
   }

   public String applyPrefix(String tableName)
   {
      if(StringUtils.hasContent(tableNamePrefix))
      {
         return tableNamePrefix + "_" + tableName;
      }
      return tableName;
   }
}
```

### AbstractDataQBitProducer (Data QBits)

Base class handling metadata discovery, prefix application, and scope tracking:

```java
public abstract class AbstractDataQBitProducer<C extends AbstractDataQBitConfig>
   implements QBitProducer
{
   @Override
   public void produce(QInstance qInstance, String namespace) throws QException
   {
      C config = getConfig();

      // 1. Create QBit identity
      QBitMetaData qBitMetaData = createQBitMetaData(namespace, config);
      qInstance.addQBit(qBitMetaData);

      // 2. Discover all producers in package
      List<MetaDataProducerInterface<?>> producers =
         MetaDataProducerHelper.findProducers(getClass().getPackageName());

      // 3. Filter disabled tables
      producers.removeIf(p -> !isProducerEnabled(p, config));

      // 4. Produce with prefix and scope
      for(MetaDataProducerInterface<?> producer : producers)
      {
         MetaDataProducerOutput output = producer.produce(qInstance);

         // Apply prefix to table names
         if(output instanceof QTableMetaData table)
         {
            table.setName(config.applyPrefix(table.getName()));
         }

         // Mark scope
         if(output instanceof SourceQBitAware sqa)
         {
            sqa.setSourceQBitName(qBitMetaData.getName());
         }

         output.addSelfToInstance(qInstance);
      }
   }

   protected abstract C getConfig();
   protected abstract QBitMetaData createQBitMetaData(String namespace, C config);
   protected abstract boolean isProducerEnabled(MetaDataProducerInterface<?> p, C config);
}
```

---

## Namespace and Scope Management

### Namespace

The namespace parameter in `produce(qInstance, namespace)` identifies a specific instance of a QBit. It's used when:

1. **Multiple instances** of the same QBit exist in one application
2. **QBit-to-QBit references** need to be resolved
3. **Admin UI** needs to filter by QBit source

```java
// Two geo instances with different namespaces
new GeoDataQBitProducer()
   .withConfig(config.withTableNamePrefix("shipping"))
   .produce(qInstance, "shipping-geo");

new GeoDataQBitProducer()
   .withConfig(config.withTableNamePrefix("billing"))
   .produce(qInstance, "billing-geo");
```

### Scope via SourceQBitAware

The `SourceQBitAware` interface marks metadata with its originating QBit:

```java
public interface SourceQBitAware
{
   String getSourceQBitName();
   void setSourceQBitName(String name);
}
```

**Implementing types:**
- `QTableMetaData`
- `QProcessMetaData`
- `QPossibleValueSource`
- `QWidgetMetaData`

**Use cases:**
- Query all tables belonging to a specific QBit
- Show QBit source in admin UI
- Dependency analysis between QBits

---

## Inter-QBit Dependencies

### Pattern 1: Maven Dependency

Classpath-level dependency for compile-time access:

```xml
<dependency>
   <groupId>com.kingsrook.qbits</groupId>
   <artifactId>qbit-geo-data</artifactId>
   <version>1.0.0</version>
</dependency>
```

### Pattern 2: Config Validation

Runtime validation that required components exist:

```java
@Override
public void validate(QInstance qInstance, List<String> errors)
{
   // Ensure geo QBit is loaded first
   if(qInstance.getTable("country") == null)
   {
      errors.add("geo-data QBit must be loaded before oms QBit");
   }
}
```

### Pattern 3: Namespace References

Config stores namespace of dependent QBit for cross-references:

```java
public class OMSQBitConfig implements QBitConfig
{
   private String geoQBitNamespace;  // e.g., "shipping-geo"

   // When building FK, reference prefixed table:
   // geoNamespace + "_country" -> "shipping_geo_country"
}
```

---

## Data Versioning and Updates

### Sync Process Pattern

Data QBits use a sync process to load and update reference data:

```
Source Data (JSON) --> Sync Process --> Database Tables
                           |
                           v
                    [Compare by natural key]
                           |
         +-----------------+------------------+
         |                 |                  |
      Insert           Update            Deactivate
    (new keys)    (changed values)    (removed keys)
```

### Natural Key Design

Each table defines a natural key for upsert matching:

| Table | Natural Key | Example |
|-------|-------------|---------|
| country | `alpha2Code` | "US", "CA", "MX" |
| stateProvince | `countryId` + `code` | (1, "CA"), (1, "TX") |
| city | `stateProvinceId` + `name` | (5, "Los Angeles") |

### Data File Format

Reference data ships as JSON in classpath resources:

```json
[
   {
      "alpha2Code": "US",
      "alpha3Code": "USA",
      "name": "United States",
      "numericCode": 840
   },
   {
      "alpha2Code": "CA",
      "alpha3Code": "CAN",
      "name": "Canada",
      "numericCode": 124
   }
]
```

---

## Liquibase Integration

### Template-Based Generation

Data QBits ship a template changelog; host apps generate final changelogs:

```
changelog-template.xml  -->  LiquibaseGenerator  -->  shipping-geo-changelog.xml
       +                          +                         |
  ${prefix} tokens        GeoDataQBitConfig          Host app includes
                          (prefix="shipping")
```

### Changeset ID Convention

Use prefix in changeset IDs to avoid collisions:

```xml
<changeSet id="${prefix}-create-country-v1" author="geo-qbit">
   <createTable tableName="${prefix}_country">
      ...
   </createTable>
</changeSet>
```

### Host Application Integration

```xml
<!-- Host app's master-changelog.xml -->
<databaseChangeLog>
   <!-- App's own tables -->
   <include file="db/app-changelog.xml"/>

   <!-- Generated QBit changelogs -->
   <include file="db/generated/shipping-geo-changelog.xml"/>
   <include file="db/generated/billing-geo-changelog.xml"/>
</databaseChangeLog>
```

---

## Type Comparison

| Aspect | Extension | Data | Application |
|--------|-----------|------|-------------|
| Base classes | `QBitConfig`, `QBitProducer` | `AbstractDataQBitConfig`, `AbstractDataQBitProducer` | `QBitConfig`, `QBitProducer` |
| Table prefix | N/A | Required pattern | Optional |
| Multi-instance | Rare | Common | Possible |
| QAppSection | No | Optional | Required |
| Liquibase | Minimal/none | Template generator | Standard |
| Data sync | N/A | Core feature | N/A |

---

## See Also

- [01-qbit-basics.md](01-qbit-basics.md) - Core concepts
- [02-extension-patterns.md](02-extension-patterns.md) - Extension QBits
- [03-data-qbits.md](03-data-qbits.md) - Data QBits
- [04-application-qbits.md](04-application-qbits.md) - Application QBits
- [QBIT_TYPE_TAXONOMY.md](../QBIT_TYPE_TAXONOMY.md) - Type taxonomy and architecture patterns
³2JQ·ÕxW¨ò<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ QQQ - Low-code Application Framework for Engineers.
  ~ Copyright (C) 2021-2025.  Kingsrook, LLC
  ~ 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
  ~ contact@kingsrook.com
  ~ https://github.com/Kingsrook/
  ~
  ~ This program is free software: you can redistribute it and/or modify
  ~ it under the terms of the GNU Affero General Public License as
  ~ published by the Free Software Foundation, either version 3 of the
  ~ License, or (at your option) any later version.
  ~
  ~ This program is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
  ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  ~ GNU Affero General Public License for more details.
  ~
  ~ You should have received a copy of the GNU Affero General Public License
  ~ along with this program.  If not, see <https://www.gnu.org/licenses/>.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <properties>
      <revision>0.1.0-SNAPSHOT</revision>
   </properties>

   <parent>
      <groupId>com.kingsrook</groupId>
      <artifactId>qbit-build-parent</artifactId>
      <version>1.4.0</version>
   </parent>

   <groupId>com.kingsrook.qbits</groupId>
   <artifactId>qbit-todo</artifactId>
   <version>${revision}</version>
   <packaging>jar</packaging>

   <name>QBit Todo</name>
   <description>A QBit for the QQQ framework</description>
   <url>https://github.com/qrun-io/qbit-todo</url>

   <modelVersion>4.0.0</modelVersion>

   <licenses>
      <license>
         <name>GNU Affero General Public License v3.0</name>
         <url>https://www.gnu.org/licenses/agpl-3.0.html</url>
         <distribution>repo</distribution>
      </license>
   </licenses>

   <developers>
      <developer>
         <id>kingsrook</id>
         <name>Kingsrook Team</name>
         <email>contact@kingsrook.com</email>
         <organization>Kingsrook, LLC</organization>
         <organizationUrl>https://kingsrook.com</organizationUrl>
      </developer>
   </developers>

   <scm>
      <connection>scm:git:git://github.com/qrun-io/qbit-todo.git</connection>
      <developerConnection>scm:git:ssh://github.com:qrun-io/qbit-todo.git</developerConnection>
      <url>https://github.com/qrun-io/qbit-todo</url>
      <tag>HEAD</tag>
   </scm>

   <dependencies>
      <dependency>
         <groupId>com.kingsrook.qqq</groupId>
         <artifactId>qqq-backend-core</artifactId>
      </dependency>

      <dependency>
         <groupId>com.kingsrook.qqq</groupId>
         <artifactId>qqq-backend-module-rdbms</artifactId>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>com.h2database</groupId>
         <artifactId>h2</artifactId>
         <version>2.2.220</version>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>org.junit.jupiter</groupId>
         <artifactId>junit-jupiter</artifactId>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>org.assertj</groupId>
         <artifactId>assertj-core</artifactId>
         <version>3.27.3</version>
         <scope>test</scope>
      </dependency>
   </dependencies>

</project>
’Ò>¡x1 Îÿ100644 customize_template.py Ž¡hÒ»æRY@éêÏ)aôäLÆŒo»ªx«Tå#!/usr/bin/env python3
"""
Customize the QBit template:
 - Set your QBit name (e.g., "my-feature" or "MyFeature")
 - Set groupId / artifactId
 - Move source folders to the new package path
 - Rename classes

This is intended for one-time use right after cloning.

Usage:
    python3 scripts/customize_template.py

Or make executable and run:
    chmod +x scripts/customize_template.py
    ./scripts/customize_template.py
"""

import re
import shutil
from pathlib import Path


def prompt(msg: str, default: str) -> str:
    val = input(f"{msg} [{default}]: ").strip()
    return val or default


def to_pascal_case(name: str) -> str:
    """Convert 'my-qbit' or 'my_qbit' to 'MyQbit'"""
    words = re.split(r'[-_\s]+', name)
    return ''.join(word.capitalize() for word in words)


def to_camel_case(name: str) -> str:
    """Convert 'my-qbit' or 'MyQbit' to 'myQbit'"""
    pascal = to_pascal_case(name)
    return pascal[0].lower() + pascal[1:] if pascal else ''


def to_kebab_case(name: str) -> str:
    """Convert 'MyQbit' or 'my_qbit' to 'my-qbit'"""
    # Handle PascalCase
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', name)
    s2 = re.sub('([a-z0-9])([A-Z])', r'\1-\2', s1)
    return s2.lower().replace('_', '-').replace(' ', '-')


def to_package_name(name: str) -> str:
    """Convert 'my-qbit' to 'myqbit' (no separators, lowercase)"""
    return re.sub(r'[-_\s]+', '', name).lower()


def replace_in_files(files, replacements):
    for file in files:
        if not file.exists():
            continue
        try:
            text = file.read_text(encoding="utf-8")
        except UnicodeDecodeError:
            continue  # Skip binary files
        changed = text
        for old, new in replacements.items():
            changed = changed.replace(old, new)
        if changed != text:
            file.write_text(changed, encoding="utf-8")
            print(f"  Updated: {file}")


def main():
    repo = Path(__file__).resolve().parents[1]
    pom = repo / "pom.xml"
    if not pom.exists():
        raise SystemExit("Run from the template repo; pom.xml not found.")

    print("=" * 60)
    print("QBit Template Customization")
    print("=" * 60)
    print()
    print("This script will rename the template to match your QBit name.")
    print("Enter your QBit name in any format (e.g., 'my-feature', 'MyFeature').")
    print()

    # Get QBit name
    qbit_name = prompt("QBit name", "my-qbit")

    # Derive various forms
    kebab_name = to_kebab_case(qbit_name)
    pascal_name = to_pascal_case(qbit_name)
    camel_name = to_camel_case(qbit_name)
    package_name = to_package_name(qbit_name)

    print()
    print(f"Derived names:")
    print(f"  kebab-case:  {kebab_name}")
    print(f"  PascalCase:  {pascal_name}")
    print(f"  camelCase:   {camel_name}")
    print(f"  package:     {package_name}")
    print()

    # Get Maven coordinates
    group_id = prompt("Maven groupId", "com.kingsrook.qbits")
    artifact_id = prompt("Maven artifactId", f"qbit-{kebab_name}")

    # Get GitHub org
    github_org = prompt("GitHub organization", "qrun-io")

    print()
    print("Configuration:")
    print(f"  groupId:     {group_id}")
    print(f"  artifactId:  {artifact_id}")
    print(f"  GitHub:      {github_org}/{artifact_id}")
    print()

    confirm = input("Proceed with customization? [Y/n]: ").strip().lower()
    if confirm == 'n':
        print("Aborted.")
        return

    # Old values (from template)
    old_package = "com.kingsrook.qbits.todo"
    old_package_path = Path("com/kingsrook/qbits/todo")
    new_package = f"{group_id}.{package_name}"
    new_package_path = Path(*new_package.split("."))

    # Move Java sources to the new package path
    print()
    print("Moving source files...")
    for src_root in ["src/main/java", "src/test/java"]:
        src_dir = repo / src_root / old_package_path
        if src_dir.exists():
            dst_dir = repo / src_root / new_package_path
            dst_dir.parent.mkdir(parents=True, exist_ok=True)
            shutil.move(str(src_dir), str(dst_dir))
            print(f"  Moved: {src_root}/{old_package_path} -> {src_root}/{new_package_path}")
            # Remove empty parent dirs
            try:
                (repo / src_root / "com/kingsrook/qbits").rmdir()
                (repo / src_root / "com/kingsrook").rmdir()
                (repo / src_root / "com").rmdir()
            except OSError:
                pass  # Dir not empty, that's fine

    # Rename Java files
    print()
    print("Renaming Java files...")
    for src_root in ["src/main/java", "src/test/java"]:
        new_dir = repo / src_root / new_package_path
        if new_dir.exists():
            for java_file in new_dir.glob("Todo*.java"):
                new_name = java_file.name.replace("Todo", pascal_name)
                new_path = java_file.parent / new_name
                java_file.rename(new_path)
                print(f"  Renamed: {java_file.name} -> {new_name}")

    # Collect all files to update
    java_files = list((repo / "src").rglob("*.java"))
    xml_files = [repo / "pom.xml"]
    md_files = list(repo.glob("*.md")) + list((repo / "docs").rglob("*.md"))
    yml_files = list(repo.rglob("*.yml")) + list(repo.rglob("*.yaml"))
    all_files = java_files + xml_files + md_files + yml_files

    # Define replacements
    replacements = {
        # Package
        f"package {old_package}": f"package {new_package}",
        f"import {old_package}.": f"import {new_package}.",
        old_package: new_package,

        # Class names
        "TodoQBitConfig": f"{pascal_name}QBitConfig",
        "TodoQBitProducer": f"{pascal_name}QBitProducer",
        "todoQBitConfig": f"{camel_name}QBitConfig",
        "Todo QBit": f"{pascal_name} QBit",
        "Todo": pascal_name,  # Catch-all for remaining references

        # Maven coordinates
        "<artifactId>qbit-todo</artifactId>": f"<artifactId>{artifact_id}</artifactId>",
        "<name>QBit Todo</name>": f"<name>QBit {pascal_name}</name>",
        "qbit-todo": artifact_id,

        # GitHub URLs
        "qrun-io/qbit-todo": f"{github_org}/{artifact_id}",
        "github.com/qrun-io/qbit-todo": f"github.com/{github_org}/{artifact_id}",
    }

    print()
    print("Updating file contents...")
    replace_in_files(all_files, replacements)

    print()
    print("=" * 60)
    print("Customization complete!")
    print("=" * 60)
    print()
    print(f"  Package:     {new_package}")
    print(f"  groupId:     {group_id}")
    print(f"  artifactId:  {artifact_id}")
    print(f"  GitHub:      {github_org}/{artifact_id}")
    print()
    print("Next steps:")
    print("  1. Review the changes: git diff")
    print("  2. Build the project:  mvn clean package")
    print("  3. Commit your changes")
    print()


if __name__ == "__main__":
    main()
gß2�®x> Áÿ40000 main Ì¤1+&bNÆ
â…wøÈ¡Í¢40000 test ‚œŸ¥MÓqF’ÒŸj�ƒh6¸7_¯x àÿ40000 java –UÄÚ°¦bUæí¶�sÀ^3	ÊÀˆ&®x áÿ40000 com Î‡S5làã²L¢¾‡”"*AïœŒ¤x$ Ûÿ40000 kingsrook ÷�+é;êSFñßÊŠ¸à#öD§ü7 x  ßÿ40000 qbits ÏRe»/Âýñš‚Wø�·qIº´ÿ¯x àÿ40000 todo ÊŽ‘ïWˆlEˆÑ”G®#òê1QíµÌ‡ x€ ÿ100644 TodoQBitConfig.java ,�’WýI‚Ù=§NÖ»ÑvPójó100644 TodoQBitProducer.java V“HùýJ¹²�¿�d…Fæ®ÄLµ40000 model %þÐªžs:â�]�)Õ”§çøÁ-6µ¤xEºå/*
 * QQQ - Low-code Application Framework for Engineers.
 * Copyright (C) 2021-2025.  Kingsrook, LLC
 * 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
 * contact@kingsrook.com
 * https://github.com/Kingsrook/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package com.kingsrook.qbits.todo;


import java.util.List;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerHelper;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerInterface;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitProducer;


/*******************************************************************************
 ** Producer class for the Todo QBit.
 **
 ** The QBitProducer is the entry point for a QBit. When an application wants to
 ** use your QBit, they create an instance of this producer, configure it, and
 ** call produce() to add the QBit's metadata to their QInstance.
 **
 ** Example usage in an application:
 ** <pre>
 ** new TodoQBitProducer()
 **    .withTodoQBitConfig(new TodoQBitConfig()
 **       .withBackendName("myBackend")
 **       .withSomeFeatureEnabled(true))
 **    .produce(qInstance);
 ** </pre>
 **
 ** See docs/01-qbit-basics.md for more details on QBitProducer.
 *******************************************************************************/
public class TodoQBitProducer implements QBitProducer
{
   /////////////////////////////////////////////////////////////////////////////
   // Maven-style coordinates for this QBit. These uniquely identify the     //
   // QBit and are used for versioning, dependency management, and display.  //
   /////////////////////////////////////////////////////////////////////////////
   public static final String GROUP_ID    = "com.kingsrook.qbits";
   public static final String ARTIFACT_ID = "todo";
   public static final String VERSION     = "0.1.0";

   private TodoQBitConfig todoQBitConfig;



   /*******************************************************************************
    ** Produce the QBit's metadata and add it to the QInstance.
    **
    ** This method:
    ** 1. Creates QBitMetaData with Maven-style identification
    ** 2. Registers the QBit with the QInstance
    ** 3. Discovers and produces all component metadata (tables, processes, etc.)
    ** 4. Applies configuration and customizations
    **
    ** @param qInstance the QInstance to add metadata to
    ** @param namespace optional namespace for multiple instances of this QBit
    *******************************************************************************/
   @Override
   public void produce(QInstance qInstance, String namespace) throws QException
   {
      //////////////////////////////////////////////////////////////////////////
      // Create QBitMetaData - this identifies the QBit and stores its config //
      //////////////////////////////////////////////////////////////////////////
      QBitMetaData qBitMetaData = new QBitMetaData()
         .withGroupId(GROUP_ID)
         .withArtifactId(ARTIFACT_ID)
         .withVersion(VERSION)
         .withNamespace(namespace)
         .withConfig(todoQBitConfig);

      ////////////////////////////////////
      // Register the QBit with QInstance //
      ////////////////////////////////////
      qInstance.addQBit(qBitMetaData);

      //////////////////////////////////////////////////////////////////////////
      // Find all MetaDataProducers in this package (entities, processes, etc.) //
      // MetaDataProducerHelper scans for:                                      //
      //   - Classes implementing MetaDataProducerInterface                     //
      //   - Classes annotated with @QMetaDataProducingEntity                   //
      //   - Classes annotated with @QMetaDataProducingPossibleValueEnum        //
      //////////////////////////////////////////////////////////////////////////
      List<MetaDataProducerInterface<?>> producers = MetaDataProducerHelper.findProducers(getClass().getPackageName());

      //////////////////////////////////////////////////////////////////////////
      // Example: Conditionally filter producers based on configuration       //
      // Uncomment and modify as needed                                        //
      //////////////////////////////////////////////////////////////////////////
      // if(!Boolean.TRUE.equals(todoQBitConfig.getSomeFeatureEnabled()))
      // {
      //    producers.removeIf(p -> p.getSourceClass().equals(SomeOptionalEntity.class));
      // }

      //////////////////////////////////////////////////////////////////////////
      // Finish producing - this processes all discovered producers and       //
      // applies the QBit's configuration to produced metadata                //
      //////////////////////////////////////////////////////////////////////////
      finishProducing(qInstance, qBitMetaData, todoQBitConfig, producers);
   }



   /*******************************************************************************
    ** Getter for todoQBitConfig
    *******************************************************************************/
   public TodoQBitConfig getTodoQBitConfig()
   {
      return (this.todoQBitConfig);
   }



   /*******************************************************************************
    ** Setter for todoQBitConfig
    *******************************************************************************/
   public void setTodoQBitConfig(TodoQBitConfig todoQBitConfig)
   {
      this.todoQBitConfig = todoQBitConfig;
   }



   /*******************************************************************************
    ** Fluent setter for todoQBitConfig
    *******************************************************************************/
   public TodoQBitProducer withTodoQBitConfig(TodoQBitConfig todoQBitConfig)
   {
      this.todoQBitConfig = todoQBitConfig;
      return (this);
   }

}
OÆi}ãç³SxsŒñÅ4ó=°ì“O“Õ@%producers.MetaDataCustomizerInterface“7“^
Config“7tables.QTableMetaData“pYConfiguration“Ñ"QBitConfig provides configuration options that control how the QBit behaves
 ** when it is produced and at runtime. Configuration is validated during QBit
 ** production to catch errors early.
 **
 ** Common configuration patterns include:
 ** - Feature flags to enable/disable optional functionality
 ** - Backend names for where tables should be stored
 ** - Table customizers foTr modifying produced metadata
 ** - Integration settings (API keys, endpoints, etc.)“Æ<	Config.
 “M“ZConfig implements QBitConfig
{
“@M/
   // Example configuration field - the backend name for tables.           //
   // Applications can override this to store QBit tables in their backend //
“@M"/
   private String backendName;

“@MP/
   // Example feature flag - enable or disable optional functionality      //
“@M1/
   private Boolean someFeatureEnabled = true;

“@MQ/
   // Table customizer - allows applications to modify table metadata       //
“@MP/
   private MetaDataCustomizerInterface<QTableMetaData> tableMetaDataCustomizer“­
`Validate the configuration.
    **
    ** This method is called during QBit production. Add any validation logic here
    ** to? ensure the configuration is valid before the QBit is produced.“T.Sbeing configured
    ** @param errors list to add validation error messages to
    “M“5 7validate(QInstance qInstance, List<String> errors)
   {“q+“°&“m
=Example validation: require backendName if someFeatureEnabled“o2for your QBit's requirements“¿iBoolean.TRUE.equals(someFeatureEnabled) && backendName == null)
      // {
      //    errors.add("backendName is required when) someFeatureEnabled is true");
      // }“ÐdReturn the default backend name for tables produced by this QBit.
    **
    ** This tells QQQ which backend to use for storing_ data in the QBit's tables.
    ** Applications pass this value when configuring the QBit.
    “M“5LString getDefaultBackendNameForTables()
   {
      return (this.backendName)“Ïe“ÉbackendName
    “M“\<String getBackendName()
   {
      return (this.backendName)“ÏeSetter for backendName
    “M“\IBackendName(String backendName)
   {
      this.backendName = backendName“ÏwbackendName
    “M“\TodoQBitConfig withBackendName(String backendName)
   {
      this.backendName = backendName;
      return (this);
   }



   /“ÝW“ÉsomeFeatureEnabled
    “M“\KBoolean getSomeFeatureEnabled()
   {
      return (this.someFeatureEnabled)“Ïe"Setter for someFeatureEnabled
    “M“\fSomeFeatureEnabled(Boolean someFeatureEnabled)
   {
      this.someFeatureEnabled = someFeatureEnabled“ÏwsomeFeatureEnabled
    “M“\TodoQBitConfig withSomeFeatureEnabled(Boolean someFeatureEnabled)
   {
      this.someFeatureEnabled = someFeatureEnabled;
      return (this)“Ïe“ÉableMetaDataCustomizer - overrides interface default.
    **
    ** Applications use this to customize table metadata during prWoduction,
    ** such as setting backend names or adding backend-specific details.
    “M“5MetaDataCustomizerInterface<QTableMetaData> getTableMetaDataCustomizer()
   {
      return (this.tableMetaDataCustomizer);
   }“Õ_'Setter for tableMetaDataCustomizer
    “M“\ableMetaDataCustomizer(MetaDataCustomizerInterface<QTableMetaData> tableMetaDataCustomizer)
   {
      this.tableMetaDataCustomizer = tableMetaDataCustomizer“ÏxableMetaDataCustomizer
    “M“\TodoQBitConfig withTableMetaDataCustomizer(MetaDataCustomizerInterface<QTableMetaData> tableMetaDataCustomizer)
   {
      this2.tableMetaDataCustomizer = tableMetaDataCustomizer“&éÈ®x. Ñÿ100644 ExampleEntity.java ¯‹ey¬eýpôH¨â£mpÝ6<:ƒ‚Ü²üxÂ=ð/*******************************************************************************
 ** Example entity demonstrating the QRecordEntity pattern.
 **
 ** This is a placeholder entity - replace or remove it when customizing your QBit.
 *******************************************************************************/
package com.kingsrook.qbits.todo.model;


import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.producers.annotations.QMetaDataProducingEntity;


/*******************************************************************************
 ** Example entity for the Todo QBit.
 **
 ** Replace this with your own entities or delete if building an extension QBit.
 *******************************************************************************/
@QMetaDataProducingEntity(produceTableMetaData = true, producePossibleValueSource = true)
public class ExampleEntity extends QRecordEntity
{
   public static final String TABLE_NAME = "example";

   @QField(isPrimaryKey = true)
   private Integer id;

   @QField(isRequired = true, maxLength = 100, label = "Name")
   private String name;

   @QField(maxLength = 500, label = "Description")
   private String description;



   /***************************************************************************
    ** Default constructor
    ***************************************************************************/
   public ExampleEntity()
   {
   }



   /***************************************************************************
    ** Getter for id
    ***************************************************************************/
   public Integer getId()
   {
      return id;
   }



   /***************************************************************************
    ** Setter for id
    ***************************************************************************/
   public void setId(Integer id)
   {
      this.id = id;
   }



   /***************************************************************************
    ** Fluent setter for id
    ***************************************************************************/
   public ExampleEntity withId(Integer id)
   {
      this.id = id;
      return this;
   }



   /***************************************************************************
    ** Getter for name
    ***************************************************************************/
   public String getName()
   {
      return name;
   }



   /***************************************************************************
    ** Setter for name
    ***************************************************************************/
   public void setName(String name)
   {
      this.name = name;
   }



   /***************************************************************************
    ** Fluent setter for name
    ***************************************************************************/
   public ExampleEntity withName(String name)
   {
      this.name = name;
      return this;
   }



   /***************************************************************************
    ** Getter for description
    ***************************************************************************/
   public String getDescription()
   {
      return description;
   }



   /***************************************************************************
    ** Setter for description
    ***************************************************************************/
   public void setDescription(String description)
   {
      this.description = description;
   }



   /***************************************************************************
    ** Fluent setter for description
    ***************************************************************************/
   public ExampleEntity withDescription(String description)
   {
      this.description = description;
      return this;
   }

}
o¼Þ,¯x àÿ40000 java Jwas�=;Ä{ŸM*4 Ô´>¨ÿ¡Ÿ®x áÿ40000 com ÓšSG¤“8õgx;€�[ ‡X	”¤x$ Ûÿ40000 kingsrook o¼24�ûa¯Ú[ ®w¯.ëm:Êë{Ò x  ßÿ40000 qbits áwéî^Ù´C�†�™fŒæ¢ sÇÔ!¿¯x àÿ40000 todo è¤×Ÿë:_:—*×tÕÚ	\"ýºòñ©x) Öÿ100644 BaseTest.java ß×õŒ‘Ø\°�ûicU„ˆƒXi<— ´Ïxôë/*
 * QQQ - Low-code Application Framework for Engineers.
 * Copyright (C) 2021-2025.  Kingsrook, LLC
 * 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
 * contact@kingsrook.com
 * https://github.com/Kingsrook/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package com.kingsrook.qbits.todo;


import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.instances.QInstanceValidator;
import com.kingsrook.qqq.backend.core.model.metadata.QAuthenticationType;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.authentication.QAuthenticationMetaData;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryRecordStore;
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSBackendMetaData;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;


/*******************************************************************************
 ** Base test class for Todo QBit tests.
 **
 ** This class sets up the QInstance with the QBit for each test. Extend this
 ** class when writing tests that need the QBit's metadata available.
 **
 ** For QBits with database tables, you may want to add database priming logic
 ** using the RDBMS backend. See docs/01-qbit-basics.md for examples.
 *******************************************************************************/
public class BaseTest
{
   public static final String BACKEND_NAME = "testBackend";



   /*******************************************************************************
    ** Set up the QInstance with the QBit before each test.
    *******************************************************************************/
   @BeforeEach
   void baseBeforeEach() throws Exception
   {
      QInstance qInstance = defineQInstance();
      new QInstanceValidator().validate(qInstance);
      QContext.init(qInstance, new QSession());

      MemoryRecordStore.fullReset();
   }



   /*******************************************************************************
    ** Define the QInstance with the QBit.
    **
    ** This creates a minimal QInstance with:
    ** - Anonymous authentication (for testing)
    ** - An H2 in-memory database backend
    ** - The Todo QBit produced with default configuration
    **
    ** Customize this method as your QBit grows to include entities and processes.
    *******************************************************************************/
   protected QInstance defineQInstance() throws QException
   {
      QInstance qInstance = new QInstance();

      //////////////////////////////////////////////
      // Set up anonymous authentication for tests //
      //////////////////////////////////////////////
      qInstance.setAuthentication(new QAuthenticationMetaData()
         .withType(QAuthenticationType.FULLY_ANONYMOUS));

      ///////////////////////////////////
      // Add an H2 in-memory backend   //
      ///////////////////////////////////
      qInstance.addBackend(new RDBMSBackendMetaData()
         .withName(BACKEND_NAME)
         .withVendor("h2")
         .withHostName("mem")
         .withDatabaseName("test_database")
         .withUsername("sa"));

      ////////////////////////////////
      // Configure and produce QBit //
      ////////////////////////////////
      TodoQBitConfig config = new TodoQBitConfig()
         .withBackendName(BACKEND_NAME)
         .withSomeFeatureEnabled(true)
         .withTableMetaDataCustomizer((qInstance1, table) ->
         {
            if(table.getBackendName() == null)
            {
               table.setBackendName(BACKEND_NAME);
            }
            return (table);
         });

      new TodoQBitProducer()
         .withTodoQBitConfig(config)
         .produce(qInstance);

      return qInstance;
   }



   /*******************************************************************************
    ** Basic test to verify the QBit produces successfully.
    *******************************************************************************/
   @Test
   void testQBitProduces() throws QException
   {
      ///////////////////////////////////////////////////////
      // Verify the QBit was registered with the QInstance //
      ///////////////////////////////////////////////////////
      assertThat(QContext.getQInstance().getQBits()).isNotEmpty();
      assertThat(QContext.getQInstance().getQBits()).containsKey(
         TodoQBitProducer.GROUP_ID + ":" + TodoQBitProducer.ARTIFACT_ID);
   }

}
˜n)U¼�xÜ#÷# QBit Template

[![License](https://img.shields.io/badge/license-GNU%20Affero%20GPL%20v3-green.svg)](https://www.gnu.org/licenses/agpl-3.0.en.html)
[![Java](https://img.shields.io/badge/java-17+-blue.svg)](https://adoptium.net/)

> GitHub template repository for creating QBits for the QQQ framework

## Quick Start

1. **Use this template** - Click "Use this template" on GitHub
2. **Customize** - Run `python3 scripts/customize_template.py`
3. **Build** - Run `mvn clean package`

## What is a QBit?

QBits are modular, reusable components for QQQ applications:

| Type | Purpose | Examples |
|------|---------|----------|
| **Extension** | Extend QQQ functionality | Audit customization, custom auth, PHI masking |
| **Data** | Provide reference data | Countries, currencies, time zones |
| **Application** | Complete mini-apps | WMS, CRM, Inventory, Shipping |

## Documentation

- [Getting Started](docs/00-getting-started.md) - Setup and customization
- [QBit Basics](docs/01-qbit-basics.md) - Producer, Config, and entities
- [Extension Patterns](docs/02-extension-patterns.md) - Hooks and customizers
- [Data QBits](docs/03-data-qbits.md) - Reference data patterns
- [Application QBits](docs/04-application-qbits.md) - Full applications
- [Extension Points](docs/05-existing-extension-points.md) - Complete reference

## Project Structure

```
qbit-your-name/
â”œâ”€â”€ src/main/java/com/kingsrook/qbits/yourname/
â”‚   â”œâ”€â”€ YourNameQBitConfig.java    # Configuration
â”‚   â””â”€â”€ YourNameQBitProducer.java  # Entry point
â”œâ”€â”€ src/test/java/...
â”‚   â””â”€â”€ BaseTest.java              # Test base class
â”œâ”€â”€ docs/                          # Documentation
â”œâ”€â”€ scripts/customize_template.py  # Setup script
â””â”€â”€ pom.xml
```

## Usage in Applications

```java
new MyQBitProducer()
   .withMyQBitConfig(new MyQBitConfig()
      .withBackendName("myBackend")
      .withSomeOption(true))
   .produce(qInstance);
```

## Requirements

- Java 17+
- Maven 3.8+
- QQQ framework knowledge

## License

GNU Affero General Public License v3.0 - see [LICENSE](LICENSE)

## Resources

- [QQQ Framework](https://github.com/Kingsrook/qqq)
- [QQQ Wiki](https://github.com/Kingsrook/qqq/wiki)
- [Issues](https://github.com/Kingsrook/qqq/issues)
ý!½îxíñ# Data QBits

Data QBits provide reusable reference data such as countries, currencies, time zones, or industry-specific lookup tables.

## Structure

A data QBit typically includes:
- Entity classes for the reference data
- Seed data files (CSV, JSON, or SQL)
- Optional data loading logic

```
com.kingsrook.qbits.countries/
â”œâ”€â”€ CountriesQBitConfig.java
â”œâ”€â”€ CountriesQBitProducer.java
â”œâ”€â”€ model/
â”‚   â””â”€â”€ Country.java
â”œâ”€â”€ loaders/
â”‚   â””â”€â”€ CountryDataSeeder.java
â””â”€â”€ resources/
    â””â”€â”€ data/
        â””â”€â”€ countries.csv
```

## Entity Definition

```java
@QMetaDataProducingEntity(producePossibleValueSource = true)
public class Country extends QRecordEntity
{
   public static final String TABLE_NAME = "country";

   @QField(isPrimaryKey = true, maxLength = 2)
   private String isoCode2;

   @QField(maxLength = 3)
   private String isoCode3;

   @QField(isRequired = true, maxLength = 100)
   private String name;

   @QField(maxLength = 50)
   private String region;

   // Getters, setters, fluent setters...
}
```

## Seed Data (CSV)

Create `src/main/resources/data/countries.csv`:

```csv
isoCode2,isoCode3,name,region
US,USA,United States,North America
CA,CAN,Canada,North America
MX,MEX,Mexico,North America
GB,GBR,United Kingdom,Europe
DE,DEU,Germany,Europe
FR,FRA,France,Europe
```

## Data Seeder

```java
public class CountryDataSeeder
{
   public void seedData(QInstance qInstance, String backendName) throws QException
   {
      InputStream csvStream = getClass().getResourceAsStream("/data/countries.csv");
      if(csvStream == null)
      {
         throw new QException("countries.csv not found");
      }

      List<QRecord> records = parseCsv(csvStream);

      InsertInput input = new InsertInput();
      input.setTableName(Country.TABLE_NAME);
      input.setRecords(records);

      new InsertAction().execute(input);
   }

   private List<QRecord> parseCsv(InputStream stream)
   {
      // Parse CSV and return QRecords
      // Use OpenCSV or similar library
   }
}
```

## Configuration Options

```java
public class CountriesQBitConfig implements QBitConfig
{
   private String backendName;
   private Boolean autoSeedOnStartup = false;
   private Boolean includeAllCountries = true;
   private List<String> regionsToInclude;  // Filter by region

   @Override
   public void validate(QInstance qInstance, List<String> errors)
   {
      if(autoSeedOnStartup && backendName == null)
      {
         errors.add("backendName required when autoSeedOnStartup is true");
      }
   }

   // Getters, setters, fluent setters...
}
```

## Producer with Seeding

```java
@Override
public void produce(QInstance qInstance, String namespace) throws QException
{
   // ... standard QBit production ...

   // Optionally seed data after production
   if(Boolean.TRUE.equals(countriesQBitConfig.getAutoSeedOnStartup()))
   {
      // Register a post-startup action or use a process
      // Note: Seeding should typically be done by the application,
      // not automatically, to avoid duplicate data on restart
   }
}
```

## Application Usage

```java
// Use the QBit with auto-seed disabled (default)
new CountriesQBitProducer()
   .withCountriesQBitConfig(new CountriesQBitConfig()
      .withBackendName("myBackend"))
   .produce(qInstance);

// Application seeds data during setup/migration
new CountryDataSeeder().seedData(qInstance, "myBackend");
```

## Best Practices

1. **Don't auto-seed by default** - Let applications control when data is seeded
2. **Provide upsert logic** - Handle re-seeding without duplicates
3. **Version your data** - Include data version in config or resources
4. **Support filtering** - Let applications include only the data they need
5. **Use Possible Value Sources** - Enable dropdown selection in UI
‚mÓª¤Rì›CñabÍ.G”¤k³5Í›